Merge branch 'master' of https://github.com/eugenp/tutorials into sanketmeghani-master

This commit is contained in:
Zeger Hendrikse 2016-09-27 20:34:17 +02:00
commit 1017089825
72 changed files with 1173 additions and 765 deletions

View File

@ -60,12 +60,8 @@
<configuration>
<source>1.9</source>
<target>1.9</target>
<verbose>true</verbose>
<!-- <executable>C:\develop\jdks\jdk-9_ea122\bin\javac</executable>
<compilerVersion>1.9</compilerVersion> -->
</configuration>
</plugin>
<plugin>
@ -85,12 +81,7 @@
<!-- maven plugins -->
<!--
<maven-war-plugin.version>2.6</maven-war-plugin.version>
maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->

View File

@ -0,0 +1,58 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class Java9OptionalsStreamTest {
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
@Test
public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.java9;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

View File

@ -0,0 +1,21 @@
package com.baeldung.java9;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class OptionalToStreamTest {
@Test
public void testOptionalToStream() {
Optional<String> op = Optional.ofNullable("String value");
Stream<String> strOptionalStream = op.stream();
Stream<String> filteredStream = strOptionalStream.filter((str) -> {
return str != null && str.startsWith("String");
});
assertEquals(1, filteredStream.count());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java9;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SetExamplesTest {
@Test
public void testUnmutableSet() {
Set<String> strKeySet = Set.of("key1", "key2", "key3");
try {
strKeySet.add("newKey");
} catch (UnsupportedOperationException uoe) {
}
assertEquals(strKeySet.size(), 3);
}
@Test
public void testArrayToSet() {
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Set<Integer> intSet = Set.of(intArray);
assertEquals(intSet.size(), intArray.length);
}
}

View File

@ -0,0 +1,65 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@ -11,13 +11,11 @@ public class Rectangle extends Shape {
@Override
public double area() {
// A = w * l
return width * length;
}
@Override
public double perimeter() {
// P = 2(w + l)
return 2 * (width + length);
}

View File

@ -22,11 +22,10 @@ public class ComplexClassTest {
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -12,11 +12,10 @@ public class PrimitiveClassTest {
PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -15,11 +15,10 @@ public class SquareClassTest {
Square dObject = new Square(20, Color.BLUE);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -18,18 +18,18 @@ public class ArrayListTest {
@Before
public void setUp() {
List<String> xs = LongStream.range(0, 16)
List<String> list = LongStream.range(0, 16)
.boxed()
.map(Long::toHexString)
.collect(toCollection(ArrayList::new));
stringsToSearch = new ArrayList<>(xs);
stringsToSearch.addAll(xs);
stringsToSearch = new ArrayList<>(list);
stringsToSearch.addAll(list);
}
@Test
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
List<String> xs = new ArrayList<>();
assertTrue(xs.isEmpty());
List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());
}
@Test
@ -37,29 +37,29 @@ public class ArrayListTest {
Collection<Integer> numbers =
IntStream.range(0, 10).boxed().collect(toSet());
List<Integer> xs = new ArrayList<>(numbers);
assertEquals(10, xs.size());
assertTrue(numbers.containsAll(xs));
List<Integer> list = new ArrayList<>(numbers);
assertEquals(10, list.size());
assertTrue(numbers.containsAll(list));
}
@Test
public void givenElement_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>();
List<Long> list = new ArrayList<>();
xs.add(1L);
xs.add(2L);
xs.add(1, 3L);
list.add(1L);
list.add(2L);
list.add(1, 3L);
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs));
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
}
@Test
public void givenCollection_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
LongStream.range(4, 10).boxed()
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> xs.addAll(0, ys)));
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
}
@Test
@ -106,27 +106,27 @@ public class ArrayListTest {
@Test
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(xs);
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(list);
xs.remove(0);
assertThat(xs.get(0), equalTo(8));
list.remove(0);
assertThat(list.get(0), equalTo(8));
xs.remove(Integer.valueOf(0));
assertFalse(xs.contains(0));
list.remove(Integer.valueOf(0));
assertFalse(list.contains(0));
}
@Test
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = xs.listIterator(xs.size());
List<Integer> result = new ArrayList<>(xs.size());
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = list.listIterator(list.size());
List<Integer> result = new ArrayList<>(list.size());
while (it.hasPrevious()) {
result.add(it.previous());
}
Collections.reverse(xs);
assertThat(result, equalTo(xs));
Collections.reverse(list);
assertThat(result, equalTo(list));
}
@Test

