Not able to convert date into desired format using initbinder spring - spring-mvc

I am unable to convert date format using initbinder.
Here is my code of jsp.
<!DOCTYPE html>
<html>
<head>
</head>
<form action="postdata" method="post">
fname <input type="text" name="fname"/> </br>
lname <input type="text" name="lname"/> </br>
Date <input type="text" name="myDate"/> </br>
<input type="submit"/>
</form>
</body>
</html>
My Model Class Employee.java
package com.model;
import java.util.Date;
public class Employee
{
private String fname;
private String lname;
private Date myDate;
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 Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
this.myDate = myDate;
}
#Override
public String toString() {
return "Employee [fname=" + fname + ", lname=" + lname + ", myDate=" +
myDate + "]";
}
}
My Controller is as below
package com.mkyong;
import java.io.IOException;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.model.Employee;
#Controller
public class WelcomeController {
#InitBinder
public void dataBinding(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "myDate", new
CustomDateEditor(dateFormat, false));
}
#RequestMapping(value="/postdata",method=RequestMethod.POST)
public ModelAndView welcome(HttpServletRequest request, HttpServletResponse
response,#ModelAttribute("employee") Employee employee,BindingResult
bresult)
{
System.out.println("In Welcomeontroller");
System.out.println(employee);
return new ModelAndView("myajax");
}
}
When i checked in debug mode , In dataBinding method i am getting null values for Employee model. In welcome method i am getting the date format as Mon Jan 01 00:00:00 IST 1990. I want it in dd/MM/yyyy format. Please help me out i need to apply same in project for JQGrid.

Change
binder.registerCustomEditor(Date.class, "myDate", new CustomDateEditor(dateFormat, false));
to
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
If you want to use easier approach than above one then try annotating the date field like below.
#DateTimeFormat(pattern = "dd/MM/yyyy")
#ModelAttribute
#Temporal(TemporalType.DATE)
#Column(name = "date")
private Date date;

Related

Java Code to invoke PATCH method from JUnit

