Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Christian Raedel 2016-08-14 15:50:40 +02:00
commit 21550cd2f8
57 changed files with 743 additions and 350 deletions

View File

@ -1,14 +1,14 @@
package org.baeldung.gson.deserialization; 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.ActorGson;
import org.baeldung.gson.entities.Movie; import org.baeldung.gson.entities.Movie;
import org.baeldung.gson.serialization.ActorGsonDeserializer; import org.baeldung.gson.serialization.ActorGsonDeserializer;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import com.google.gson.Gson; import java.text.ParseException;
import com.google.gson.GsonBuilder;
public class GsonDeserializeTest { public class GsonDeserializeTest {

View File

@ -1,20 +1,17 @@
package org.baeldung.gson.serialization; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser; 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 { public class GsonSerializeTest {

View File

@ -1,20 +1,18 @@
package org.baeldung.jackson.deserialization; package org.baeldung.jackson.deserialization;
import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.baeldung.jackson.entities.Movie; import org.baeldung.jackson.entities.Movie;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException; import java.io.IOException;
import com.fasterxml.jackson.databind.JsonMappingException; import java.text.DateFormat;
import com.fasterxml.jackson.databind.ObjectMapper; import java.text.SimpleDateFormat;
public class JacksonDeserializeTest { public class JacksonDeserializeTest {
@Test @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\"]}]}"; String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -25,7 +23,7 @@ public class JacksonDeserializeTest {
} }
@Test @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\"]}]}"; String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";

View File

@ -27,7 +27,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.el</groupId> <groupId>javax.el</groupId>
<artifactId>el-api</artifactId> <artifactId>javax.el-api</artifactId>
<version>${javax.el.version}</version> <version>${javax.el.version}</version>
</dependency> </dependency>
@ -126,8 +126,8 @@
<org.springframework.version>4.2.5.RELEASE</org.springframework.version> <org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<!-- JSF --> <!-- JSF -->
<com.sun.faces.version>2.1.7</com.sun.faces.version> <com.sun.faces.version>2.2.13</com.sun.faces.version>
<javax.el.version>2.2</javax.el.version> <javax.el.version>3.0.0</javax.el.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version> <org.slf4j.version>1.7.13</org.slf4j.version>

View File

@ -1,13 +1,17 @@
package com.baeldung.springintegration.controllers; package com.baeldung.springintegration.controllers;
import java.util.Random;
import javax.annotation.PostConstruct; 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.Application;
import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage;
import javax.el.LambdaExpression;
import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped; import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext; import javax.faces.context.FacesContext;
import java.util.Collection;
import java.util.Random;
@ManagedBean(name = "ELBean") @ManagedBean(name = "ELBean")
@ViewScoped @ViewScoped
@ -16,22 +20,37 @@ public class ELSampleBean {
private String firstName; private String firstName;
private String lastName; private String lastName;
private String pageDescription = "This page demos JSF EL Basics"; private String pageDescription = "This page demos JSF EL Basics";
public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON";
private int pageCounter; private int pageCounter;
private Random randomIntGen = new Random(); private Random randomIntGen = new Random();
@PostConstruct @PostConstruct
public void init() { public void init() {
pageCounter = randomIntGen.nextInt(); 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 void save() {
} }
public static String constantField() {
return constantField;
}
public void saveFirstName(String firstName) { public void saveFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public Long multiplyValue(LambdaExpression expr) {
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter);
return theResult;
}
public void saveByELEvaluation() { public void saveByELEvaluation() {
firstName = (String) evaluateEL("#{firstName.value}", String.class); firstName = (String) evaluateEL("#{firstName.value}", String.class);

View File

@ -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>

View File

@ -1,8 +1,5 @@
package org.baeldung.main; package org.baeldung.main;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.error.SpringHelloServletRegistrationBean;
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
import org.baeldung.controller.servlet.HelloWorldServlet; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController @RestController
@EnableAutoConfiguration @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" }) @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; 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 @Bean
@Autowired @Autowired
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {

View File

@ -3,7 +3,7 @@ package com.baeldung.hibernate.fetching.model;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Date; import java.sql.Date;
public class OrderDetail implements Serializable{ public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Long orderId; private Long orderId;
@ -11,7 +11,7 @@ public class OrderDetail implements Serializable{
private String orderDesc; private String orderDesc;
private User user; private User user;
public OrderDetail(){ public OrderDetail() {
} }
@ -24,21 +24,27 @@ public class OrderDetail implements Serializable{
public Date getOrderDate() { public Date getOrderDate() {
return orderDate; return orderDate;
} }
public void setOrderDate(Date orderDate) { public void setOrderDate(Date orderDate) {
this.orderDate = orderDate; this.orderDate = orderDate;
} }
public String getOrderDesc() { public String getOrderDesc() {
return orderDesc; return orderDesc;
} }
public void setOrderDesc(String orderDesc) { public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc; this.orderDesc = orderDesc;
} }
public User getUser() { public User getUser() {
return user; return user;
} }
public void setUser(User user) { public void setUser(User user) {
this.user = user; this.user = user;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -46,6 +52,7 @@ public class OrderDetail implements Serializable{
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
@ -63,9 +70,11 @@ public class OrderDetail implements Serializable{
return true; return true;
} }
public Long getOrderId() { public Long getOrderId() {
return orderId; return orderId;
} }
public void setOrderId(Long orderId) { public void setOrderId(Long orderId) {
this.orderId = orderId; this.orderId = orderId;
} }

View File

@ -14,7 +14,6 @@ public class User implements Serializable {
private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>(); private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>();
public User() { public User() {
} }
public User(final Long userId, final String userName, final String firstName, final String lastName) { public User(final Long userId, final String userName, final String firstName, final String lastName) {
@ -92,5 +91,4 @@ public class User implements Serializable {
} }
} }

View File

@ -1,35 +1,30 @@
package com.baeldung.hibernate.fetching.util; package com.baeldung.hibernate.fetching.util;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
public class HibernateUtil { public class HibernateUtil {
private static SessionFactory factory;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static Session getHibernateSession(String fetchMethod) { public static Session getHibernateSession(String fetchMethod) {
//two config files are there //two config files are there
//one with lazy loading enabled //one with lazy loading enabled
//another lazy = false //another lazy = false
SessionFactory sf = null;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); final String configFileName = "lazy".equals(fetchMethod) ?
} "fetchingLazy.cfg.xml" :
// fetching.cfg.xml is used for this example "fetching.cfg.xml";
final Session session = sf.openSession();
return session; return new Configuration()
.configure(configFileName)
.buildSessionFactory().openSession();
} }
public static Session getHibernateSession() { public static Session getHibernateSession() {
System.out.println("Loading eager"); return new Configuration()
SessionFactory sf = null; .configure("fetching.cfg.xml")
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); .buildSessionFactory()
final Session session = sf.openSession(); .openSession();
return session;
} }
} }

View File

@ -18,30 +18,28 @@ import com.baeldung.hibernate.fetching.model.User;
public class FetchingAppView { public class FetchingAppView {
public FetchingAppView(){ public FetchingAppView() {
} }
//lazily loaded public boolean lazyLoaded() {
public boolean lazyLoaded(){
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List<User> users = sessionLazy.createQuery("From User").list(); List<User> users = sessionLazy.createQuery("From User").list();
User userLazyLoaded = new User(); User userLazyLoaded = users.get(3);
userLazyLoaded = users.get(3);
//since data is lazyloaded so data won't be initialized //since data is lazyloaded so data won't be initialized
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail(); Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet)); return (Hibernate.isInitialized(orderDetailSet));
} }
//eagerly loaded public boolean eagerLoaded() {
public boolean eagerLoaded(){
final Session sessionEager = HibernateUtil.getHibernateSession(); final Session sessionEager = HibernateUtil.getHibernateSession();
//data should be loaded in the following line //data should be loaded in the following line
//also note the queries generated //also note the queries generated
List<User> users =sessionEager.createQuery("From User").list(); List<User> users = sessionEager.createQuery("From User").list();
User userEagerLoaded = new User(); User userEagerLoaded = users.get(3);
userEagerLoaded = users.get(3);
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail(); Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet)); return (Hibernate.isInitialized(orderDetailSet));
} }
@ -51,10 +49,8 @@ public class FetchingAppView {
public void createTestData() { public void createTestData() {
final Session session = HibernateUtil.getHibernateSession(); final Session session = HibernateUtil.getHibernateSession();
Transaction tx = session.beginTransaction();
Transaction tx = null;
tx = session.beginTransaction();
final User user1 = new User(); final User user1 = new User();
final User user2 = new User(); final User user2 = new User();
final User user3 = new User(); final User user3 = new User();
@ -110,6 +106,5 @@ public class FetchingAppView {
// session.saveOrUpdate(user1); // session.saveOrUpdate(user1);
tx.commit(); tx.commit();
session.close(); session.close();
} }
} }

View File

@ -10,6 +10,7 @@
<property name="hibernate.connection.username">root</property> <property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">iamtheking</property> <property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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/User.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" /> <mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
</session-factory> </session-factory>

View File

@ -10,6 +10,7 @@
<property name="hibernate.connection.username">root</property> <property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">iamtheking</property> <property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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/OrderDetail.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" /> <mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
</session-factory> </session-factory>

View File

@ -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()) {
}
}
}

View File

@ -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 {
}

View File

@ -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());
}
}

View File

@ -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>

View File

@ -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>

View File

@ -111,6 +111,11 @@
<version>${mockito.version}</version> <version>${mockito.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,5 @@
<html>
<body>
<h1>Spring MVC - Integration Testing</h1>
</body>
</html>

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -3,7 +3,7 @@
## Spring Security with Basic Authentication Example Project ## Spring Security with Basic Authentication Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Article: ### Relevant Article:
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)

View File

@ -1,2 +1,2 @@
###The Course ###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring The "REST With Spring" Classes: http://github.learnspringsecurity.com

View File

@ -1,2 +1,2 @@
###The Course ###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring The "REST With Spring" Classes: http://github.learnspringsecurity.com

View File

@ -3,7 +3,7 @@
## Spring Security Login Example Project ## Spring Security Login Example Project
###The Course ###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring The "REST With Spring" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) - [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me)

View File

@ -3,7 +3,7 @@
## Spring Security with Digest Authentication Example Project ## Spring Security with Digest Authentication Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Article: ### Relevant Article:
- [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication) - [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication)

View File

@ -2,7 +2,7 @@
## Spring Security with LDAP Example Project ## Spring Security with LDAP Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Article: ### Relevant Article:
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)