View File

@ -1,63 +0,0 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
public class ComplexClass {
private ArrayList<?> genericArrayList;
private HashSet<Integer> integerHashSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericArrayList = genericArrayList;
this.integerHashSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericArrayList == null) ? 0 : genericArrayList.hashCode());
result = prime * result + ((integerHashSet == null) ? 0 : integerHashSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericArrayList == null) {
if (other.genericArrayList != null)
return false;
} else if (!genericArrayList.equals(other.genericArrayList))
return false;
if (integerHashSet == null) {
if (other.integerHashSet != null)
return false;
} else if (!integerHashSet.equals(other.integerHashSet))
return false;
return true;
}
protected ArrayList<?> getGenericArrayList() {
return genericArrayList;
}
protected void setGenericArrayList(ArrayList<?> genericArrayList) {
this.genericArrayList = genericArrayList;
}
protected HashSet<Integer> getIntegerHashSet() {
return integerHashSet;
}
protected void setIntegerHashSet(HashSet<Integer> integerHashSet) {
this.integerHashSet = integerHashSet;
}
}

View File

@ -1,6 +0,0 @@
=========
## ElasticSearch
### Relevant Articles:
- [A Guide to ElasticSearch](http://www.baeldung.com/????????)

View File

@ -1,35 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>elasticsearch</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -22,24 +22,17 @@ public class FrontControllerServlet extends HttpServlet {
private FrontCommand getCommand(HttpServletRequest request) {
try {
return (FrontCommand) getCommandClass(request)
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to get command!", e);
}
}
private Class getCommandClass(HttpServletRequest request) {
try {
return Class.forName(
Class type = Class.forName(
String.format(
"com.baeldung.enterprise.patterns.front.controller.commands.%sCommand",
request.getParameter("command")
)
);
} catch (ClassNotFoundException e) {
return UnknownCommand.class;
return (FrontCommand) type
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
return new UnknownCommand();
}
}
}

View File

@ -1,40 +1,15 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public class Book {
private String author;
private String title;
private Double price;
public interface Book {
String getAuthor();
public Book() {
}
void setAuthor(String author);
public Book(String author, String title, Double price) {
this.author = author;
this.title = title;
this.price = price;
}
String getTitle();
public String getAuthor() {
return author;
}
void setTitle(String title);
public void setAuthor(String author) {
this.author = author;
}
Double getPrice();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
void setPrice(Double price);
}

View File

@ -0,0 +1,46 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public class BookImpl implements Book {
private String author;
private String title;
private Double price;
public BookImpl() {
}
public BookImpl(String author, String title, Double price) {
this.author = author;
this.title = title;
this.price = price;
}
@Override
public String getAuthor() {
return author;
}
@Override
public void setAuthor(String author) {
this.author = author;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public Double getPrice() {
return price;
}
@Override
public void setPrice(Double price) {
this.price = price;
}
}

View File

@ -3,8 +3,8 @@ package com.baeldung.enterprise.patterns.front.controller.data;
public interface Bookshelf {
default void init() {
add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99));
add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88));
add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99));
add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88));
}
Bookshelf getInstance();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