I have a simple MyLibraryApplication which is having code to invoke POST(TransactionControllerImpl.issueBookToMember) and PATCH(TransactionControllerImpl.returnBookTransaction) methods. I have referred some links on net and tried my best to write code to invoke PATCH method. The code can be found in TransactionControllerTest(testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods). The code for invoking POST is working fine but the code for invoking PATCH is not working. Control never reaches returnBookTransaction inside TransactionControllerImpl.
Error: Invalid PATCH method.
I am looking for code snippet for TransactionControllerTest.testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods. Can someone help me in getting this code into proper shape?
package com.mycompany.techtrial;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.mycompany.techtrial.Transaction;
public interface TransactionController {
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params);
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId);
}
/**
*
*/
package com.mycompany.techtrial;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TransactionControllerImpl implements TransactionController{
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
* Example Post Request : { "book":"Java8 Primer","member":"Test 1" }
*/
#PostMapping(path = "/api/transaction")
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params){
String book = params.get("book");
String member = params.get("member");
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now());
transaction.setDateOfReturn(Transaction.getDefaultReturnDate());
return ResponseEntity.ok().body(transaction);
}
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
*/
#PatchMapping(path= "/api/transaction/{transaction-id}/return")
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId){
String book = "Java8 Primer";
String member = "Test 1";
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now().minusDays(10));
transaction.setDateOfReturn(LocalDateTime.now());
return ResponseEntity.ok().body(transaction);
}
}
package com.mycompany.techtrial;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TransactionControllerTest {
MockMvc mockMvc;
#Mock
private TransactionController transactionController;
#Autowired
private TestRestTemplate template;
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(transactionController).build();
}
#Test
public void testBookIssue() throws Exception {
HttpEntity<Object> transaction = getHttpEntity(
"{\"book\": \"Java8 Primer\", \"member\": \"Test 1\" }");
ResponseEntity<Transaction> response = template.postForEntity(
"/api/transaction", transaction, Transaction.class);
Assert.assertEquals("Java8 Primer", response.getBody().getBook());
Assert.assertEquals("Test 1", response.getBody().getMember());
Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingRestTemplate() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
Transaction transaction = template.patchForObject(
"/api/transaction/{transaction-id}/return",null, Transaction.class, uriVariables);
Assert.assertEquals(new Long(1), transaction.getId());
//Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingMockMvc() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
ResultActions obj = mockMvc.perform( MockMvcRequestBuilders
.patch("/api/transaction/{transaction-id}/return",transactionId)
.content("")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
System.out.println(obj.getClass());
HttpStatus status = obj.andReturn().getModelAndView().getStatus();
boolean success = status.is2xxSuccessful();
System.out.println("success="+success);
Assert.assertEquals(new Long(1), transactionId);
//Assert.assertEquals(200,response.getStatusCode().value());
}
private HttpEntity<Object> getHttpEntity(Object body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<Object>(body, headers);
}
}
package com.mycompany.techtrial;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Transaction implements Serializable {
private static final long serialVersionUID = 8951221480021840448L;
private static final LocalDateTime defaultReturnDate = LocalDateTime.of(LocalDate.of(2299, 12, 31), LocalTime.of(12, 0, 0));
Long id;
private String book;
private String member;
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
//Date and time of issuance of this book
LocalDateTime dateOfIssue;
//Date and time of return of this book
LocalDateTime dateOfReturn;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getDateOfIssue() {
return dateOfIssue;
}
public void setDateOfIssue(LocalDateTime dateOfIssue) {
this.dateOfIssue = dateOfIssue;
}
public LocalDateTime getDateOfReturn() {
return dateOfReturn;
}
public void setDateOfReturn(LocalDateTime dateOfReturn) {
this.dateOfReturn = dateOfReturn;
}
#Override
public String toString() {
return "Transaction [id=" + id + ", book=" + book + ", member=" + member + ", dateOfIssue=" + dateOfIssue + ", dateOfReturn=" + dateOfReturn + "]";
}
//#PrePersist
void preInsert() {
if (this.dateOfReturn == null)
this.dateOfReturn = defaultReturnDate;
}
public static LocalDateTime getDefaultReturnDate() {
return defaultReturnDate;
}
}
package com.mycompany.techtrial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(MyLibraryApplication.class, args);
}
}
It seems to be a known issue with the RestTemplate default Http client.
RestTemplate bug
A workaround for this would be to use the apache httpcomponents httpclient library in the RestTemplateBuilder.setRequestFactory and pass that in the constructor to TestRestTemplate
After that you can use the exchange method on the TestRestTemplate class and do a PATCH request.
Sample code to create TestRestTemplate:
Supplier<ClientHttpRequestFactory> supplier = () -> {
return new HttpComponentsClientHttpRequestFactory();
};
restTemplateBuilder.requestFactory(supplier);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
testRestTemplate.exchange("/api/transaction/{transaction-id}/return",HttpMethod.PATCH,null,Transaction.class,uriVariables);

Java FX Circle Image

