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 {
@ -40,12 +37,12 @@ public class GsonSerializeTest {
MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));
String expectedOutput = new GsonBuilder() String expectedOutput = new GsonBuilder()
.setPrettyPrinting() .setPrettyPrinting()
.serializeNulls() .serializeNulls()
.disableHtmlEscaping() .disableHtmlEscaping()
.create() .create()
.toJson(new JsonParser() .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\"}]}")); .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); Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput);
} }
} }

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,71 +3,80 @@ 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 Long orderId;
private Date orderDate;
private String orderDesc;
private User user;
public OrderDetail() {
}
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;
return true;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
private static final long serialVersionUID = 1L;
private Long orderId;
private Date orderDate;
private String orderDesc;
private User user;
public OrderDetail(){
}
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;
return true;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
} }

View File

@ -5,92 +5,90 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
public class User implements Serializable { public class User implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Long userId; private Long userId;
private String userName; private String userName;
private String firstName; private String firstName;
private String lastName; private String lastName;
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) {
super(); super();
this.userId = userId; this.userId = userId;
this.userName = userName; this.userName = userName;
this.firstName = firstName; this.firstName = firstName;
this.lastName = lastName; this.lastName = lastName;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
final User other = (User) obj; final User other = (User) obj;
if (userId == null) { if (userId == null) {
if (other.userId != null) if (other.userId != null)
return false; return false;
} else if (!userId.equals(other.userId)) } else if (!userId.equals(other.userId))
return false; return false;
return true; return true;
} }
public Long getUserId() { public Long getUserId() {
return userId; return userId;
} }
public void setUserId(final Long userId) { public void setUserId(final Long userId) {
this.userId = userId; this.userId = userId;
} }
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
public void setUserName(final String userName) { public void setUserName(final String userName) {
this.userName = userName; this.userName = userName;
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(final String firstName) { public void setFirstName(final String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(final String lastName) { public void setLastName(final String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
public Set<OrderDetail> getOrderDetail() { public Set<OrderDetail> getOrderDetail() {
return orderDetail; return orderDetail;
} }
public void setOrderDetail(Set<OrderDetail> orderDetail) { public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail; this.orderDetail = orderDetail;
} }
} }

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;
}
public static Session getHibernateSession() { return new Configuration()
System.out.println("Loading eager"); .configure(configFileName)
SessionFactory sf = null; .buildSessionFactory().openSession();
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); }
final Session session = sf.openSession();
return session; public static Session getHibernateSession() {
} return new Configuration()
.configure("fetching.cfg.xml")
.buildSessionFactory()
.openSession();
}
} }

View File

@ -17,99 +17,94 @@ import com.baeldung.hibernate.fetching.model.User;
public class FetchingAppView { public class FetchingAppView {
public FetchingAppView(){
}
//lazily loaded public FetchingAppView() {
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));
}
//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));
}
//creates test data
//call this method to create the data in the database
public void createTestData() {
final Session session = HibernateUtil.getHibernateSession(); }
Transaction tx = null; 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();
tx = session.beginTransaction(); return (Hibernate.isInitialized(orderDetailSet));
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);
user2.setFirstName("Navneeta");
user2.setLastName("Mukherjee");
user2.setUserName("nmukh");
session.save(user2);
user3.setFirstName("Molly");
user3.setLastName("Banerjee");
user3.setUserName("mollyb");
session.save(user3);
final OrderDetail order1 = new OrderDetail(); public boolean eagerLoaded() {
final OrderDetail order2 = new OrderDetail(); final Session sessionEager = HibernateUtil.getHibernateSession();
final OrderDetail order3 = new OrderDetail(); //data should be loaded in the following line
final OrderDetail order4 = new OrderDetail(); //also note the queries generated
final OrderDetail order5 = new OrderDetail(); List<User> users = sessionEager.createQuery("From User").list();
User userEagerLoaded = users.get(3);
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
order1.setOrderDesc("First Order"); return (Hibernate.isInitialized(orderDetailSet));
order1.setOrderDate(new Date(2014, 10, 12)); }
order1.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);
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);
session.saveOrUpdate(order1);
session.saveOrUpdate(order2);
session.saveOrUpdate(order3);
session.saveOrUpdate(order4);
session.saveOrUpdate(order5);
// session.saveOrUpdate(user1);
tx.commit();
session.close();
} //creates test data
//call this method to create the data in the database
public void createTestData() {
final Session session = HibernateUtil.getHibernateSession();
Transaction 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);
user2.setFirstName("Navneeta");
user2.setLastName("Mukherjee");
user2.setUserName("nmukh");
session.save(user2);
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();
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);
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);
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(user1);
tx.commit();
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,74 +1,78 @@
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 **/ /**
@Override * Executed before actual handler is executed
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { **/
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); @Override
return true; 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 * Executed before after handler is executed
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, **/
final ModelAndView modelAndView) throws Exception { @Override
log.info("[postHandle][" + request + "]"); 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 * Executed after complete request is finished
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) **/
throws Exception { @Override
if (ex != null) public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
ex.printStackTrace(); throws Exception {
log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); if (ex != null)
} ex.printStackTrace();
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
}
private String getParameters(final HttpServletRequest request) { private String getParameters(final HttpServletRequest request) {
final StringBuffer posted = new StringBuffer(); final StringBuffer posted = new StringBuffer();
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 {
posted.append(request.getParameter(curr)); posted.append(request.getParameter(curr));
} }
} }
final String ip = request.getHeader("X-FORWARDED-FOR"); final String ip = request.getHeader("X-FORWARDED-FOR");
final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip; final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
if (!Strings.isNullOrEmpty(ipAddr)) if (!Strings.isNullOrEmpty(ipAddr))
posted.append("&_psip=" + ipAddr); posted.append("&_psip=" + ipAddr);
return posted.toString(); return posted.toString();
} }
private String getRemoteAddr(final HttpServletRequest request) { private String getRemoteAddr(final HttpServletRequest request) {
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR"); final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
if (ipFromHeader != null && ipFromHeader.length() > 0) { if (ipFromHeader != null && ipFromHeader.length() > 0) {
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader); log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
return ipFromHeader; return ipFromHeader;
} }
return request.getRemoteAddr(); return request.getRemoteAddr();
} }
} }

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>