@ -1,5 +1,5 @@
@startuml
scale 1.5
class Handler {
doGet
doPost

View File

@ -15,7 +15,13 @@
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- SLF4J - Log4J dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
-->
<!--log4j2 dependencies-->
<dependency>
@ -28,22 +34,34 @@
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<!--disruptor for log4j2 async logging-->
<!--disruptor for log4j2 async logging-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
<!-- SLF4J - Log4J2 dependency
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
-->
<!--logback dependencies-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- SLF4J - JCL dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jcl</artifactId>
<version>1.7.21</version>
</dependency>
-->
</dependencies>
<build>
<plugins>

View File

@ -0,0 +1,20 @@
package com.baeldung.slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml
*/
public class Slf4jExample {
private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
public static void main(String[] args) {
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
String variable = "Hello John";
logger.debug("Printing variable value {} ", variable);
}
}

View File

@ -91,7 +91,6 @@
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-jpa</module>
<module>spring-jpa-jndi</module>
<module>spring-katharsis</module>
<module>spring-mockito</module>
<module>spring-mvc-java</module>

View File

@ -0,0 +1,36 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>selenium-junit-testng</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,29 @@
package main.java.com.baeldung.selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumExample {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
public SeleniumExample() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
public void closeWindow() {
webDriver.close();
}
public String getActualTitle() {
return webDriver.getTitle();
}
public String getExpectedTitle() {
return expectedTitle;
}
}

View File

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestSeleniumWithJUnit {
private SeleniumExample seleniumExample;
@Before
public void setUp() {
seleniumExample = new SeleniumExample();
}
@After
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private SeleniumExample seleniumExample;
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldun.selenium.testng;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@BeforeSuite
public void setUp() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
@AfterSuite
public void tearDown() {
webDriver.close();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitleReturned = webDriver.getTitle();
assertNotNull(actualTitleReturned);
assertEquals(expectedTitle, actualTitleReturned);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.selenium.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestSeleniumWithJUnit {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@Before
public void setUp() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
@After
public void tearDown() {
webDriver.close();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitleReturned = webDriver.getTitle();
assertNotNull(actualTitleReturned);
assertEquals(expectedTitle, actualTitleReturned);
}
}

View File

@ -0,0 +1,27 @@
## Spring Cloud Config ##
To get this example working, you have to initialize a new *Git* repository in
the ```client-config``` directory first *and* you have to set the environment variable
```CONFIG_REPO``` to an absolute path of that directory.
```
$> cd client-config
$> git init
$> git add .
$> git commit -m 'Initial commit'
$> export CONFIG_REPO=$(pwd)
```
Then you're able to run the examples with ```mvn install spring-boot:run```.
### Docker ###
To get the *Docker* examples working, you have to repackage the ```spring-cloud-config-server```
and ```spring-cloud-config-client``` modules first:
```
$> mvn install spring-boot:repackage
```
Don't forget to download the *Java JCE* package from
(Oracle)[http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html].

View File

@ -0,0 +1,6 @@
FROM alpine-java:base
MAINTAINER baeldung.com
RUN apk --no-cache add netcat-openbsd
COPY files/spring-cloud-config-client-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-client.jar
COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/
RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh

View File

@ -0,0 +1,9 @@
FROM alpine-java:base
MAINTAINER baeldung.com
COPY files/spring-cloud-config-server-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-server.jar
ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \
{"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}'
ENTRYPOINT ["/usr/bin/java"]
CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"]
VOLUME /var/lib/spring-cloud/config-repo
EXPOSE 8888

View File

@ -0,0 +1,2 @@
/UnlimitedJCEPolicyJDK8
/*.jar

View File

@ -0,0 +1,8 @@
#!/bin/sh
while ! nc -z config-server 8888 ; do
echo "Waiting for upcoming Config Server"
sleep 2
done
java -jar /opt/spring-cloud/lib/config-client.jar

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<packaging>pom</packaging>
<modules>
<module>spring-cloud-config-server</module>
<module>spring-cloud-config-client</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>1.4.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -69,6 +69,17 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -1,52 +1,52 @@
package com.baeldung.elasticsearch;
import java.util.Date;
public class Person {
private int age;
private String fullName;
private Date dateOfBirth;
public Person() {
}
public Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName = fullName;
this.dateOfBirth = dateOfBirth;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]";
}
}
package com.baeldung.elasticsearch;
import java.util.Date;
public class Person {
private int age;
private String fullName;
private Date dateOfBirth;
public Person() {
}
public Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName = fullName;
this.dateOfBirth = dateOfBirth;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]";
}
}

View File

@ -5,6 +5,7 @@ import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -102,13 +103,9 @@ public class ElasticSearchUnitTests {
try {
response2.getHits();
response3.getHits();
SearchHit[] searchHits = response.getHits().getHits();
List<Person> results = new ArrayList<Person>();
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
Person person = JSON.parseObject(sourceAsString, Person.class);
results.add(person);
}
List<SearchHit> searchHits = Arrays.asList(response.getHits().getHits());
final List<Person> results = new ArrayList<Person>();
searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class)));
} catch (Exception e) {
isExecutedSuccessfully = false;
}

View File

@ -1,7 +1,7 @@
## Spring Data Neo4j
### Relevant Articles:
- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-tutorial)
- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro)
### Build the Project with Tests Running
```

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,7 +0,0 @@
=========
## Spring JPA using JNDI Project
### Relevant Articles:
- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](http://www.baeldung.com/spring-jpa-fndi)

View File

@ -1,145 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-jpa-jndi</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-jpa-jndi</name>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${javax.servlet.jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet.servlet-api.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.5</version>
</dependency>
</dependencies>
<build>
<finalName>spring-jpa-jndi</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.2.RELEASE</org.springframework.version>
<javassist.version>3.20.0-GA</javassist.version>
<!-- web -->
<javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<spring-data-jpa.version>1.8.2.RELEASE</spring-data-jpa.version>
<h2.version>1.4.192</h2.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
<!-- <maven-war-plugin.version>2.6</maven-war-plugin.version> -->
</properties>
</project>

View File

@ -1,22 +0,0 @@
package org.baeldung.persistence.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao {
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
public List<Foo> findAll() {
return entityManager.createQuery("from " + Foo.class.getName()).getResultList();
}
}

View File

@ -1,34 +0,0 @@
package org.baeldung.persistence.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,22 +0,0 @@
package org.baeldung.persistence.service;
import java.util.List;
import org.baeldung.persistence.dao.FooDao;
import org.baeldung.persistence.model.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class FooService {
@Autowired
private FooDao dao;
public List<Foo> findAll() {
return dao.findAll();
}
}

View File

@ -1,20 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -4,6 +4,7 @@
<groupId>com.baeldung</groupId>
<artifactId>spring-jpa</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-jpa</name>
@ -21,6 +22,11 @@
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
@ -73,6 +79,18 @@
<artifactId>javax.el-api</artifactId>
<version>2.2.5</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${javax.servlet.jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet.servlet-api.version}</version>
</dependency>
<!-- utils -->
@ -147,6 +165,16 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -197,6 +225,10 @@
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<spring-data-jpa.version>1.10.2.RELEASE</spring-data-jpa.version>
<h2.version>1.4.192</h2.version>
<!-- web -->
<javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
@ -224,6 +256,7 @@
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
<!-- <maven-war-plugin.version>2.6</maven-war-plugin.version> -->
</properties>

View File

@ -36,7 +36,7 @@ public class PersistenceJNDIConfig {
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
@ -46,12 +46,8 @@ public class PersistenceJNDIConfig {
}
@Bean
public DataSource dataSource() {
try {
return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
} catch (NamingException e) {
throw new IllegalArgumentException("Error looking up JNDI datasource", e);
}
public DataSource dataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
}
@Bean

View File

@ -182,7 +182,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -192,16 +191,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
@ -216,7 +213,7 @@
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<containerId>tomcat8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
@ -234,6 +231,61 @@
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- Spring -->
@ -266,7 +318,7 @@
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
</properties>

View File

@ -7,7 +7,7 @@ import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class RequestMappingLiveTest {
private static String BASE_URI = "http://localhost:8080/spring-rest/ex/";
private static String BASE_URI = "http://localhost:8082/spring-rest/ex/";
@Test
public void givenSimplePath_whenGetFoos_thenOk() {

View File

@ -21,9 +21,9 @@ import org.springframework.web.client.RestTemplate;
/**
* Integration Test class. Tests methods hits the server's rest services.
*/
public class SpringHttpMessageConvertersIntegrationTestsCase {
public class SpringHttpMessageConvertersLiveTest {
private static String BASE_URI = "http://localhost:8080/spring-rest/";
private static String BASE_URI = "http://localhost:8082/spring-rest/";
/**
* Without specifying Accept Header, uses the default response from the

View File

@ -31,9 +31,8 @@ public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
request.setAttribute("executionTime", startTime);
if (UserInterceptor.isUserLogged()) {
session = request.getSession();
log.info("Who is logged in: " + SecurityContextHolder.getContext().getAuthentication().getName());
log.info("Time since last request in this session: "
+ (System.currentTimeMillis() - request.getSession().getLastAccessedTime()) + " ms");
log.info("Time since last request in this session: {} ms",
System.currentTimeMillis() - request.getSession().getLastAccessedTime());
if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) {
log.warn("Logging out, due to inactive session");
SecurityContextHolder.clearContext();
@ -52,6 +51,6 @@ public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
final ModelAndView model) throws Exception {
log.info("Post handle method - check execution time of handling");
long startTime = (Long) request.getAttribute("executionTime");
log.info("Execution time for handling the request was: " + (System.currentTimeMillis() - startTime) + " ms");
log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime);
}
}

View File

@ -14,6 +14,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonProcessingException;
@ -21,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
public class CsrfAbstractIntegrationTest {
@Autowired

View File

@ -5,59 +5,69 @@
<artifactId>spring-thymeleaf</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java-version>1.7</java-version>
<!-- spring -->
<org.springframework-version>4.1.8.RELEASE</org.springframework-version>
<javax.servlet-version>3.0.1</javax.servlet-version>
<!-- logging -->
<properties>
<java-version>1.8</java-version>
<!-- spring -->
<org.springframework-version>4.3.3.RELEASE</org.springframework-version>
<javax.servlet-version>3.0.1</javax.servlet-version>
<!-- logging -->
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- thymeleaf -->
<org.thymeleaf-version>2.1.4.RELEASE</org.thymeleaf-version>
<!-- validation -->
<javax.validation-version>1.1.0.Final</javax.validation-version>
<org.hibernate-version>5.1.2.Final</org.hibernate-version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- Logging -->
<!-- logging -->
<!-- thymeleaf -->
<org.thymeleaf-version>3.0.1.RELEASE</org.thymeleaf-version>
<!-- validation -->
<javax.validation-version>1.1.0.Final</javax.validation-version>
<org.hibernate-version>5.1.2.Final</org.hibernate-version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@ -80,55 +90,81 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-version}</version>
<scope>provided</scope>
</dependency>
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
</excludes>
<systemPropertyVariables>
</systemPropertyVariables>
</configuration>
</plugin>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-version}</version>
<scope>provided</scope>
</dependency>
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
</excludes>
<systemPropertyVariables>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
@ -148,6 +184,7 @@
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.thymeleaf.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class InitSecurity extends AbstractSecurityWebApplicationInitializer {
public InitSecurity() {
super(WebMVCSecurity.class);
}
}

View File

@ -9,28 +9,28 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
*/
public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {
public WebApp() {
super();
}
public WebApp() {
super();
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMVCConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected void customizeRegistration(final Dynamic registration) {
super.customizeRegistration(registration);
}
@Override
protected void customizeRegistration(final Dynamic registration) {
super.customizeRegistration(registration);
}
}

View File

@ -1,18 +1,25 @@
package com.baeldung.thymeleaf.config;
import com.baeldung.thymeleaf.formatter.NameFormatter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import com.baeldung.thymeleaf.formatter.NameFormatter;
@Configuration
@EnableWebMvc
@ -21,35 +28,38 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
* Java configuration file that is used for Spring MVC and Thymeleaf
* configurations
*/
public class WebMVCConfig extends WebMvcConfigurerAdapter {
public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
@Bean
@Description("Thymeleaf Template Resolver")
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
private ApplicationContext applicationContext;
return templateResolver;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
@Description("Thymeleaf Template Engine")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
resolver.setOrder(1);
return resolver;
}
@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
@Bean

View File

@ -0,0 +1,49 @@
package com.baeldung.thymeleaf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebMVCSecurity extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
public WebMVCSecurity() {
super();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
}
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
;
}
}

View File

@ -20,50 +20,50 @@ import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class StudentController {
@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
// get mock objects
List<Student> students = buildStudents();
// add current student
students.add(student);
model.addAttribute("students", students);
}
return ((errors.hasErrors()) ? "addStudent" : "listStudents");
}
@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
// get mock objects
List<Student> students = buildStudents();
// add current student
students.add(student);
model.addAttribute("students", students);
}
return ((errors.hasErrors()) ? "addStudent" : "listStudents");
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public String addStudent(Model model) {
model.addAttribute("student", new Student());
return "addStudent";
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public String addStudent(Model model) {
model.addAttribute("student", new Student());
return "addStudent";
}
@RequestMapping(value = "/listStudents", method = RequestMethod.GET)
public String listStudent(Model model) {
@RequestMapping(value = "/listStudents", method = RequestMethod.GET)
public String listStudent(Model model) {
model.addAttribute("students", buildStudents());
model.addAttribute("students", buildStudents());
return "listStudents";
}
return "listStudents";
}
private List<Student> buildStudents() {
List<Student> students = new ArrayList<Student>();
private List<Student> buildStudents() {
List<Student> students = new ArrayList<Student>();
Student student1 = new Student();
student1.setId(1001);
student1.setName("John Smith");
student1.setGender('M');
student1.setPercentage(Float.valueOf("80.45"));
Student student1 = new Student();
student1.setId(1001);
student1.setName("John Smith");
student1.setGender('M');
student1.setPercentage(Float.valueOf("80.45"));
students.add(student1);
students.add(student1);
Student student2 = new Student();
student2.setId(1002);
student2.setName("Jane Williams");
student2.setGender('F');
student2.setPercentage(Float.valueOf("60.25"));
Student student2 = new Student();
student2.setId(1002);
student2.setName("Jane Williams");
student2.setGender('F');
student2.setPercentage(Float.valueOf("60.25"));
students.add(student2);
return students;
}
students.add(student2);
return students;
}
}

View File

@ -12,49 +12,49 @@ import javax.validation.constraints.NotNull;
*/
public class Student implements Serializable {
private static final long serialVersionUID = -8582553475226281591L;
private static final long serialVersionUID = -8582553475226281591L;
@NotNull(message = "Student ID is required.")
@Min(value = 1000, message = "Student ID must be at least 4 digits.")
private Integer id;
@NotNull(message = "Student ID is required.")
@Min(value = 1000, message = "Student ID must be at least 4 digits.")
private Integer id;
@NotNull(message = "Student name is required.")
private String name;
@NotNull(message = "Student name is required.")
private String name;
@NotNull(message = "Student gender is required.")
private Character gender;
@NotNull(message = "Student gender is required.")
private Character gender;
private Float percentage;
private Float percentage;
public Integer getId() {
return id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public Character getGender() {
return gender;
}
public Character getGender() {
return gender;
}
public void setGender(Character gender) {
this.gender = gender;
}
public void setGender(Character gender) {
this.gender = gender;
}
public Float getPercentage() {
return percentage;
}
public Float getPercentage() {
return percentage;
}
public void setPercentage(Float percentage) {
this.percentage = percentage;
}
public void setPercentage(Float percentage) {
this.percentage = percentage;
}
}

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form action="http://localhost:8080/spring-thymeleaf/saveStudent" method="post">
<input type="hidden" name="payload" value="CSRF attack!"/>
<input type="submit" />
</form>
</body>
</html>

View File

@ -0,0 +1,63 @@
package org.baeldung.security.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
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.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.thymeleaf.config.InitSecurity;
import com.baeldung.thymeleaf.config.WebApp;
import com.baeldung.thymeleaf.config.WebMVCConfig;
import com.baeldung.thymeleaf.config.WebMVCSecurity;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
public class CsrfEnabledIntegrationTest {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
@Autowired
private Filter springSecurityFilterChain;
protected RequestPostProcessor testUser() {
return user("user1").password("user1Pass").roles("USER");
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
}
@Test
public void addStudentWithoutCSRF() throws Exception {
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden());
}
@Test
public void addStudentWithCSRF() throws Exception {
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk());
}
}