I hope you can help me. I'm trying to round a image retrieved from my database. In the next image you can see the image is correctly displayed in a imageview. User selects a new item in the table and the image change to display the correct image, this is working, no problems here.
This is the program
I try with this code in the gestionarEventos :
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
Image im = imgfotovisi.getImage();
circulo.setFill(new ImagePattern(im));
But java say :
... 58 more
Caused by: java.lang.NullPointerException: Image must be non-null.
at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235)
The program runs if I delete the lines below the
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
line.
When it runs, I don't know why says the image is null, when I can see clearly there.
This is ver_visitantes class:
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.InputEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ver_visitantes implements Initializable {
#FXML private TableView<visitantes> tbvisitantes;
#FXML private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones;
#FXML private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto;
#FXML private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones;
#FXML private Label lblinfovisiact,lblusuario,lblstatusvisi;
#FXML private Circle circulo;
private ObservableList<visitantes> visitorlist;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ConexionSQL cnt = new ConexionSQL();
cnt.conexion();
visitorlist = FXCollections.observableArrayList();
visitantes.llenarlistavisitas(cnt.conexion(), visitorlist);
tbvisitantes.setItems(visitorlist);// llenar table view con la lista
clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula()));
clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres()));
clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos()));
clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento()));
clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular()));
clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones()));
gestionarEventos();
tbvisitantes.getSelectionModel().selectFirst();
}
public void gestionarEventos() {
tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() {
#Override
public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior,
visitantes valorSeleccionado) {
imgfoto.setVisible(false);
btnmodificar.setDisable(false);
btncancelar.setDisable(false);
btneliminar.setDisable(false);
imageRetrievalService.restart();
if (valorSeleccionado != null) {
txtcedula.setText(String.valueOf(valorSeleccionado.getcedula()));
txtnombres.setText(valorSeleccionado.getnombres());
txtapellidos.setText(valorSeleccionado.getapellidos());
txtapto.setText(String.valueOf(valorSeleccionado.getapartamento()));
txtcelular.setText(String.valueOf(valorSeleccionado.getcelular()));
txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones()));
}
}
});
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
}
private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes
#Override
protected Task<Image> createTask() {
final String id;
final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem();
if (visitante == null) {
id = null;
} else {
id = visitante.getcedula();
}
return new Task<Image>() {
#Override
protected Image call() throws Exception {
if (id == null) {
return null;
}
return visitante.getImageById(id);
}
};
}
};
}
this is the visitantes class,called from the imageRetrievalService to get the image:
package application;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
public class visitantes {
private StringProperty cedula;
private StringProperty nombres;
private StringProperty apellidos;
private StringProperty apartamento;
private StringProperty celular;
private StringProperty observaciones;
public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){
this.cedula = new SimpleStringProperty(cedula);
this.nombres = new SimpleStringProperty(nombres);
this.apellidos = new SimpleStringProperty(apellidos);
this.apartamento = new SimpleStringProperty(apartamento);
this.celular = new SimpleStringProperty(celular);
this.observaciones = new SimpleStringProperty(observaciones);
}
public String getnombres(){
return nombres.get();
}
public void setnombres(String nombres){
this.nombres = new SimpleStringProperty(nombres);
}
public String getcedula(){
return cedula.get();
}
public void setcedula(String cedula){
this.cedula = new SimpleStringProperty(cedula);
}
public String getapellidos(){
return apellidos.get();
}
public void setapellidos(String apellidos){
this.apellidos = new SimpleStringProperty(apellidos);
}
public String getapartamento(){
return apartamento.get();
}
public void setapartamento(String apartamento){
this.apartamento = new SimpleStringProperty(apartamento);
}
public String getcelular(){
return celular.get();
}
public void setcelular(String celular){
this.celular = new SimpleStringProperty(celular);
}
public Image getImageById(String id) throws SQLException, IOException {
try (
ConexionSQL cn = new ConexionSQL();
Connection con = cn.conexion();
PreparedStatement ps = con.prepareStatement(
"SELECT foto_visi FROM visitantes WHERE cedula_visi = ?");
) {
ps.setString(1, id);
ResultSet results = ps.executeQuery();
Image img = null ;
if (results.next()) {
Blob foto = results.getBlob("foto_visi");
InputStream is = foto.getBinaryStream();
img = new Image(is) ; // false = no background loading
is.close();
}
results.close();
return img ;
} catch (Throwable e) {
String info = e.getMessage();
System.out.println(info);
}
return null;
}
}
I think the problem is here:
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
I don't know if the retrieved image is loaded in the imageivew in this line. Looks like yes, but if I do
Image im = imgfotovisi.getImage();
Java says it is null. Then I can't get the image into the circle.
Thanks in advance :)
bind isn't going to load an image itself, it will just bind so that one variable will change when the source changes (in this case the value property of the service), which isn't going to happen straight away as the service is running asynchronously. So, if you query the value straight away after issuing the bind statement, you won't get the result you are expecting, as the source hasn't yet changed.
Instead you need to take action only once the image is actually available.
For instance:
imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
Or, if you don't want a direct linkage to the service, and given that the imgfotovsi image property is already bound to the service value:
imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);

