Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
21550cd2f8
|
@ -1,14 +1,14 @@
|
|||
package org.baeldung.gson.deserialization;
|
||||
|
||||
import java.text.ParseException;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.baeldung.gson.entities.ActorGson;
|
||||
import org.baeldung.gson.entities.Movie;
|
||||
import org.baeldung.gson.serialization.ActorGsonDeserializer;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.text.ParseException;
|
||||
|
||||
public class GsonDeserializeTest {
|
||||
|
||||
|
|
|
@ -1,20 +1,17 @@
|
|||
package org.baeldung.gson.serialization;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.gson.entities.ActorGson;
|
||||
import org.baeldung.gson.entities.Movie;
|
||||
import org.baeldung.gson.entities.MovieWithNullValue;
|
||||
import org.baeldung.gson.serialization.ActorGsonDeserializer;
|
||||
import org.baeldung.gson.serialization.ActorGsonSerializer;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.baeldung.gson.entities.ActorGson;
|
||||
import org.baeldung.gson.entities.Movie;
|
||||
import org.baeldung.gson.entities.MovieWithNullValue;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class GsonSerializeTest {
|
||||
|
||||
|
@ -40,12 +37,12 @@ public class GsonSerializeTest {
|
|||
MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));
|
||||
|
||||
String expectedOutput = new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.serializeNulls()
|
||||
.disableHtmlEscaping()
|
||||
.create()
|
||||
.toJson(new JsonParser()
|
||||
.parse("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}"));
|
||||
.setPrettyPrinting()
|
||||
.serializeNulls()
|
||||
.disableHtmlEscaping()
|
||||
.create()
|
||||
.toJson(new JsonParser()
|
||||
.parse("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}"));
|
||||
Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +1,18 @@
|
|||
package org.baeldung.jackson.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.baeldung.jackson.entities.Movie;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
public class JacksonDeserializeTest {
|
||||
|
||||
@Test
|
||||
public void whenSimpleDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
public void whenSimpleDeserialize_thenCorrect() throws IOException {
|
||||
|
||||
String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
@ -25,7 +23,7 @@ public class JacksonDeserializeTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
public void whenCustomDeserialize_thenCorrect() throws IOException {
|
||||
|
||||
String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
|
||||
|
||||
|
|
|
@ -27,7 +27,7 @@
|
|||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>el-api</artifactId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
@ -126,8 +126,8 @@
|
|||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
|
||||
<!-- JSF -->
|
||||
<com.sun.faces.version>2.1.7</com.sun.faces.version>
|
||||
<javax.el.version>2.2</javax.el.version>
|
||||
<com.sun.faces.version>2.2.13</com.sun.faces.version>
|
||||
<javax.el.version>3.0.0</javax.el.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
|
|
|
@ -1,13 +1,17 @@
|
|||
package com.baeldung.springintegration.controllers;
|
||||
|
||||
import java.util.Random;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.el.ELContextEvent;
|
||||
import javax.el.ELContextListener;
|
||||
import javax.el.LambdaExpression;
|
||||
import javax.faces.application.Application;
|
||||
import javax.faces.application.FacesMessage;
|
||||
import javax.el.LambdaExpression;
|
||||
import javax.faces.bean.ManagedBean;
|
||||
import javax.faces.bean.ViewScoped;
|
||||
import javax.faces.component.html.HtmlInputText;
|
||||
import javax.faces.context.FacesContext;
|
||||
import java.util.Collection;
|
||||
import java.util.Random;
|
||||
|
||||
@ManagedBean(name = "ELBean")
|
||||
@ViewScoped
|
||||
|
@ -16,22 +20,37 @@ public class ELSampleBean {
|
|||
private String firstName;
|
||||
private String lastName;
|
||||
private String pageDescription = "This page demos JSF EL Basics";
|
||||
public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON";
|
||||
private int pageCounter;
|
||||
private Random randomIntGen = new Random();
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
pageCounter = randomIntGen.nextInt();
|
||||
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() {
|
||||
@Override
|
||||
public void contextCreated(ELContextEvent evt) {
|
||||
evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void save() {
|
||||
|
||||
}
|
||||
|
||||
public static String constantField() {
|
||||
return constantField;
|
||||
}
|
||||
|
||||
public void saveFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public Long multiplyValue(LambdaExpression expr) {
|
||||
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter);
|
||||
return theResult;
|
||||
}
|
||||
|
||||
public void saveByELEvaluation() {
|
||||
firstName = (String) evaluateEL("#{firstName.value}", String.class);
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
<?xml version='1.0' encoding='UTF-8' ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:h="http://java.sun.com/jsf/html"
|
||||
xmlns:c="http://java.sun.com/jsp/jstl/core">
|
||||
<h:head>
|
||||
<title>Baeldung | Expression Language 3.0</title>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<h:outputLabel id="valueLabel" for="valueOutput" value="Composite Lambda Evaluation:"/>
|
||||
<h:outputText id="valueOutput" value="#{(cube=(x->x*x*x);cube(4))}"/>
|
||||
<br/>
|
||||
<h:outputLabel id="staticLabel" for="staticFieldOutput" value="Static Field Output:"/>
|
||||
<h:outputText id="staticFieldOutput" value="#{ElBean.constantField}"/>
|
||||
<br/>
|
||||
<h:outputLabel id="avgLabel" for="avg" value="Average of Integer List Value:"/>
|
||||
<h:outputText id="avg" value="#{['1','2','3'].stream().average().get()}"/>
|
||||
<br/>
|
||||
<h:outputLabel id="lambdaLabel" for="lambdaPass" value="Passing Lambda Expressions:"/>
|
||||
<h:outputText id="lambdaPass" value="#{ELBean.multiplyValue(x->x*x*x)}"/>
|
||||
<br/>
|
||||
<c:set var='pageLevelNumberList' value="#{[1,2,3]}"/>
|
||||
<h:outputLabel id="avgPageVarLabel" for="avgPageVar" value="Average of Page-Level Integer List Value:"/>
|
||||
<h:outputText id="avgPageVar" value="#{pageLevelNumberList.stream().average().get()}"/>
|
||||
<br/>
|
||||
<h:panelGrid title="Data Structures" border="3" >
|
||||
<h:dataTable var="streamResult" value="#{pageLevelNumberList.stream().filter(x-> x>1).toList()}">
|
||||
<h:column id="nameCol">
|
||||
<h:outputText id="name" value="#{streamResult}"/>
|
||||
</h:column>
|
||||
</h:dataTable>
|
||||
</h:panelGrid>
|
||||
</h:body>
|
||||
</html>
|
||||
|
|
@ -1,8 +1,5 @@
|
|||
package org.baeldung.main;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.baeldung.common.error.SpringHelloServletRegistrationBean;
|
||||
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
|
||||
import org.baeldung.controller.servlet.HelloWorldServlet;
|
||||
|
@ -17,6 +14,9 @@ import org.springframework.context.annotation.ComponentScan;
|
|||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" })
|
||||
|
@ -55,28 +55,6 @@ public class SpringBootApplication {
|
|||
return bean;
|
||||
}
|
||||
|
||||
/* @Bean
|
||||
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
|
||||
JettyEmbeddedServletContainerFactory jettyContainer = new JettyEmbeddedServletContainerFactory();
|
||||
jettyContainer.setPort(9000);
|
||||
jettyContainer.setContextPath("/springbootapp");
|
||||
return jettyContainer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
|
||||
UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
|
||||
factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
|
||||
|
||||
@Override
|
||||
public void customize(io.undertow.Undertow.Builde builder) {
|
||||
builder.addHttpListener(8080, "0.0.0.0");
|
||||
}
|
||||
|
||||
});
|
||||
return factory;
|
||||
}*/
|
||||
|
||||
@Bean
|
||||
@Autowired
|
||||
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {
|
||||
|
|
|
@ -3,71 +3,80 @@ package com.baeldung.hibernate.fetching.model;
|
|||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
|
||||
public class OrderDetail implements Serializable{
|
||||
public class OrderDetail implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long orderId;
|
||||
private Date orderDate;
|
||||
private String orderDesc;
|
||||
private User user;
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long orderId;
|
||||
private Date orderDate;
|
||||
private String orderDesc;
|
||||
private User user;
|
||||
|
||||
public OrderDetail(){
|
||||
public OrderDetail() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public OrderDetail(Date orderDate, String orderDesc) {
|
||||
super();
|
||||
this.orderDate = orderDate;
|
||||
this.orderDesc = orderDesc;
|
||||
}
|
||||
public OrderDetail(Date orderDate, String orderDesc) {
|
||||
super();
|
||||
this.orderDate = orderDate;
|
||||
this.orderDesc = orderDesc;
|
||||
}
|
||||
|
||||
public Date getOrderDate() {
|
||||
return orderDate;
|
||||
}
|
||||
public void setOrderDate(Date orderDate) {
|
||||
this.orderDate = orderDate;
|
||||
}
|
||||
public String getOrderDesc() {
|
||||
return orderDesc;
|
||||
}
|
||||
public void setOrderDesc(String orderDesc) {
|
||||
this.orderDesc = orderDesc;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
OrderDetail other = (OrderDetail) obj;
|
||||
if (orderId == null) {
|
||||
if (other.orderId != null)
|
||||
return false;
|
||||
} else if (!orderId.equals(other.orderId))
|
||||
return false;
|
||||
public Date getOrderDate() {
|
||||
return orderDate;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
public void setOrderDate(Date orderDate) {
|
||||
this.orderDate = orderDate;
|
||||
}
|
||||
|
||||
public String getOrderDesc() {
|
||||
return orderDesc;
|
||||
}
|
||||
|
||||
public void setOrderDesc(String orderDesc) {
|
||||
this.orderDesc = orderDesc;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
OrderDetail other = (OrderDetail) obj;
|
||||
if (orderId == null) {
|
||||
if (other.orderId != null)
|
||||
return false;
|
||||
} else if (!orderId.equals(other.orderId))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -6,91 +6,89 @@ import java.util.Set;
|
|||
|
||||
public class User implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long userId;
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long userId;
|
||||
private String userName;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>();
|
||||
|
||||
public User() {
|
||||
|
||||
}
|
||||
|
||||
public User(final Long userId, final String userName, final String firstName, final String lastName) {
|
||||
super();
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
super();
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
||||
return result;
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final User other = (User) obj;
|
||||
if (userId == null) {
|
||||
if (other.userId != null)
|
||||
return false;
|
||||
} else if (!userId.equals(other.userId))
|
||||
return false;
|
||||
return true;
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final User other = (User) obj;
|
||||
if (userId == null) {
|
||||
if (other.userId != null)
|
||||
return false;
|
||||
} else if (!userId.equals(other.userId))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(final Long userId) {
|
||||
this.userId = userId;
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(final String userName) {
|
||||
this.userName = userName;
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(final String lastName) {
|
||||
this.lastName = lastName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Set<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
public Set<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,35 +1,30 @@
|
|||
package com.baeldung.hibernate.fetching.util;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory factory;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static Session getHibernateSession(String fetchMethod) {
|
||||
//two config files are there
|
||||
//one with lazy loading enabled
|
||||
//another lazy = false
|
||||
SessionFactory sf = null;
|
||||
if ("lazy".equals(fetchMethod)) {
|
||||
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
public static Session getHibernateSession(String fetchMethod) {
|
||||
//two config files are there
|
||||
//one with lazy loading enabled
|
||||
//another lazy = false
|
||||
|
||||
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
|
||||
}
|
||||
// fetching.cfg.xml is used for this example
|
||||
final Session session = sf.openSession();
|
||||
return session;
|
||||
}
|
||||
final String configFileName = "lazy".equals(fetchMethod) ?
|
||||
"fetchingLazy.cfg.xml" :
|
||||
"fetching.cfg.xml";
|
||||
|
||||
public static Session getHibernateSession() {
|
||||
System.out.println("Loading eager");
|
||||
SessionFactory sf = null;
|
||||
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
|
||||
final Session session = sf.openSession();
|
||||
return session;
|
||||
}
|
||||
return new Configuration()
|
||||
.configure(configFileName)
|
||||
.buildSessionFactory().openSession();
|
||||
}
|
||||
|
||||
public static Session getHibernateSession() {
|
||||
return new Configuration()
|
||||
.configure("fetching.cfg.xml")
|
||||
.buildSessionFactory()
|
||||
.openSession();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -18,98 +18,93 @@ import com.baeldung.hibernate.fetching.model.User;
|
|||
|
||||
public class FetchingAppView {
|
||||
|
||||
public FetchingAppView(){
|
||||
public FetchingAppView() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
//lazily loaded
|
||||
public boolean lazyLoaded(){
|
||||
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
|
||||
List<User> users = sessionLazy.createQuery("From User").list();
|
||||
User userLazyLoaded = new User();
|
||||
userLazyLoaded = users.get(3);
|
||||
//since data is lazyloaded so data won't be initialized
|
||||
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
|
||||
return (Hibernate.isInitialized(orderDetailSet));
|
||||
}
|
||||
public boolean lazyLoaded() {
|
||||
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
|
||||
List<User> users = sessionLazy.createQuery("From User").list();
|
||||
User userLazyLoaded = users.get(3);
|
||||
//since data is lazyloaded so data won't be initialized
|
||||
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
|
||||
|
||||
//eagerly loaded
|
||||
public boolean eagerLoaded(){
|
||||
final Session sessionEager = HibernateUtil.getHibernateSession();
|
||||
//data should be loaded in the following line
|
||||
//also note the queries generated
|
||||
List<User> users =sessionEager.createQuery("From User").list();
|
||||
User userEagerLoaded = new User();
|
||||
userEagerLoaded = users.get(3);
|
||||
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
|
||||
return (Hibernate.isInitialized(orderDetailSet));
|
||||
}
|
||||
return (Hibernate.isInitialized(orderDetailSet));
|
||||
}
|
||||
|
||||
public boolean eagerLoaded() {
|
||||
final Session sessionEager = HibernateUtil.getHibernateSession();
|
||||
//data should be loaded in the following line
|
||||
//also note the queries generated
|
||||
List<User> users = sessionEager.createQuery("From User").list();
|
||||
User userEagerLoaded = users.get(3);
|
||||
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
|
||||
|
||||
return (Hibernate.isInitialized(orderDetailSet));
|
||||
}
|
||||
|
||||
|
||||
//creates test data
|
||||
//call this method to create the data in the database
|
||||
public void createTestData() {
|
||||
//creates test data
|
||||
//call this method to create the data in the database
|
||||
public void createTestData() {
|
||||
|
||||
final Session session = HibernateUtil.getHibernateSession();
|
||||
final Session session = HibernateUtil.getHibernateSession();
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
Transaction tx = null;
|
||||
final User user1 = new User();
|
||||
final User user2 = new User();
|
||||
final User user3 = new User();
|
||||
|
||||
tx = session.beginTransaction();
|
||||
final User user1 = new User();
|
||||
final User user2 = new User();
|
||||
final User user3 = new User();
|
||||
user1.setFirstName("Priyam");
|
||||
user1.setLastName("Banerjee");
|
||||
user1.setUserName("priyambanerjee");
|
||||
session.save(user1);
|
||||
|
||||
user1.setFirstName("Priyam");
|
||||
user1.setLastName("Banerjee");
|
||||
user1.setUserName("priyambanerjee");
|
||||
session.save(user1);
|
||||
user2.setFirstName("Navneeta");
|
||||
user2.setLastName("Mukherjee");
|
||||
user2.setUserName("nmukh");
|
||||
session.save(user2);
|
||||
|
||||
user2.setFirstName("Navneeta");
|
||||
user2.setLastName("Mukherjee");
|
||||
user2.setUserName("nmukh");
|
||||
session.save(user2);
|
||||
user3.setFirstName("Molly");
|
||||
user3.setLastName("Banerjee");
|
||||
user3.setUserName("mollyb");
|
||||
session.save(user3);
|
||||
|
||||
user3.setFirstName("Molly");
|
||||
user3.setLastName("Banerjee");
|
||||
user3.setUserName("mollyb");
|
||||
session.save(user3);
|
||||
final OrderDetail order1 = new OrderDetail();
|
||||
final OrderDetail order2 = new OrderDetail();
|
||||
final OrderDetail order3 = new OrderDetail();
|
||||
final OrderDetail order4 = new OrderDetail();
|
||||
final OrderDetail order5 = new OrderDetail();
|
||||
|
||||
final OrderDetail order1 = new OrderDetail();
|
||||
final OrderDetail order2 = new OrderDetail();
|
||||
final OrderDetail order3 = new OrderDetail();
|
||||
final OrderDetail order4 = new OrderDetail();
|
||||
final OrderDetail order5 = new OrderDetail();
|
||||
order1.setOrderDesc("First Order");
|
||||
order1.setOrderDate(new Date(2014, 10, 12));
|
||||
order1.setUser(user1);
|
||||
|
||||
order1.setOrderDesc("First Order");
|
||||
order1.setOrderDate(new Date(2014, 10, 12));
|
||||
order1.setUser(user1);
|
||||
order2.setOrderDesc("Second Order");
|
||||
order2.setOrderDate(new Date(2016, 10, 25));
|
||||
order2.setUser(user1);
|
||||
|
||||
order2.setOrderDesc("Second Order");
|
||||
order2.setOrderDate(new Date(2016, 10, 25));
|
||||
order2.setUser(user1);
|
||||
order3.setOrderDesc("Third Order");
|
||||
order3.setOrderDate(new Date(2015, 2, 17));
|
||||
order3.setUser(user2);
|
||||
|
||||
order3.setOrderDesc("Third Order");
|
||||
order3.setOrderDate(new Date(2015, 2, 17));
|
||||
order3.setUser(user2);
|
||||
order4.setOrderDesc("Fourth Order");
|
||||
order4.setOrderDate(new Date(2014, 10, 1));
|
||||
order4.setUser(user2);
|
||||
|
||||
order4.setOrderDesc("Fourth Order");
|
||||
order4.setOrderDate(new Date(2014, 10, 1));
|
||||
order4.setUser(user2);
|
||||
|
||||
order5.setOrderDesc("Fifth Order");
|
||||
order5.setOrderDate(new Date(2014, 9, 11));
|
||||
order5.setUser(user3);
|
||||
order5.setOrderDesc("Fifth Order");
|
||||
order5.setOrderDate(new Date(2014, 9, 11));
|
||||
order5.setUser(user3);
|
||||
|
||||
|
||||
session.saveOrUpdate(order1);
|
||||
session.saveOrUpdate(order2);
|
||||
session.saveOrUpdate(order3);
|
||||
session.saveOrUpdate(order4);
|
||||
session.saveOrUpdate(order5);
|
||||
session.saveOrUpdate(order1);
|
||||
session.saveOrUpdate(order2);
|
||||
session.saveOrUpdate(order3);
|
||||
session.saveOrUpdate(order4);
|
||||
session.saveOrUpdate(order5);
|
||||
|
||||
// session.saveOrUpdate(user1);
|
||||
tx.commit();
|
||||
session.close();
|
||||
|
||||
}
|
||||
// session.saveOrUpdate(user1);
|
||||
tx.commit();
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@
|
|||
<property name="hibernate.connection.username">root</property>
|
||||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
</session-factory>
|
||||
|
|
|
@ -10,6 +10,7 @@
|
|||
<property name="hibernate.connection.username">root</property>
|
||||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
||||
</session-factory>
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.hibernate.criteria;
|
||||
|
||||
import org.junit.runner.JUnitCore;
|
||||
import org.junit.runner.Result;
|
||||
import org.junit.runner.notification.Failure;
|
||||
|
||||
public class HibernateCriteriaTestRunner {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class);
|
||||
for (Failure failure : result.getFailures()) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.hibernate.criteria;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ HibernateCriteriaTest.class })
|
||||
|
||||
public class HibernateCriteriaTestSuite {
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.hibernate.fetching;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.fetching.view.FetchingAppView;
|
||||
|
||||
public class HibernateFetchingTest {
|
||||
|
||||
@Test
|
||||
public void testLazyFetching() {
|
||||
FetchingAppView fav = new FetchingAppView();
|
||||
fav.createTestData();
|
||||
assertFalse(fav.lazyLoaded());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEagerFetching() {
|
||||
FetchingAppView fav = new FetchingAppView();
|
||||
assertTrue(fav.eagerLoaded());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE hibernate-configuration PUBLIC
|
||||
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
|
||||
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
|
||||
<property name="hibernate.connection.username">root</property>
|
||||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE hibernate-configuration PUBLIC
|
||||
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
|
||||
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
|
||||
<property name="hibernate.connection.username">root</property>
|
||||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -111,6 +111,11 @@
|
|||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.jsonpath</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>2.2.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.model;
|
||||
|
||||
public class Greeting {
|
||||
private int id;
|
||||
private String message;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.spring.web.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
|
||||
public class ApplicationConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public ApplicationConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/").setViewName("index");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setViewClass(JstlView.class);
|
||||
bean.setPrefix("/WEB-INF/jsp/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.model.Greeting;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Controller
|
||||
public class GreetController {
|
||||
|
||||
@RequestMapping(value = "/homePage", method = RequestMethod.GET)
|
||||
public String index() {
|
||||
return "index";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json")
|
||||
@ResponseBody
|
||||
public Greeting greet() {
|
||||
Greeting greeting = new Greeting();
|
||||
greeting.setId(1);
|
||||
greeting.setMessage("Hello World!!!");
|
||||
return greeting;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json")
|
||||
@ResponseBody
|
||||
public Greeting greetWithPathVariable(@PathVariable("name") String name) {
|
||||
Greeting greeting = new Greeting();
|
||||
greeting.setId(1);
|
||||
greeting.setMessage("Hello World " + name + "!!!");
|
||||
return greeting;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json")
|
||||
@ResponseBody
|
||||
public Greeting greetWithQueryVariable(@RequestParam("name") String name) {
|
||||
Greeting greeting = new Greeting();
|
||||
greeting.setId(1);
|
||||
greeting.setMessage("Hello World " + name + "!!!");
|
||||
return greeting;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json")
|
||||
@ResponseBody
|
||||
public Greeting greetWithPost() {
|
||||
Greeting greeting = new Greeting();
|
||||
greeting.setId(1);
|
||||
greeting.setMessage("Hello World!!!");
|
||||
return greeting;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json")
|
||||
@ResponseBody
|
||||
public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) {
|
||||
Greeting greeting = new Greeting();
|
||||
greeting.setId(id);
|
||||
greeting.setMessage("Hello World " + name + "!!!");
|
||||
return greeting;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
<html>
|
||||
<body>
|
||||
<h1>Spring MVC - Integration Testing</h1>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,91 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
|
||||
import com.baeldung.spring.web.config.ApplicationConfig;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = {ApplicationConfig.class})
|
||||
public class GreetControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
private static final String CONTENT_TYPE = "application/json";
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWAC_whenServletContext_thenItProvidesGreetController() {
|
||||
ServletContext servletContext = wac.getServletContext();
|
||||
Assert.assertNotNull(servletContext);
|
||||
Assert.assertTrue(servletContext instanceof MockServletContext);
|
||||
Assert.assertNotNull(wac.getBean("greetController"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/homePage")).andDo(print()).andExpect(MockMvcResultMatchers.view().name("index"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn();
|
||||
Assert.assertEquals(CONTENT_TYPE, mvcResult.getResponse().getContentType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
public class GreetControllerTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
private static final String CONTENT_TYPE = "application/json";
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception {
|
||||
this.mockMvc.perform(get("/homePage")).andExpect(view().name("index"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World Doe!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE))
|
||||
.andExpect(jsonPath("$.message").value("Hello World!!!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1));
|
||||
}
|
||||
}
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security with Basic Authentication Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Article:
|
||||
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security Login Example Project
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security with Digest Authentication Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Article:
|
||||
- [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication)
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
## Spring Security with LDAP Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Article:
|
||||
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security Login Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Form Login](http://www.baeldung.com/spring-security-login)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security Persisted Remember Me Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security Login Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## REST API with Basic Authentication - Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## Spring Security for REST Example Project
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
## REST API with Digest Authentication - Example Project
|
||||
|
||||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication)
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
### Courses
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic)
|
||||
|
|
|
@ -1,74 +1,78 @@
|
|||
package org.baeldung.web.interceptor;
|
||||
|
||||
import java.util.Enumeration;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Enumeration;
|
||||
|
||||
public class LoggerInterceptor extends HandlerInterceptorAdapter {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
|
||||
private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
|
||||
|
||||
/** Executed before actual handler is executed **/
|
||||
@Override
|
||||
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
|
||||
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Executed before actual handler is executed
|
||||
**/
|
||||
@Override
|
||||
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
|
||||
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Executed before after handler is executed **/
|
||||
@Override
|
||||
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
|
||||
final ModelAndView modelAndView) throws Exception {
|
||||
log.info("[postHandle][" + request + "]");
|
||||
}
|
||||
/**
|
||||
* Executed before after handler is executed
|
||||
**/
|
||||
@Override
|
||||
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
|
||||
final ModelAndView modelAndView) throws Exception {
|
||||
log.info("[postHandle][" + request + "]");
|
||||
}
|
||||
|
||||
/** Executed after complete request is finished **/
|
||||
@Override
|
||||
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
|
||||
throws Exception {
|
||||
if (ex != null)
|
||||
ex.printStackTrace();
|
||||
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
|
||||
}
|
||||
/**
|
||||
* Executed after complete request is finished
|
||||
**/
|
||||
@Override
|
||||
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
|
||||
throws Exception {
|
||||
if (ex != null)
|
||||
ex.printStackTrace();
|
||||
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
|
||||
}
|
||||
|
||||
private String getParameters(final HttpServletRequest request) {
|
||||
final StringBuffer posted = new StringBuffer();
|
||||
final Enumeration<?> e = request.getParameterNames();
|
||||
if (e != null)
|
||||
posted.append("?");
|
||||
while (e.hasMoreElements()) {
|
||||
if (posted.length() > 1)
|
||||
posted.append("&");
|
||||
final String curr = (String) e.nextElement();
|
||||
posted.append(curr + "=");
|
||||
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
|
||||
posted.append("*****");
|
||||
} else {
|
||||
posted.append(request.getParameter(curr));
|
||||
}
|
||||
}
|
||||
private String getParameters(final HttpServletRequest request) {
|
||||
final StringBuffer posted = new StringBuffer();
|
||||
final Enumeration<?> e = request.getParameterNames();
|
||||
if (e != null)
|
||||
posted.append("?");
|
||||
while (e != null && e.hasMoreElements()) {
|
||||
if (posted.length() > 1)
|
||||
posted.append("&");
|
||||
final String curr = (String) e.nextElement();
|
||||
posted.append(curr).append("=");
|
||||
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
|
||||
posted.append("*****");
|
||||
} else {
|
||||
posted.append(request.getParameter(curr));
|
||||
}
|
||||
}
|
||||
|
||||
final String ip = request.getHeader("X-FORWARDED-FOR");
|
||||
final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
|
||||
if (!Strings.isNullOrEmpty(ipAddr))
|
||||
posted.append("&_psip=" + ipAddr);
|
||||
return posted.toString();
|
||||
}
|
||||
final String ip = request.getHeader("X-FORWARDED-FOR");
|
||||
final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
|
||||
if (!Strings.isNullOrEmpty(ipAddr))
|
||||
posted.append("&_psip=" + ipAddr);
|
||||
return posted.toString();
|
||||
}
|
||||
|
||||
private String getRemoteAddr(final HttpServletRequest request) {
|
||||
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
|
||||
if (ipFromHeader != null && ipFromHeader.length() > 0) {
|
||||
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
|
||||
return ipFromHeader;
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
private String getRemoteAddr(final HttpServletRequest request) {
|
||||
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
|
||||
if (ipFromHeader != null && ipFromHeader.length() > 0) {
|
||||
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
|
||||
return ipFromHeader;
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
### Courses
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
||||
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/)
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>basic-secured-server</module>
|
||||
<module>client-auth-server</module>
|
||||
<module>spring-security-x509-basic-auth</module>
|
||||
<module>spring-security-x509-client-auth</module>
|
||||
</modules>
|
||||
|
||||
<parent>
|
||||
|
|
Loading…
Reference in New Issue