View File

@ -3,7 +3,7 @@
## Spring Security Login Example Project ## Spring Security Login Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [Spring Security Form Login](http://www.baeldung.com/spring-security-login) - [Spring Security Form Login](http://www.baeldung.com/spring-security-login)

View File

@ -3,7 +3,7 @@
## Spring Security Persisted Remember Me Example Project ## Spring Security Persisted Remember Me Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) - [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me)

View File

@ -3,7 +3,7 @@
## Spring Security Login Example Project ## Spring Security Login Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [HttpSessionListener Example Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) - [HttpSessionListener Example Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics)

View File

@ -3,7 +3,7 @@
## REST API with Basic Authentication - Example Project ## REST API with Basic Authentication - Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### 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) - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1)

View File

@ -3,7 +3,7 @@
## Spring Security for REST Example Project ## Spring Security for REST Example Project
###The Course ###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring The "REST With Spring" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider) - [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider)

View File

@ -3,7 +3,7 @@
## REST API with Digest Authentication - Example Project ## REST API with Digest Authentication - Example Project
###The Course ###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles: ### Relevant Articles:
- [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication) - [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication)

View File

@ -5,7 +5,7 @@
### Courses ### Courses
The "REST With Spring" Classes: http://bit.ly/restwithspring 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: ### Relevant Articles:
- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic)