month is set to january in oracle 11g irresptive of any month

I know its a bit weird question. I am passing date dd-mm-yyyy format from my UI and storing that into oracle 11g. but strange thing happened that it is storing it as JAN month only i.e if I pass 16-10-1992 or 10-03-1992 it is storing it as a 16-JAN-1992 way only. please let me know what silly thing I missed out?
Here's my HibernateUtil.java
package assignment.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Component;
import assignment.service.UserEntity;
#Component
public class HibernateUtil {
private static SessionFactory sessionFactorty=null;
public static SessionFactory getSessionFactory(){
if(sessionFactorty==null){
System.out.println("inside hibernate Util");
Configuration configuration=new Configuration();
configuration.addAnnotatedClass(UserEntity.class);
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
configuration.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
configuration.setProperty("hibernate.connection.username", "myDb");
configuration.setProperty("hibernate.connection.password", "Vihang616");
configuration.setProperty("hibernate.connection.url", "jdbc:oracle:thin:#127.0.0.1:1521:myDb");
/*SchemaExport schemaExport=new SchemaExport(configuration);
schemaExport.create(true, true);*/
StandardServiceRegistryBuilder srb=new StandardServiceRegistryBuilder();
srb.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry=srb.build();
sessionFactorty=configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactorty;
}
public static void shutDown(){
if(sessionFactorty!=null)
sessionFactorty.close();
}
}
Here's my USerService.java
package assignment.service;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import assignment.model.User;
import assignment.util.HibernateUtil;
import assignment.util.ServiceUtil;
#Component
public class UserService {
public Integer saveUser(User user) {
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
UserEntity userEntity=new UserEntity();
userEntity.setDob(ServiceUtil.stringToDateConverter(user.getDob()));
userEntity.setEmail(user.getEmail());
userEntity.setUserName(user.getUserName());
session.save(userEntity);
session.getTransaction().commit();
System.out.println("ID:"+userEntity.getUserId());
session.disconnect();
HibernateUtil.shutDown();
return userEntity.getUserId();
}
}
Here's my SerivceUtl.java
package assignment.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ServiceUtil {
public static Date stringToDateConverter(String string){
SimpleDateFormat sdf=new SimpleDateFormat("dd-mm-yyyy");
System.out.println("dob:"+string);
Date date=new Date();
try {
date=sdf.parse(string);
} catch (ParseException e) {
System.out.println("exception in parsing date");
e.printStackTrace();
}
return date;
}
}
Here's My Entity class
package assignment.service;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="UserDb")
public class UserEntity implements Serializable {
private static final long serialVersionUID = -6620152467355557520L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer userId;
#Column(nullable=false)
private String userName;
#Column(nullable=false)
private String email;
#Column(nullable=false)
#Temporal(TemporalType.DATE)
private Date dob;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}

Mockito testing service layer

