diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
index b29838d283..844ad6a782 100644
--- a/core-java-9/pom.xml
+++ b/core-java-9/pom.xml
@@ -60,12 +60,8 @@
1.9
-
true
-
-
@@ -85,12 +81,7 @@
-
- 3.6-jigsaw-SNAPSHOT
-
-
+ 3.6-jigsaw-SNAPSHOT
2.19.1
diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
new file mode 100644
index 0000000000..102ceda18f
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
@@ -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> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
+
+ @Test
+ public void filterOutPresentOptionalsWithFilter() {
+ assertEquals(4, listOfOptionals.size());
+
+ List 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 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 filteredList = listOfOptionals.stream()
+ .flatMap(Optional::stream)
+ .collect(Collectors.toList());
+
+ assertEquals(2, filteredList.size());
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
index d6c16b91bc..a00646e4db 100644
--- a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
+++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
@@ -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;
diff --git a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
new file mode 100644
index 0000000000..56b4bb7b8c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
@@ -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 op = Optional.ofNullable("String value");
+ Stream strOptionalStream = op.stream();
+ Stream filteredStream = strOptionalStream.filter((str) -> {
+ return str != null && str.startsWith("String");
+ });
+ assertEquals(1, filteredStream.count());
+
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
new file mode 100644
index 0000000000..0f8db83d9c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
@@ -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 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 intSet = Set.of(intArray);
+ assertEquals(intSet.size(), intArray.length);
+ }
+}
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
new file mode 100644
index 0000000000..d4a6a0f42e
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
@@ -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 integerSet;
+
+ public ComplexClass(ArrayList> genericArrayList, HashSet 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 getIntegerSet() {
+ return integerSet;
+ }
+
+ protected void setIntegerSet(Set integerSet) {
+ this.integerSet = integerSet;
+ }
+}
diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java
similarity index 100%
rename from eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java
rename to core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java
diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
similarity index 96%
rename from eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
rename to core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
index 315ef41a12..1e1423f0b3 100644
--- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
@@ -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);
}
diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java
similarity index 100%
rename from eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java
rename to core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java
diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java
similarity index 100%
rename from eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java
rename to core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java
diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java
similarity index 90%
rename from eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java
rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java
index 09123e988b..75d96e5989 100644
--- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java
@@ -22,11 +22,10 @@ public class ComplexClassTest {
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(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());
}
diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java
similarity index 84%
rename from eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java
rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java
index feb04d65ff..16f25ae021 100644
--- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java
@@ -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());
}
diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java
similarity index 84%
rename from eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java
rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java
index 53ca199405..52d024a696 100644
--- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java
@@ -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());
}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java
index 9cafa179ab..30b0111555 100644
--- a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java
+++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java
@@ -18,18 +18,18 @@ public class ArrayListTest {
@Before
public void setUp() {
- List xs = LongStream.range(0, 16)
+ List 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 xs = new ArrayList<>();
- assertTrue(xs.isEmpty());
+ List list = new ArrayList<>();
+ assertTrue(list.isEmpty());
}
@Test
@@ -37,29 +37,29 @@ public class ArrayListTest {
Collection numbers =
IntStream.range(0, 10).boxed().collect(toSet());
- List xs = new ArrayList<>(numbers);
- assertEquals(10, xs.size());
- assertTrue(numbers.containsAll(xs));
+ List list = new ArrayList<>(numbers);
+ assertEquals(10, list.size());
+ assertTrue(numbers.containsAll(list));
}
@Test
public void givenElement_whenAddToArrayList_thenIsAdded() {
- List xs = new ArrayList<>();
+ List 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 xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
+ List 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 xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
- Collections.reverse(xs);
+ List 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 xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
- ListIterator it = xs.listIterator(xs.size());
- List result = new ArrayList<>(xs.size());
+ List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
+ ListIterator it = list.listIterator(list.size());
+ List 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
diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
deleted file mode 100644
index 3f7723facd..0000000000
--- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
+++ /dev/null
@@ -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 integerHashSet;
-
- public ComplexClass(ArrayList> genericArrayList, HashSet 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 getIntegerHashSet() {
- return integerHashSet;
- }
-
- protected void setIntegerHashSet(HashSet integerHashSet) {
- this.integerHashSet = integerHashSet;
- }
-}
diff --git a/elasticsearch/README.md b/elasticsearch/README.md
deleted file mode 100644
index e21070dbee..0000000000
--- a/elasticsearch/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-=========
-
-## ElasticSearch
-
-### Relevant Articles:
-- [A Guide to ElasticSearch](http://www.baeldung.com/????????)
diff --git a/elasticsearch/pom.xml b/elasticsearch/pom.xml
deleted file mode 100644
index c12f258b98..0000000000
--- a/elasticsearch/pom.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
- 4.0.0
-
- com.baeldung
- elasticsearch
- 0.0.1-SNAPSHOT
- jar
-
- elasticsearch
- http://maven.apache.org
-
-
- UTF-8
-
-
-
-
- org.elasticsearch
- elasticsearch
- 2.3.5
-
-
- com.alibaba
- fastjson
- 1.2.13
-
-
- junit
- junit
- 4.12
- test
-
-
-
diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java
index 4dfc12c050..a8962f5108 100644
--- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java
+++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java
@@ -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();
}
}
}
diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java
index 634e05c3a0..abadcc0d76 100644
--- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java
+++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java
@@ -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);
}
diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java
new file mode 100644
index 0000000000..b270bc7985
--- /dev/null
+++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java
@@ -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;
+ }
+}
diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java
index 524e000bd9..1e30452d95 100644
--- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java
+++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java
@@ -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();
diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png
index bd475bf3f3..af22a38e37 100644
Binary files a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png and b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png differ
diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml
index fbd4f416ef..cbc2dc8bd9 100644
--- a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml
+++ b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml
@@ -1,5 +1,5 @@
@startuml
-
+scale 1.5
class Handler {
doGet
doPost
diff --git a/log4j/pom.xml b/log4j/pom.xml
index 76c05b36c1..586769aa71 100644
--- a/log4j/pom.xml
+++ b/log4j/pom.xml
@@ -15,7 +15,13 @@
log4j
1.2.17
-
+
@@ -28,22 +34,34 @@
log4j-core
2.6
-
-
+
com.lmax
disruptor
3.3.4
-
+
-
ch.qos.logback
logback-classic
1.1.7
+
+
diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java
new file mode 100644
index 0000000000..6ecc7b887a
--- /dev/null
+++ b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java
@@ -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);
+ }
+}
diff --git a/pom.xml b/pom.xml
index 8115c1e902..33162777b7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -91,7 +91,6 @@
spring-hibernate3
spring-hibernate4
spring-jpa
- spring-jpa-jndi
spring-katharsis
spring-mockito
spring-mvc-java
diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml
new file mode 100644
index 0000000000..c6bd2b042c
--- /dev/null
+++ b/selenium-junit-testng/pom.xml
@@ -0,0 +1,36 @@
+
+ 4.0.0
+ com.baeldung
+ selenium-junit-testng
+ 0.0.1-SNAPSHOT
+
+ src
+
+
+ maven-compiler-plugin
+ 3.1
+
+
+ 1.8
+
+
+
+
+
+
+ org.seleniumhq.selenium
+ selenium-java
+ 2.53.1
+
+
+ junit
+ junit
+ 4.8.1
+
+
+ org.testng
+ testng
+ 6.9.10
+
+
+
\ No newline at end of file
diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java
new file mode 100644
index 0000000000..6020b6bd2c
--- /dev/null
+++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java
@@ -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;
+ }
+
+}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
new file mode 100644
index 0000000000..371f730eb9
--- /dev/null
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
@@ -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);
+ }
+}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
new file mode 100644
index 0000000000..ec10f9ca82
--- /dev/null
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
@@ -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);
+ }
+}
diff --git a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java
new file mode 100644
index 0000000000..dcdfafc4f1
--- /dev/null
+++ b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java
@@ -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);
+ }
+}
diff --git a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
new file mode 100644
index 0000000000..a7b36c4e4e
--- /dev/null
+++ b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
@@ -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);
+ }
+}
diff --git a/spring-cloud-config/README.md b/spring-cloud-config/README.md
new file mode 100644
index 0000000000..b8ebb2bfe9
--- /dev/null
+++ b/spring-cloud-config/README.md
@@ -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].
diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud-config/docker/Dockerfile.client
new file mode 100644
index 0000000000..0f9293bd22
--- /dev/null
+++ b/spring-cloud-config/docker/Dockerfile.client
@@ -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
diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud-config/docker/Dockerfile.server
new file mode 100644
index 0000000000..90d7e2a7cf
--- /dev/null
+++ b/spring-cloud-config/docker/Dockerfile.server
@@ -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
diff --git a/spring-cloud-config/docker/files/.gitignore b/spring-cloud-config/docker/files/.gitignore
new file mode 100644
index 0000000000..28ffcbffdb
--- /dev/null
+++ b/spring-cloud-config/docker/files/.gitignore
@@ -0,0 +1,2 @@
+/UnlimitedJCEPolicyJDK8
+/*.jar
diff --git a/spring-cloud-config/docker/files/config-client-entrypoint.sh b/spring-cloud-config/docker/files/config-client-entrypoint.sh
new file mode 100644
index 0000000000..12352119fa
--- /dev/null
+++ b/spring-cloud-config/docker/files/config-client-entrypoint.sh
@@ -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
diff --git a/spring-cloud-config/pom.xml b/spring-cloud-config/pom.xml
new file mode 100644
index 0000000000..3b1b59b037
--- /dev/null
+++ b/spring-cloud-config/pom.xml
@@ -0,0 +1,52 @@
+
+
+ 4.0.0
+
+ com.baeldung.spring.cloud
+ spring-cloud-config
+ pom
+
+
+ spring-cloud-config-server
+ spring-cloud-config-client
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ..
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-parent
+ 1.4.0.RELEASE
+ pom
+ import
+
+
+ org.springframework.cloud
+ spring-cloud-dependencies
+ Brixton.SR4
+ pom
+ import
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ 1.4.0.RELEASE
+
+
+
+
+
diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml
index 3a6e330564..084695c2f3 100644
--- a/spring-data-elasticsearch/pom.xml
+++ b/spring-data-elasticsearch/pom.xml
@@ -69,6 +69,17 @@
log4j-over-slf4j
${org.slf4j.version}
+
+
+ org.elasticsearch
+ elasticsearch
+ 2.3.5
+
+
+ com.alibaba
+ fastjson
+ 1.2.13
+
diff --git a/elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
similarity index 94%
rename from elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
rename to spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
index 8f0b19a186..b8ad59e2e2 100644
--- a/elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
+++ b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
@@ -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 + "]";
+ }
+}
diff --git a/elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java
similarity index 92%
rename from elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java
rename to spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java
index a5f103c005..db304ee78d 100644
--- a/elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java
+++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java
@@ -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 results = new ArrayList();
- for (SearchHit hit : searchHits) {
- String sourceAsString = hit.getSourceAsString();
- Person person = JSON.parseObject(sourceAsString, Person.class);
- results.add(person);
- }
+ List searchHits = Arrays.asList(response.getHits().getHits());
+ final List results = new ArrayList();
+ searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class)));
} catch (Exception e) {
isExecutedSuccessfully = false;
}
diff --git a/spring-data-neo4j/README.md b/spring-data-neo4j/README.md
index e62c69f8b9..0f13d9dbc9 100644
--- a/spring-data-neo4j/README.md
+++ b/spring-data-neo4j/README.md
@@ -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
```
diff --git a/spring-jpa-jndi/.gitignore b/spring-jpa-jndi/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/spring-jpa-jndi/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/spring-jpa-jndi/README.md b/spring-jpa-jndi/README.md
deleted file mode 100644
index 6a99253545..0000000000
--- a/spring-jpa-jndi/README.md
+++ /dev/null
@@ -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)
\ No newline at end of file
diff --git a/spring-jpa-jndi/pom.xml b/spring-jpa-jndi/pom.xml
deleted file mode 100644
index f7042f2384..0000000000
--- a/spring-jpa-jndi/pom.xml
+++ /dev/null
@@ -1,145 +0,0 @@
-
- 4.0.0
-
- com.baeldung
- spring-jpa-jndi
- 0.1-SNAPSHOT
- war
-
- spring-jpa-jndi
-
-
-
-
-
-
- org.springframework
- spring-orm
- ${org.springframework.version}
-
-
- org.springframework
- spring-context
- ${org.springframework.version}
-
-
- org.springframework
- spring-webmvc
- ${org.springframework.version}
-
-
-
-
- javax.servlet
- jstl
- ${javax.servlet.jstl.version}
-
-
- javax.servlet
- servlet-api
- ${javax.servlet.servlet-api.version}
-
-
-
-
-
- org.hibernate
- hibernate-entitymanager
- ${hibernate.version}
-
-
- xml-apis
- xml-apis
- 1.4.01
-
-
- org.javassist
- javassist
- ${javassist.version}
-
-
- org.springframework.data
- spring-data-jpa
- ${spring-data-jpa.version}
-
-
-
-
-
- org.hibernate
- hibernate-validator
- ${hibernate-validator.version}
-
-
- javax.el
- javax.el-api
- 2.2.5
-
-
-
-
-
- spring-jpa-jndi
-
-
- src/main/resources
- true
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 1.8
-
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
- src/main/webapp
- false
-
-
-
-
-
-
-
-
-
- 4.3.2.RELEASE
- 3.20.0-GA
-
-
- 1.2
- 2.5
-
-
- 4.3.11.Final
- 1.8.2.RELEASE
- 1.4.192
-
-
- 1.7.13
- 1.1.3
-
-
- 5.2.2.Final
-
-
- 3.5.1
- 2.7
- 2.4
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java
deleted file mode 100644
index 0133a36a14..0000000000
--- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java
+++ /dev/null
@@ -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 findAll() {
- return entityManager.createQuery("from " + Foo.class.getName()).getResultList();
- }
-
-}
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java
deleted file mode 100644
index d351fc54b8..0000000000
--- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java
+++ /dev/null
@@ -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;
- }
-}
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java
deleted file mode 100644
index a3109f5042..0000000000
--- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java
+++ /dev/null
@@ -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 findAll() {
- return dao.findAll();
- }
-
-}
diff --git a/spring-jpa-jndi/src/main/resources/logback.xml b/spring-jpa-jndi/src/main/resources/logback.xml
deleted file mode 100644
index 1146dade63..0000000000
--- a/spring-jpa-jndi/src/main/resources/logback.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
- web - %date [%thread] %-5level %logger{36} - %message%n
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml
index 5acdae7765..ebb9c5bc83 100644
--- a/spring-jpa/pom.xml
+++ b/spring-jpa/pom.xml
@@ -4,6 +4,7 @@
com.baeldung
spring-jpa
0.1-SNAPSHOT
+ war
spring-jpa
@@ -21,6 +22,11 @@
spring-context
${org.springframework.version}
+
+ org.springframework
+ spring-webmvc
+ ${org.springframework.version}
+
@@ -73,6 +79,18 @@
javax.el-api
2.2.5
+
+
+
+ javax.servlet
+ jstl
+ ${javax.servlet.jstl.version}
+
+
+ javax.servlet
+ servlet-api
+ ${javax.servlet.servlet-api.version}
+
@@ -147,6 +165,16 @@
1.8
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ src/main/webapp
+ false
+
+
org.apache.maven.plugins
@@ -197,6 +225,10 @@
5.1.38
1.10.2.RELEASE
1.4.192
+
+
+ 1.2
+ 2.5
1.7.13
@@ -224,6 +256,7 @@
2.19.1
2.7
1.4.18
+ 2.4
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java
similarity index 90%
rename from spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java
rename to spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java
index 7ea731d9d4..7f28c958f1 100644
--- a/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java
+++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java
@@ -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
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java b/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java
similarity index 100%
rename from spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java
rename to spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java b/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java
similarity index 100%
rename from spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java
rename to spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java
diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java b/spring-jpa/src/main/java/org/baeldung/web/MainController.java
similarity index 100%
rename from spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java
rename to spring-jpa/src/main/java/org/baeldung/web/MainController.java
diff --git a/spring-jpa-jndi/src/main/resources/context.xml b/spring-jpa/src/main/resources/context.xml
similarity index 100%
rename from spring-jpa-jndi/src/main/resources/context.xml
rename to spring-jpa/src/main/resources/context.xml
diff --git a/spring-jpa-jndi/src/main/resources/persistence-jndi.properties b/spring-jpa/src/main/resources/persistence-jndi.properties
similarity index 100%
rename from spring-jpa-jndi/src/main/resources/persistence-jndi.properties
rename to spring-jpa/src/main/resources/persistence-jndi.properties
diff --git a/spring-jpa-jndi/src/main/resources/server.xml b/spring-jpa/src/main/resources/server.xml
similarity index 100%
rename from spring-jpa-jndi/src/main/resources/server.xml
rename to spring-jpa/src/main/resources/server.xml
diff --git a/spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp
similarity index 100%
rename from spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp
rename to spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp
diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml
index 0c0d6219dd..18cb1dc72a 100644
--- a/spring-rest/pom.xml
+++ b/spring-rest/pom.xml
@@ -182,7 +182,6 @@
org.apache.maven.plugins
maven-compiler-plugin
- ${maven-compiler-plugin.version}
1.8
@@ -192,16 +191,14 @@
org.apache.maven.plugins
maven-war-plugin
- ${maven-war-plugin.version}
org.apache.maven.plugins
maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
+ **/*LiveTest.java
@@ -216,7 +213,7 @@
true
- jetty8x
+ tomcat8x
embedded
@@ -234,6 +231,61 @@
+
+
+ live
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+
+
+ start-server
+ pre-integration-test
+
+ start
+
+
+
+ stop-server
+ post-integration-test
+
+ stop
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+ **/*LiveTest.java
+
+
+ cargo
+
+
+
+
+
+
+
+
+
+
+
@@ -266,7 +318,7 @@
3.5.1
2.6
2.19.1
- 1.4.18
+ 1.6.0
diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
index fd349f1e44..3155b5cda9 100644
--- a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
@@ -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() {
diff --git a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java
similarity index 97%
rename from spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java
rename to spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java
index 1dfe509c09..7f250653ab 100644
--- a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java
+++ b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java
@@ -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
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java
index 8d967ed1ef..f5c1626989 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java
@@ -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);
}
}
diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
index 1b5f7cd894..13cb92a745 100644
--- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
+++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
@@ -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
diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml
index 51e26fdfdd..a13f1de4c7 100644
--- a/spring-thymeleaf/pom.xml
+++ b/spring-thymeleaf/pom.xml
@@ -5,59 +5,69 @@
spring-thymeleaf
0.1-SNAPSHOT
war
-
- 1.7
-
- 4.1.8.RELEASE
- 3.0.1
-
+
+ 1.8
+
+ 4.3.3.RELEASE
+ 3.0.1
+
1.7.12
1.1.3
-
- 2.1.4.RELEASE
-
- 1.1.0.Final
- 5.1.2.Final
-
-
- 3.5.1
- 2.6
- 2.19.1
- 1.4.18
-
-
-
-
-
- org.springframework
- spring-context
- ${org.springframework-version}
-
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.springframework
- spring-webmvc
- ${org.springframework-version}
-
-
-
- org.thymeleaf
- thymeleaf
- ${org.thymeleaf-version}
-
-
- org.thymeleaf
- thymeleaf-spring4
- ${org.thymeleaf-version}
-
-
-
+
+ 3.0.1.RELEASE
+
+ 1.1.0.Final
+ 5.1.2.Final
+
+
+ 3.5.1
+ 2.6
+ 2.19.1
+ 1.4.18
+
+
+
+
+
+ org.springframework
+ spring-context
+ ${org.springframework-version}
+
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.springframework
+ spring-webmvc
+ ${org.springframework-version}
+
+
+
+ org.springframework.security
+ spring-security-web
+ 4.1.3.RELEASE
+
+
+ org.springframework.security
+ spring-security-config
+ 4.1.3.RELEASE
+
+
+
+ org.thymeleaf
+ thymeleaf
+ ${org.thymeleaf-version}
+
+
+ org.thymeleaf
+ thymeleaf-spring4
+ ${org.thymeleaf-version}
+
+
org.slf4j
slf4j-api
@@ -80,55 +90,81 @@
log4j-over-slf4j
${org.slf4j.version}
-
-
- javax.servlet
- javax.servlet-api
- ${javax.servlet-version}
- provided
-
-
-
- javax.validation
- validation-api
- ${javax.validation-version}
-
-
- org.hibernate
- hibernate-validator
- ${org.hibernate-version}
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- ${java-version}
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
- false
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
-
-
-
-
-
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-version}
+ provided
+
+
+
+ javax.validation
+ validation-api
+ ${javax.validation-version}
+
+
+ org.hibernate
+ hibernate-validator
+ ${org.hibernate-version}
+
+
+
+
+ org.springframework
+ spring-test
+ 4.1.3.RELEASE
+ test
+
+
+
+
+ org.springframework.security
+ spring-security-test
+ 4.1.3.RELEASE
+ test
+
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${java-version}
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+
+
+
+
+
org.codehaus.cargo
cargo-maven2-plugin
@@ -148,6 +184,7 @@
-
-
+
+
+
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java
new file mode 100644
index 0000000000..956db4a0e5
--- /dev/null
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java
@@ -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);
+
+ }
+}
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java
index 89ad7e601e..3104f45ab5 100644
--- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java
@@ -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);
+ }
}
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java
index 51c60247a1..547d6deee9 100644
--- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java
@@ -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
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java
new file mode 100644
index 0000000000..37844a2976
--- /dev/null
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java
@@ -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()
+ ;
+ }
+
+}
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java
index 912eb521f4..da34b2d7b0 100644
--- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java
@@ -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 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 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 buildStudents() {
- List students = new ArrayList();
+ private List buildStudents() {
+ List students = new ArrayList();
- 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;
+ }
}
diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
index bce99f286c..202c04358a 100644
--- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
+++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
@@ -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;
+ }
}
diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html
new file mode 100644
index 0000000000..7674caa854
--- /dev/null
+++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java
new file mode 100644
index 0000000000..46a28c3c74
--- /dev/null
+++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java
@@ -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());
+ }
+
+}