i have this query in my code. i am trying to isert a image into table in the last column(blob). it is showing invalid hex number. can anybody help me out of this?
#ManagedBean(name="userprofile",eager=true)
#SessionScoped
public class Profile {
#ManagedProperty("#{jdbcTemplate}")
public JdbcTemplate jdbcTemplate;
private String firstName,lastName,email,description;
private UploadedFile photo1;
private int contactNumber;
private String insertQry;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public UploadedFile getPhoto1() {
return photo1;
}
public void setPhoto1(UploadedFile photo1) {
this.photo1 = photo1;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public void insertProfile() throws Exception{
InputStream is=photo1.getInputstream();
System.out.println(is);
insertQry="insert into profile
values('"+getFirstName()+"','"+getLastName()+"','"+getContactNumber()+"',
'"+getEmail()+"','"+getDescription()+"','"+utl_raw.cast_to_raw(is)+"')";
System.out.println(insertQry);
int num=jdbcTemplate.update(insertQry);
System.out.println(num);
}
}
any kind of response is appreciated in advance.
This error:
invalid hex number ora-01465
means that your not sending an Hexa.
Solution:
Please try to convert InputStream to Hexa before insert image.
Related
I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!
In my web app, I want to build a registration form within which I wish to list all properties of a user's contact information that can be edited and saved. However, when I run my code, I get following error.
Any help will be greatly appreciated as I am new and learning as I go.
2019-01-03 17:09:58.705 ERROR 12223 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [An exception occurred processing JSP page /WEB-INF/views/enrollment/view.jsp at line 382
org.springframework.beans.NotReadablePropertyException: Invalid property 'contact' of bean class [com.intelo.model.Enrollment]: Bean property 'contact' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Here is my view.jsp
<form:form id="editRegistration" action="/enrollment/action" modelAttribute="enrollment" method="post" enctype="multipart/form-data">
<input type="hidden" name="enrollmentId" value="${enrollment.id}">
...
<c:forEach items="${contacts}" var="contact">
<div class="form-group col-md-6">
<label class="control-label">First Name</label>
<form:input class="form-control" path="contact.firstName" disabled="${allowedActions.edit? 'false' : 'true'}"/>
</div>
</c:forEach>
Here is my EnrollmentControleller:
#GetMapping("/enrollment/view")
public String viewEnrollment(#ModelAttribute("enrollment") Enrollment enrollment, Model model,
#ModelAttribute("user") Member user)
{
StateManager stateManager = StateManager.getStateManager(enrollment);
model.addAttribute("hasActions", stateManager.allowedActions(user).size() > 0);
model.addAttribute("allowedActions", stateManager.allowedActionMap(user));
model.addAttribute("isAdministrator", stateManager.getRoleInContext(user).hasAdministratorPrivilege());
model.addAttribute("pageTitle", "View Enrollment");
RegistrationDetails registrationDetails = enrollment.getRegistrationDetails();
model.addAttribute("studentInformation", registrationDetails.getStudentInformation());
model.addAttribute("healthInformation", registrationDetails.getHealthInformation());
model.addAttribute("emergencyContact", registrationDetails.getEmergencyContact());
model.addAttribute("familyInformation", registrationDetails.getFamilyInformation());
model.addAttribute("schoolHistory", registrationDetails.getSchoolHistory());
model.addAttribute("contacts", registrationDetails.getContacts());
model.addAttribute("siblings", registrationDetails.getSiblings());
model.addAttribute("preferredSite", registrationDetails.getPreferredSite());
return "enrollment/view";
}
Enrollment class:
#Entity
#Table(name="enrollments")
#OnDelete(action = OnDeleteAction.CASCADE)
public class Enrollment extends ModelObject {
#JsonProperty("firstName")
private String firstName = "";
#JsonProperty("middleName")
private String middleName = "";
#JsonProperty("lastName")
private String lastName = "";
#JsonProperty("birthDate")
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate birthDate = LocalDate.now();
#JsonProperty("studentGrade")
private String studentGrade = null;
#JsonProperty("registrationDate")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate registrationDate = LocalDate.now();
#JsonIgnore
#OneToOne(fetch=FetchType.LAZY, mappedBy="enrollment", cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}, orphanRemoval=true)
#OnDelete(action = OnDeleteAction.CASCADE)
RegistrationDetails registrationDetails = null;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "programId")
private Program program = null;
#JsonIgnore
#OrderBy("date")
#OneToMany (mappedBy = "enrollment", cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
#OnDelete(action = OnDeleteAction.CASCADE)
private List<AttendanceRecord> attendanceRecords = new ArrayList<AttendanceRecord>();
public Enrollment() {
super();
setType(this.getClass().getCanonicalName());
setState(State.DRAFT);
setRegistrationDetails(new RegistrationDetails());
}
public String getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(String studentGrade) {
this.studentGrade = studentGrade;
}
public List<AttendanceRecord> getAttendance() {
return attendanceRecords;
}
public void addAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.add(attendanceRecord);
attendanceRecord.setEnrollment(this);
}
public void removeAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.remove(attendanceRecord);
attendanceRecord.setEnrollment(null);
}
public LocalDate getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDate registrationDate) {
this.registrationDate = registrationDate;
}
public Program getProgram() {
return program;
}
public void setProgram(Program program) {
this.program = program;
setParent(program);
}
#Override
public ParentContext getParentContext() {
return program;
}
public RegistrationDetails getRegistrationDetails() {
return registrationDetails;
}
public void setRegistrationDetails(RegistrationDetails registrationDetails) {
if (this.registrationDetails != null)
registrationDetails.setEnrollment(null);
this.registrationDetails = registrationDetails;
registrationDetails.setEnrollment(this);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
Here is my Contact class
#Embeddable
public class Contact {
String firstName = "";
String lastName = "";
String email = "";
String homePhone = "";
String dayPhone = "";
String cellPhone = "";
String relationship = "";
#Embedded
#AttributeOverrides({
#AttributeOverride(name="street", column=#Column(name="contact_street")),
#AttributeOverride(name="apartment", column=#Column(name="contact_apartment")),
#AttributeOverride(name="city", column=#Column(name="contact_city")),
#AttributeOverride(name="state", column=#Column(name="contact_state")),
#AttributeOverride(name="zipCode", column=#Column(name="contact_zipcode")),
#AttributeOverride(name="country", column=#Column(name="contact_country"))
})
Address address = new Address();
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getDayPhone() {
return dayPhone;
}
public void setDayPhone(String dayPhone) {
this.dayPhone = dayPhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getRelationship() {
return relationship;
}
public void setRelationship(String relationship) {
this.relationship = relationship;
}
public Address getAddress() {
return address;
}
}
I need to filter condition by firstname and lastname in the List of names present in either official or unOfficial names List and return List of EmployeeDetails.
Below are the pojo classes
public class EmployeeDetails {
private NameDetails nameDetails;
public NameDetails getNameDetails() {
return nameDetails;
}
public void setNameDetails(NameDetails nameDetails) {
this.nameDetails = nameDetails;
}
}
public class NameDetails {
private List<Name> officalName;
private List<Name> unOfficialName;
public List<Name> getOfficalName() {
return officalName;
}
public void setOfficalName(List<Name> offiicalName) {
this.officalName = offiicalName;
}
public List<Name> getUnOfficialName() {
return unOfficialName;
}
public void setUnOfficialName(List<Name> unOfficialName) {
this.unOfficialName = unOfficialName;
}
}
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I tried for filtering with list of officialNames and it is working fine,but I also want to filter names present in unOfficial Names also.(OR Condition)
return employeeDetailList.stream().filter(employeeDetails->(employeeDetails.getNameDetails().getOffiicalName()).stream()
.anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName())))
.collect(Collectors.toList());
Help me to solve the issue.Thanks
If you can't override equals/hashCode (if you could there would be a faster way), then:
employeeDetailList
.stream()
.filter(x -> Stream.concat(
x.getNameDetails().getOfficalName().stream(),
x.getNameDetails().getUnOfficialName().stream()
)
.anyMatch(y -> Objects.equals(y.getFirstName(), firstName) &&
Objects.equals(y.getLastName(), lastName)))
.collect(Collectors.toList());
Just add the OR condition:
return employeeDetailList.stream().filter(employeeDetails->
((employeeDetails.getNameDetails().getOffiicalName()).stream().anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName()))))
|| ((employeeDetails.getNameDetails().getUnOfficialName()).stream().anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName()))))
.collect(Collectors.toList());
I am using Spring Boot and MongoDB and I am able to store a document in MongoDB successfully. When I was trying to insert a second document, it is showing duplicatekeyexception. The total message of exception is as follows:
com.mongodb.DuplicateKeyException: Write failed with error code 11000
and error message 'E11000 duplicate key error collection:
Football_Admin.SignUp index: id dup key: { : 0 }'
The code is as follows:
SignUpRepository.java
package com.admin.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.admin.Model.SignUp;
#Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{
}
Controller
#Controller
#RequestMapping("/SignIn_Up")
public class HomeController {
#Autowired
SignUpRepository repository;
#RequestMapping(value = "/addadmin", method = RequestMethod.POST)
public String addAdmin(#ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
String originalPassword = sign.getPassword();
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
String email = sign.getEmail();
String fullname = sign.getFullName();
try {
sign.setEmail(email);
sign.setFullName(fullname);
sign.setPassword(generatedSecuredPasswordHash);
repository.save(sign);
}
catch (DuplicateKeyException e) {
e.printStackTrace();
}
System.out.println(generatedSecuredPasswordHash);
System.out.println("Email name is:"+sign.getEmail());
System.out.println("Full Name is:"+sign.getFullName());
System.out.println("Password is:"+sign.getPassword());
return "welcome";
}
Entity
package com.admin.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="SignUp")
public class SignUp {
#Id
private int id;
private String fullName;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return id+""+fullName+""+password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
MongoDb driver don't know how to create a unique Id of type int when inserting so you received unique index exception
So either you manually create and maintain your index (quite hard) or change your id field type to ObjectId
I want to sort Descending by lastChange property, the List of items from mongo.
RequestRepository interface:
public interface RequestRepository extends MongoRepository<Request, String> {
List<Request> findByUser(String id);
}
Request.java:
#Document(collection = "Requests")
public class Request {
#Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request
public Request() {}
public Request(
String user,
String requestTitle,
String requestMessage,
boolean read,
Date lastChange,
Date requestDate,
boolean isActiveRequest) {
this.user = user;
this.requestTitle = requestTitle;
this.requestMessage = requestMessage;
this.read = read;
this.lastChange = lastChange;
this.requestDate = requestDate;
this.isActiveRequest = isActiveRequest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRequestTitle() {
return requestTitle;
}
public void setRequestTitle(String requestTitle) {
this.requestTitle = requestTitle;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public Date getLastChange() {
return lastChange;
}
public void setLastChange(Date lastChange) {
this.lastChange = lastChange;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public boolean isActiveRequest() {
return isActiveRequest;
}
public void setActiveRequest(boolean activeRequest) {
isActiveRequest = activeRequest;
}
public boolean isPremiumRequest() {
return isPremiumRequest;
}
public void setPremiumRequest(boolean premiumRequest) {
isPremiumRequest = premiumRequest;
}
}
In my code I have the following list:
List<Request> = RequestRepository.findByUser(userObj.getId());
I want to have the data from RequestRepository.findByUser(userObj.getId()); sorted DESCENDING by the property lastChange.
I have searched on StackOverflow, and found the following method to sort:
List<Request> findAllByOrderByUpdatedAtDesc();
but this does not work if I search by User.
What is the solution to search by User id and to sort by lastChange?
Thank you!
This should do it.
List<Request> findByUserOrderByLastChangeDesc(String user);
Update your question with proper details.