I'm new to Mockito and trying to test my service layer. My DAO layer is #Autowired in service and Hibernate is also autowired. Hibernate is not loading while testing. I always get NullPointerException. Here is my code:
EmployeeService (Interface)
package com.spring.crud.service;
import java.util.List;
import com.spring.crud.entity.Employee;
public interface EmployeeService {
Employee save(Employee employee);
boolean update(Employee employee);
Employee find(Integer id);
List<Employee> getEmployees();
boolean remove(Integer id);
}
EmployeeServiceImpl (Class)
package com.spring.crud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.entity.Employee;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDAO dao;
public Employee save(Employee employee) {
return dao.save(employee);
}
public boolean update(Employee employee) {
return dao.update(employee);
}
public Employee find(Integer id) {
return dao.find(id);
}
public List<Employee> getEmployees() {
return dao.getEmployees();
}
public boolean remove(Integer id) {
return dao.remove(id);
}
}
EmployeeDAO (Interface)
package com.spring.crud.dao;
import java.util.List;
import com.spring.crud.entity.Employee;
public interface EmployeeDAO {
Employee save(Employee employee);
boolean update(Employee employee);
Employee find(Integer id);
List<Employee> getEmployees();
boolean remove(Integer id);
}
EmployeeDAOImpl (Class)
package com.spring.crud.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.spring.crud.entity.Employee;
#Transactional
#Repository
public class EmployeeDAOImpl extends HibernateUtil implements EmployeeDAO{
public Employee save(Employee employee) {
Session session = getCurrentSession();
session.save(employee);
return employee;
}
public boolean update(Employee employee) {
Session session = getCurrentSession();
session.update(employee);
return false;
}
public Employee find(Integer id) {
Session session = getCurrentSession();
Employee employee = (Employee)session.get(Employee.class, id);
return employee;
}
public List<Employee> getEmployees() {
Session session = getCurrentSession();
Query query = session.createQuery("from Employee");
#SuppressWarnings("unchecked")
List<Employee> employees = (List<Employee>)query.list();
return employees;
}
public boolean remove(Integer id) {
Session session = getCurrentSession();
Employee employee = (Employee)session.get(Employee.class, id);
if(employee!=null){
session.delete(employee);
return true;
}
return false;
}
}
HibernateUtil
package com.spring.crud.dao;
import javax.annotation.PostConstruct;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class HibernateUtil extends HibernateDaoSupport{
#Autowired
private SessionFactory sessionFactory;
#PostConstruct
public void init() {
setSessionFactory(sessionFactory);
}
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
EmployeeServiceTest (Test class)
package com.spring.crud.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.ContextConfiguration;
import com.spring.crud.config.WebConfig;
import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.dao.EmployeeDAOImpl;
import com.spring.crud.entity.Employee;
import com.spring.crud.service.EmployeeService;
import com.spring.crud.service.EmployeeServiceImpl;
#ContextConfiguration(classes = {WebConfig.class})
public class EmployeeServiceTest {
private EmployeeDAO employeeDAO;
private EmployeeService employeeService = new EmployeeServiceImpl();
#Spy
List<Employee> employees = new ArrayList<Employee>();
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
employeeDAO = mock(EmployeeDAOImpl.class);
}
#Test
public void listEmployees() {
}
#Test
public void create() {
Employee employee = new Employee();
employee.setDateOfBirth(new Date());
employee.setGender("male");
employee.setName("Ashutosh");
when(employeeDAO.save(any(Employee.class)))
.thenAnswer(new Answer<Employee>() {
public Employee answer(InvocationOnMock invocation) throws Throwable {
Employee employee = (Employee) invocation.getArguments()[0];
employee.setId(1);
return employee;
}
});
assertNull(employee.getId());
employee = employeeService.save(employee);
assertNotNull(employee.getId());
assertTrue(employee.getId()>0);
}
#Test
public void edit() {
}
#Test
public void update() {
}
#Test
public void remove() {
}
}
I can't find much on this on the internet.
Just because you create a mock employee DAO in your test doesn't mean that your service will use it. It won't. When you do
new EmployeeServiceImpl();
you create an instance of the service, and its DAO field is left uninitialized (so null).
Use constructor injection, and pass the mock DAO to the service constructor:
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO dao;
#Autowired
public EmployeeServiceImpl(EmployeeDAO dao) {
this.dao = dao;
}
...
}
And/or at least use Mockito annotations correctly:
#Mock
private EmployeeDAO employeeDAO;
#InjectMocks
private EmployeeServiceImpl employeeService;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
OK, I found some fixes and now the test runs.
First, I fixed the HibernateUtil
package com.spring.crud.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class HibernateUtil{
#Autowired
private SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
This is the EmployeeServiceTest class
package com.spring.crud.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.ContextConfiguration;
import com.spring.crud.config.WebConfig;
import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.entity.Employee;
import com.spring.crud.service.EmployeeServiceImpl;
#ContextConfiguration(classes = {WebConfig.class})
public class EmployeeServiceTest {
#Mock
private EmployeeDAO employeeDAO;
#InjectMocks
private EmployeeServiceImpl employeeService;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void listEmployees() {
}
#Test
public void create() {
Employee employee = new Employee();
employee.setDateOfBirth(new Date());
employee.setGender("male");
employee.setName("Ashutosh");
when(employeeDAO.save(any(Employee.class)))
.thenAnswer(new Answer<Employee>() {
public Employee answer(InvocationOnMock invocation) throws Throwable {
Employee employee = (Employee) invocation.getArguments()[0];
employee.setId(10);
return employee;
}
});
assertNull(employee.getId());
employee = employeeService.save(employee);
System.out.println("Id = " + employee.getId());
assertNotNull(employee);
assertEquals((Integer)10, (Integer)employee.getId());
}
#Test
public void edit() {
}
#Test
public void update() {
}
#Test
public void remove() {
}
}

Query execution problem using Spring and HIbernate together with FLEX

So I'm going to be using Flex 4 with Spring and Hibernate.
Everything is configured and working. I know this as I can do simple queries, like listing all values in a table.
Problem is when I try to perform a 'select' query, then I get all the values, as I was getting before, and not the specific attributes through Select query.
I'm a beginner, so kindly overlook my lack of more technically sound words..but I don use them as I don wanna mis-quote.
Following is some code which will make You understand things better:
This is class used to store data coming from the MySQL database--
package flex;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="intrial1")
public class intrial1 implements Serializable {
#Id #GeneratedValue
#Column( name = "id")
private int id;
#Column( name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is the class where the sessionFactory does things(too many import statements, just to try to make things work-ignore)--
package flex;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.NamedNativeQueries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
#Repository
#RemotingDestination
public class SpringBean_Service {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory factory) {
sessionFactory = factory;
}
#SuppressWarnings("unchecked")
#RemotingInclude
#Transactional
public List<intrial1> getList() {
return sessionFactory.getCurrentSession().createQuery("from intrial1 ").list();
}
#SuppressWarnings("unchecked")
#RemotingInclude
#Transactional
public List<intrial1> getListAgain() {
org.hibernate.Query q = sessionFactory.getCurrentSession().createQuery("select id from intrial1 where name='chirayu'");
List l = q.list();
return l;
}
#RemotingInclude
#Transactional
public void createFriend(String name, int id) {
intrial1 f = new intrial1();
f.setName(name);
f.setId(id);
sessionFactory.getCurrentSession().save(f);
}
}
In above class, getList() works
perfect, lists all the values. The
createFriend is used to enter values
of id+name, and works smoothly. The
problem is with getListAgain()
function, it gives me a result,
imagine 2 columns, having heading as
'id' and 'name', but listing id values
in both the columns (No names), As You
can understand, I am looking for
result of getListAgain() function as -
"1 column having header as 'id', and
listing id wherever the name
='chirayu'".
Kindly help, as I will need to clear this and move ahead with development.
Thank You.
Regards,
Chirayu
UPDATE NOTE: Would like to say one thing here, if only I make a class as below, which is identical to intrial1 class, but has no return statement for name, i.e., no getName() defined, I get my correct result for the query -
'select id from intrial1 where
name='chirayu''
package flex;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class intrial2 {
#Id #GeneratedValue
#Column( name = "id")
private int id;
#Column( name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
Is this strange or meant to be like this. Still looking for answers.
The query
select id from intrial1 where name='chirayu'
doesn't return intrial1 entity, so you should change return type to List or simply change your query to:
from intrial1 where name='chirayu'

Resources