View File

@ -1,36 +1,40 @@
package org.baeldung.web.interceptor; package org.baeldung.web.interceptor;
import java.util.Enumeration; import com.google.common.base.Strings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 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 { 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 **/ /**
* Executed before actual handler is executed
**/
@Override @Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
return true; return true;
} }
/** Executed before after handler is executed **/ /**
* Executed before after handler is executed
**/
@Override @Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception { final ModelAndView modelAndView) throws Exception {
log.info("[postHandle][" + request + "]"); log.info("[postHandle][" + request + "]");
} }
/** Executed after complete request is finished **/ /**
* Executed after complete request is finished
**/
@Override @Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
throws Exception { throws Exception {
@ -44,11 +48,11 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
final Enumeration<?> e = request.getParameterNames(); final Enumeration<?> e = request.getParameterNames();
if (e != null) if (e != null)
posted.append("?"); posted.append("?");
while (e.hasMoreElements()) { while (e != null && e.hasMoreElements()) {
if (posted.length() > 1) if (posted.length() > 1)
posted.append("&"); posted.append("&");
final String curr = (String) e.nextElement(); final String curr = (String) e.nextElement();
posted.append(curr + "="); posted.append(curr).append("=");
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) { if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
posted.append("*****"); posted.append("*****");
} else { } else {

View File

@ -5,7 +5,7 @@
### Courses ### Courses
The "REST With Spring" Classes: http://bit.ly/restwithspring 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: ### 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/) - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/)

View File

@ -9,8 +9,8 @@
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
<module>basic-secured-server</module> <module>spring-security-x509-basic-auth</module>
<module>client-auth-server</module> <module>spring-security-x509-client-auth</module>
</modules> </modules>
<parent> <parent>