How does java bean validation work in practical - java

I was wondering have the java bean validation would work in practical, lets say we have a Maven mvc project, with a login form for a user. So we have a jsp/jsf page with the html forms, a Datamapper/DAO for the JDBC connection and a java User bean, which could look like this:
public class Student {
#NotNull(message ="username can't be null)
private String uName;
#NotNull(message ="lastname can't be null)
private String lname;
#Email (regex string="")
private String email;
private int age;
public Student(String uName, String lname, String email, int age) {
this.uName = uName;
this.lname = lname;
this.email = email;
this.age = age;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
what would happen if a user typped in some not valid information in the view part of the application? What it go all the way down to the bean to get the message and then display it?
And how is the bean validation typically used? Only for Spring and Hibernate ,or for java EE in general?

Validation is used in JavaEE in general. Not only in Spring and Hibernate. Bean Validation is a JEE specification, marked as:
JSR-303 (v.1.0)
JSR-349 (v. 1.1)
JSR-380 (v. 2.0)
It works exacly as you mentioned in your question.

Related

Validating response from REST API call

I am working on error handling a response mapping. Before I go ahead and map the response to my domain objects, I want to validate the response. Check for errors.
I am planning to have a Validator.java class and implement validation methods for each of the API call.
Is there any alternative way in spring to do this?
package com.people.net;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class UserInfo {
//Unicode check
#Pattern(regexp="[0-9a-zA-Z\\s-]+", message="chars,numbers allowed only")
String name;
int id;
#Pattern(regexp="([0-9]{10})", message="minLength=maxLength=10 only numbers")
String pin;
#Email
String email;
#Size(max=5, message="5 chars max")
String emailType;
#Size(max=5, message="5 chars max")
String addressType;
#Size(max=300, message="5 chars max")
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserInfo(String name, String pin, String id) {
super();
this.id = Integer.parseInt(id);
this.name = name;
this.pin = pin;
}
public UserInfo(int id,String name, String pin, String email, String emailType, String addressType, String address) {
super();
this.id = id;
this.name = name;
this.pin = pin;
this.email = email;
this.emailType = emailType;
this.addressType = addressType;
this.address = address;
}
public UserInfo() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
You should explore hibernate validator which is the reference implementation JSR-349 for bean validation. more info is here https://jcp.org/en/jsr/detail?id=349 .
Also hibernate validator is a industry standard for doing the bean validation(lots of stuff available on internet) and comes with lots of popular framework like dropwizard etc.it provide annotation based validation and allow you to write your own custom annotation based validation.
please refer on step by step guide http://www.journaldev.com/2668/spring-validation-example-mvc-validator, where author uses it with the spring.

Spring MVC form validation does't work for nested complex types

I am implementing a sample Spring MVC Form with Form Validation. I have a complex type Address as bean property for Student form bean. And I have added form validation #NotEmpty for Address bean properties. But the same is not reflecting in the UI. But form validation works for other primitive types of Student form bean.
So, Validation works perfectly for Student form bean but not for nested complex types like Address within Student form bean.
I am trying understand the reason and a fix.
Spring version 4.0+.
Hibernate Validator api:5.2.4
Student POJO:
package com.xyz.form.beans;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.DateNotEmpty;
import com.xyz.validators.ListNotEmpty;
public class Student {
#Size(min = 2, max = 30)
private String firstName;
#Size(min = 2, max = 30)
private String lastName;
#NotEmpty
private String gender;
#DateNotEmpty
#Past
private Date DOB;
private String email;
private String mobileNumber;
#ListNotEmpty
private List<String> courses;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
}
Address POJO:
package com.xyz.form.beans;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.LongNotEmpty;
public class Address {
#NotEmpty
private String houseNo;
#NotEmpty
private String street;
#NotEmpty
private String area;
#NotEmpty
private String city;
#LongNotEmpty
private Long pin;
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getPin() {
return pin;
}
public void setPin(Long pin) {
this.pin = pin;
}
}
Student Controller:
#RequestMapping(value = "/newStudentDetails.do", method = RequestMethod.POST)
public ModelAndView newStudentDetails(
#Valid #ModelAttribute("student") com.xyz.form.beans.Student studentFormBean,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ModelAndView("newStudentPage");
}
Student studentDto = new Student();
studentDto.setFirstName(studentFormBean.getFirstName());
studentDto.setLastName(studentFormBean.getLastName());
studentDto.setGender(studentFormBean.getGender());
studentDto.setDOB(new Date(studentFormBean.getDOB().getTime()));
studentDto.setEmail(studentFormBean.getEmail());
studentDto.setMobileNumber(studentFormBean.getMobileNumber());
StringBuilder sb = new StringBuilder();
sb.append(studentFormBean.getAddress().getHouseNo() + ", ");
sb.append(studentFormBean.getAddress().getStreet() + ", ");
sb.append(studentFormBean.getAddress().getArea() + ", ");
sb.append(studentFormBean.getAddress().getCity() + "-");
sb.append(studentFormBean.getAddress().getPin());
studentDto.setAddress(sb.toString());
studentDto.setCourses(studentFormBean.getCourses());
studentDao.createStudent(studentDto);
ModelAndView mav = new ModelAndView("newStudentSuccess");
return mav;
}
Thanks,
Viswanath
You need to annotate your complex types with #Valid.
This is the reference (which references here)
Hi lets try #ModelAttribute("student") #Valid com.xyz.form.beans.Student studentFormBean in place of #Valid #ModelAttribute("student")
For nested complex types, you have to activate the direct field access. Just like below:
#org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.initDirectFieldAccess();
}

objectify, javascript and google endpoint

I am trying to figure out how integration between google endpoint, objectify and javscripts works. I made a real simple class named 'User'. All I am trying is to fetch a record from a Data Store and return this object back and use this in javascript.
However, the object does not seem to flow back properly. I do not see any details around this object using Chrome's developer tools... Any ideas? FYI, the record exists in the data store as I can see it while using the development console. I also can see the information as I've logged this info to the console as well. Thanks.
** JAVA CLASS **
package com.Backend;
import com.googlecode.objectify.annotation.*;
#Entity
public class User {
String firstName;
String lastName;
#Id String email;
public User(){
super();
}
public User(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
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;
}
}
** GOOGLE ENDPOINT **
public class UserEndpoint {
private static final Logger LOG = Logger.getLogger(UserEndpoint.class.getName());
static {
ObjectifyService.register(User.class);
}
#ApiMethod(name = "getUser")
public User getUser() {
User u = ofy().load().type(User.class).id("johndoe#domain.com").now();
return u;
}
}
Finally found out what the issue is. It has to do with how the object was returned... It did not have any return value.

LazyInitializationException in Hibernate and Jersey

Hi I am doing a project using Hibernate and Jersey.
In the service layer I am getting a 'LazyInitializationException'. I searched a lot about it.
I saw a solution for creating custom AccessorType. But still I am getting the exception.
Can anyone help me??
I am including more details about it.
Bean: User
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlAccessorFactory(XmlAccessorFactoryImpl.class)
public class User {
private String userName;
private String password;
private String email;
private String fname;
private String lname;
private Set<MachineTemplate> machineTemplates;
private String photoUrl;
public User() {
machineTemplates = new HashSet<>();
}
public User(String userName) {
this.userName = userName;
}
public User(String userName, String password, String email, String fname,
String lname) {
this.userName = userName;
this.password = password;
this.email = email;
this.fname = fname;
this.lname = lname;
this.machineTemplates = new HashSet<>();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Set<MachineTemplate> getMachineTemplates() {
return machineTemplates;
}
public void setMachineTemplates(Set<MachineTemplate> machineTemplates) {
this.machineTemplates = machineTemplates;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
DAO Layer method
public User get(String uName) {
Session session = getSessionFactory().openSession();
User u = (User) session.get(User.class, uName);
session.close();
}
Service Layer method
#GET
#Path("/{userName}")
#Produces(MediaType.APPLICATION_JSON)
public User getUserInfo(#PathParam("userName") String userName) {
return userHelper.getUser(userName);
}
The exception says you are trying to load an lazy collection which of out of session. Meaning you need to initialize the collection object before you use. The initialization should happen either in entity setter method or in DAO class. Initializing in setter method of an entity is not recommended usually since it couples your entity with hibernate framework. So best place is DAO layer. But here I have mentioned just for your reference.
Try this
public void setMachineTemplates(Set<MachineTemplate> machineTemplates) {
Hibernate.initialize(machineTemplates);
this.machineTemplates = machineTemplates;
}
Hope this is helpful!
You get the LazyInitializationException when trying to access a lazy fetched atttribute on an entity detached from the persistence context.
It usually means that your hibernate session ( / JPA entityManager) have been already closed when you access the lazy attribute.
see Struggling to understand EntityManager proper use
Actually I dont want to load the machineTemplates data. So I did like
public Set<MachineTemplate> getMachineTemplates() {
if(Hibernate.isInitialized(machineTemplates))
return machineTemplates;
return null;
}

JavaBean to CSV file [duplicate]

This question already has answers here:
How to serialize object to CSV file?
(8 answers)
Closed 9 years ago.
what would be the best way to have information in a JavaBean be put into a CSV file? I am making a registration page and have set all the parameters of my User JavaBean through a JSP page using I need to store this information into a csv from a servlet everytime someone registers so I can retrieve this information when they use the login JSP page.
Here is my JavaBean
package bean.user;
public class User_profile {
private String First_Name;
private String Last_Name;
private String ssn;
private String birthday;
private String home_phone;
private String password;
private String gender;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getHome_phone() {
return home_phone;
}
public void setHome_phone(String home_phone) {
this.home_phone = home_phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
You can use introspection to retrieve all the properties of your bean with their corresponding read/write method then call them by reflection.
Here is an example with this simple class:
public class User {
private String login;
private String name;
private String surname;
private Integer age;
//Getters and setters
}
Now, I create a user and dump its properties in a String with comma separated values :
User u = new User();
u.setAge(18);
u.setLogin("myLogin");
u.setName("myName");
u.setSurname("mySurname");
for(PropertyDescriptor pd : Introspector.getBeanInfo(User.class).getPropertyDescriptors()){
//I don't want to get the "class" property
if(!pd.getName().equals("class")){
Method readMethod = pd.getReadMethod();
System.out.print(readMethod.invoke(u)+",");
}
}
Output :
18,myLogin,myName,mySurname,
Note: For the simplicity of this example, I did not suppress the ',' at the end of the output and did not handle case when properties contain character ','.
Use jsefa if you really really want CSV but this is better suited to store the details in some sort or repository/DB.
You can use this library http://jexcelapi.sourceforge.net/ or any such library which can help you convert your java objects in CSV form. One more for you http://kasparov.skife.org/csv/

Categories

Resources