From 0706cd84532d324f6556a19ad259fbae882ba919 Mon Sep 17 00:00:00 2001 From: maverick Date: Thu, 28 Jul 2016 16:38:17 +0530 Subject: [PATCH 01/68] First Commit for Sorting Examples. --- .../java/com/baeldung/beans/Employee.java | 49 +++++++++ .../org/baeldung/java/sorting/ArraySort.java | 88 +++++++++++++++ .../baeldung/java/sorting/ComparingTest.java | 38 +++++++ .../org/baeldung/java/sorting/Employee.java | 54 +++++++++ .../org/baeldung/java/sorting/ListSort.java | 59 ++++++++++ .../org/baeldung/java/sorting/MapSort.java | 104 ++++++++++++++++++ .../java/sorting/NaturalOrderExample.java | 34 ++++++ .../org/baeldung/java/sorting/SetSort.java | 54 +++++++++ 8 files changed, 480 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/beans/Employee.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ListSort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/MapSort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/SetSort.java diff --git a/core-java/src/main/java/com/baeldung/beans/Employee.java b/core-java/src/main/java/com/baeldung/beans/Employee.java new file mode 100644 index 0000000000..78d65e18fe --- /dev/null +++ b/core-java/src/main/java/com/baeldung/beans/Employee.java @@ -0,0 +1,49 @@ +package com.baeldung.beans; + +public class Employee implements Comparable{ + private String name; + private int age; + private double salary; + + public Employee() { + + } + + public Employee(String name, int age, double salary) { + super(); + this.name = name; + this.age = age; + this.salary = salary; + } + + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public double getSalary() { + return salary; + } + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "("+name+","+age+","+salary+")"; + + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getAge() - e.getAge() ; + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java new file mode 100644 index 0000000000..3e55ab7f6a --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java @@ -0,0 +1,88 @@ +package org.baeldung.java.sorting; + +import static org.junit.Assert.*; + +import java.sql.Array; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ArraySort { + + private int[] numbers; + private Integer[] integers; + private String[] names; + private Employee[] employees; + + @Before + public void initData() { + numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + integers = new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + + names = new String[] { "John", "Apple", "Steve", "Frank", "Earl", "Jessica", "Jake", "Pearl" }; + + employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + + } + + @Test + public void naturalSortIntArray() { + + Arrays.sort(numbers); + + } + + @Test + public void comparatorSortIntArray() { + + Arrays.sort(integers, new Comparator() { + + @Override + public int compare(Integer a, Integer b) { + return a - b; + } + }); + + } + + @Test + public void comparatorSortIntArray_Java8Lambda() { + Arrays.sort(integers, (a, b) -> { + return a - b; + }); + + } + + @Test + public void comparableSortEmployeeArrayByAge_NaturalOrder() { + + Arrays.sort(employees); + + } + + @Test + public void comparatorSortEmployeeArrayByName() { + Arrays.sort(employees, new Comparator() { + + @Override + public int compare(Employee o1, Employee o2) { + + return o1.getName().compareTo(o2.getName()); + } + }); + } + + @Test + public void comparatorSortEmployeeArrayByName_Java8Lambda() { + Arrays.sort(employees, (o1, o2) -> { + return o1.getName().compareTo(o2.getName()); + + }); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java b/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java new file mode 100644 index 0000000000..02cdede7db --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java @@ -0,0 +1,38 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ComparingTest { + + private List employees; + + @Before + public void initData() { + + // employees = Arrays.asList(new Employee[] { + // new Employee("John", 23, 5000), + // new Employee("Steve", 26, 6000), + // new Employee("Frank", 33, 7000), + // new Employee("Earl", 43, 10000), + // new Employee("Jessica", 23, 4000), + // new Employee("Pearl", 33, 6000) }); + + } + + @Test + public void testComparing() { + employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); + + employees.sort(Comparator.comparing(Employee::getAge).thenComparing(Employee::getName)); + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java new file mode 100644 index 0000000000..f36e552daf --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -0,0 +1,54 @@ +package org.baeldung.java.sorting; + +public class Employee implements Comparable { + private String name; + private int age; + private double salary; + + public Employee() { + + } + + public Employee(String name, int age, double salary) { + super(); + this.name = name; + this.age = age; + this.salary = salary; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "(" + name + "," + age + "," + salary + ")"; + + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getAge() - e.getAge(); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java b/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java new file mode 100644 index 0000000000..91e1c40607 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java @@ -0,0 +1,59 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ListSort { + + private List integers; + private List employees; + + @Before + public void initData() { + integers = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); + + employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); + } + + @Test + public void naturalOrderIntegerListSort() { + + Collections.sort(integers); + + } + + @Test + public void comparableEmployeeSortByAge() { + + Collections.sort(employees); + + } + + @Test + public void comparatorEmployeeSortByName() { + + Collections.sort(employees, new Comparator() { + @Override + public int compare(Employee e1, Employee e2) { + return e1.getName().compareTo(e2.getName()); + } + }); + + } + + @Test + public void comparatorEmployeeSortByNameJava8() { + + Collections.sort(employees, (e1, e2) -> { + return e1.getName().compareTo(e1.getName()); + }); + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java b/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java new file mode 100644 index 0000000000..1a9fd30437 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java @@ -0,0 +1,104 @@ +package org.baeldung.java.sorting; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; + +import org.junit.Before; +import org.junit.Test; + +public class MapSort { + + HashMap map; + + @Before + public void initData() { + map = new HashMap<>(); + + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + + } + + @Test + public void sortMapByKeys() { + + + List> entries = new ArrayList<>(map.entrySet()); + + Collections.sort(entries, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + + return o1.getKey().compareTo(o2.getKey()); + } + }); + + HashMap sortedMap = new LinkedHashMap<>(); + + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + + } + + @Test + public void sortMapByValues() { + + //showMap(map); + + List> entries = new ArrayList<>(map.entrySet()); + + Collections.sort(entries, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + return o1.getValue().compareTo(o2.getValue()); + } + }); + + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + +/// showMap(sortedMap); + } + + @Test + public void sortMapViaTreeMap() { + +// showMap(map); + Map treeMap = new TreeMap<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1 - o2; + } + }); + + treeMap.putAll(map); +// showMap(treeMap); + + } + + public void showMap(Map map1) { + for (Map.Entry entry : map1.entrySet()) { + System.out.println("[Key: " + entry.getKey() + " , " + "Value: " + entry.getValue() + "] "); + + } + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java b/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java new file mode 100644 index 0000000000..bb35557561 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java @@ -0,0 +1,34 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.Test; + +public class NaturalOrderExample { + + @Test + public void sortArray() { + int[] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + + Arrays.sort(numbers); + + } + + @Test + public void sortEmployees() { + Employee[] employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + + Arrays.sort(employees, new Comparator() { + + @Override + public int compare(Employee o1, Employee o2) { + return -(int) (o1.getSalary() - o2.getSalary()); + } + }); + + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java b/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java new file mode 100644 index 0000000000..d892223862 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java @@ -0,0 +1,54 @@ +package org.baeldung.java.sorting; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.TreeSet; + +import org.junit.Before; +import org.junit.Test; + +public class SetSort { + + private HashSet integers; + private TreeSet employees; + + @Before + public void initData() { + + integers = new HashSet<>(); + integers.addAll(Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 })); + + employees = new TreeSet<>(); + + employees.addAll(Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) })); + + } + + @Test + public void hashSetSortIntegers() { + + + + ArrayList list = new ArrayList(integers); + Collections.sort(list, (i1, i2) -> { + return i2 - i1; + }); + + + } + + @Test + public void treeSetEmployeeSorting() { + + ArrayList list = new ArrayList(employees); + Collections.sort(list, (e1, e2) -> { + return e2.getName().compareTo(e1.getName()); + }); + + } + +} From bf1c98fd1679b3d0b6f6ff6cd766aa98042f2b8f Mon Sep 17 00:00:00 2001 From: maverick Date: Thu, 28 Jul 2016 16:38:17 +0530 Subject: [PATCH 02/68] First Commit for Sorting Examples. --- .../java/com/baeldung/beans/Employee.java | 49 +++++++++ .../org/baeldung/java/sorting/ArraySort.java | 88 +++++++++++++++ .../baeldung/java/sorting/ComparingTest.java | 38 +++++++ .../org/baeldung/java/sorting/Employee.java | 54 +++++++++ .../org/baeldung/java/sorting/ListSort.java | 59 ++++++++++ .../org/baeldung/java/sorting/MapSort.java | 104 ++++++++++++++++++ .../java/sorting/NaturalOrderExample.java | 34 ++++++ .../org/baeldung/java/sorting/SetSort.java | 54 +++++++++ 8 files changed, 480 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/beans/Employee.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ListSort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/MapSort.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/SetSort.java diff --git a/core-java/src/main/java/com/baeldung/beans/Employee.java b/core-java/src/main/java/com/baeldung/beans/Employee.java new file mode 100644 index 0000000000..78d65e18fe --- /dev/null +++ b/core-java/src/main/java/com/baeldung/beans/Employee.java @@ -0,0 +1,49 @@ +package com.baeldung.beans; + +public class Employee implements Comparable{ + private String name; + private int age; + private double salary; + + public Employee() { + + } + + public Employee(String name, int age, double salary) { + super(); + this.name = name; + this.age = age; + this.salary = salary; + } + + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public double getSalary() { + return salary; + } + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "("+name+","+age+","+salary+")"; + + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getAge() - e.getAge() ; + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java new file mode 100644 index 0000000000..3e55ab7f6a --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java @@ -0,0 +1,88 @@ +package org.baeldung.java.sorting; + +import static org.junit.Assert.*; + +import java.sql.Array; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ArraySort { + + private int[] numbers; + private Integer[] integers; + private String[] names; + private Employee[] employees; + + @Before + public void initData() { + numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + integers = new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + + names = new String[] { "John", "Apple", "Steve", "Frank", "Earl", "Jessica", "Jake", "Pearl" }; + + employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + + } + + @Test + public void naturalSortIntArray() { + + Arrays.sort(numbers); + + } + + @Test + public void comparatorSortIntArray() { + + Arrays.sort(integers, new Comparator() { + + @Override + public int compare(Integer a, Integer b) { + return a - b; + } + }); + + } + + @Test + public void comparatorSortIntArray_Java8Lambda() { + Arrays.sort(integers, (a, b) -> { + return a - b; + }); + + } + + @Test + public void comparableSortEmployeeArrayByAge_NaturalOrder() { + + Arrays.sort(employees); + + } + + @Test + public void comparatorSortEmployeeArrayByName() { + Arrays.sort(employees, new Comparator() { + + @Override + public int compare(Employee o1, Employee o2) { + + return o1.getName().compareTo(o2.getName()); + } + }); + } + + @Test + public void comparatorSortEmployeeArrayByName_Java8Lambda() { + Arrays.sort(employees, (o1, o2) -> { + return o1.getName().compareTo(o2.getName()); + + }); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java b/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java new file mode 100644 index 0000000000..02cdede7db --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java @@ -0,0 +1,38 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ComparingTest { + + private List employees; + + @Before + public void initData() { + + // employees = Arrays.asList(new Employee[] { + // new Employee("John", 23, 5000), + // new Employee("Steve", 26, 6000), + // new Employee("Frank", 33, 7000), + // new Employee("Earl", 43, 10000), + // new Employee("Jessica", 23, 4000), + // new Employee("Pearl", 33, 6000) }); + + } + + @Test + public void testComparing() { + employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); + + employees.sort(Comparator.comparing(Employee::getAge).thenComparing(Employee::getName)); + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java new file mode 100644 index 0000000000..f36e552daf --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -0,0 +1,54 @@ +package org.baeldung.java.sorting; + +public class Employee implements Comparable { + private String name; + private int age; + private double salary; + + public Employee() { + + } + + public Employee(String name, int age, double salary) { + super(); + this.name = name; + this.age = age; + this.salary = salary; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "(" + name + "," + age + "," + salary + ")"; + + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getAge() - e.getAge(); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java b/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java new file mode 100644 index 0000000000..91e1c40607 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java @@ -0,0 +1,59 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ListSort { + + private List integers; + private List employees; + + @Before + public void initData() { + integers = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); + + employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); + } + + @Test + public void naturalOrderIntegerListSort() { + + Collections.sort(integers); + + } + + @Test + public void comparableEmployeeSortByAge() { + + Collections.sort(employees); + + } + + @Test + public void comparatorEmployeeSortByName() { + + Collections.sort(employees, new Comparator() { + @Override + public int compare(Employee e1, Employee e2) { + return e1.getName().compareTo(e2.getName()); + } + }); + + } + + @Test + public void comparatorEmployeeSortByNameJava8() { + + Collections.sort(employees, (e1, e2) -> { + return e1.getName().compareTo(e1.getName()); + }); + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java b/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java new file mode 100644 index 0000000000..1a9fd30437 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java @@ -0,0 +1,104 @@ +package org.baeldung.java.sorting; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; + +import org.junit.Before; +import org.junit.Test; + +public class MapSort { + + HashMap map; + + @Before + public void initData() { + map = new HashMap<>(); + + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + + } + + @Test + public void sortMapByKeys() { + + + List> entries = new ArrayList<>(map.entrySet()); + + Collections.sort(entries, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + + return o1.getKey().compareTo(o2.getKey()); + } + }); + + HashMap sortedMap = new LinkedHashMap<>(); + + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + + } + + @Test + public void sortMapByValues() { + + //showMap(map); + + List> entries = new ArrayList<>(map.entrySet()); + + Collections.sort(entries, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + return o1.getValue().compareTo(o2.getValue()); + } + }); + + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + +/// showMap(sortedMap); + } + + @Test + public void sortMapViaTreeMap() { + +// showMap(map); + Map treeMap = new TreeMap<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1 - o2; + } + }); + + treeMap.putAll(map); +// showMap(treeMap); + + } + + public void showMap(Map map1) { + for (Map.Entry entry : map1.entrySet()) { + System.out.println("[Key: " + entry.getKey() + " , " + "Value: " + entry.getValue() + "] "); + + } + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java b/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java new file mode 100644 index 0000000000..bb35557561 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java @@ -0,0 +1,34 @@ +package org.baeldung.java.sorting; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.Test; + +public class NaturalOrderExample { + + @Test + public void sortArray() { + int[] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + + Arrays.sort(numbers); + + } + + @Test + public void sortEmployees() { + Employee[] employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + + Arrays.sort(employees, new Comparator() { + + @Override + public int compare(Employee o1, Employee o2) { + return -(int) (o1.getSalary() - o2.getSalary()); + } + }); + + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java b/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java new file mode 100644 index 0000000000..d892223862 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java @@ -0,0 +1,54 @@ +package org.baeldung.java.sorting; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.TreeSet; + +import org.junit.Before; +import org.junit.Test; + +public class SetSort { + + private HashSet integers; + private TreeSet employees; + + @Before + public void initData() { + + integers = new HashSet<>(); + integers.addAll(Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 })); + + employees = new TreeSet<>(); + + employees.addAll(Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) })); + + } + + @Test + public void hashSetSortIntegers() { + + + + ArrayList list = new ArrayList(integers); + Collections.sort(list, (i1, i2) -> { + return i2 - i1; + }); + + + } + + @Test + public void treeSetEmployeeSorting() { + + ArrayList list = new ArrayList(employees); + Collections.sort(list, (e1, e2) -> { + return e2.getName().compareTo(e1.getName()); + }); + + } + +} From 7c0af736049d5c57a6fe4c6b04ce45a67dab47de Mon Sep 17 00:00:00 2001 From: i032048 Date: Thu, 28 Jul 2016 18:03:48 +0300 Subject: [PATCH 03/68] initial push for core-java-9 tutorials --- core-java-9/.gitignore | 13 ++ core-java-9/README.md | 5 + core-java-9/pom.xml | 138 +++++++++++++++++ core-java-9/src/main/java/.gitignore | 13 ++ .../baeldung/java9/process/ProcessUtils.java | 48 ++++++ .../baeldung/java9/process/ServiceMain.java | 22 +++ core-java-9/src/main/resources/logback.xml | 16 ++ core-java-9/src/test/build.bat | 10 ++ .../test/java/com/baeldung/java9/Main.java | 22 +++ .../java9/MultiResultionImageTest.java | 48 ++++++ .../com/baeldung/java9/httpclient/Main.java | 14 ++ .../java9/httpclient/SimpleHttpRequests.java | 146 ++++++++++++++++++ .../baeldung/java9/language/DiamondTest.java | 36 +++++ .../java9/language/PrivateInterface.java | 23 +++ .../java9/language/TryWithResourcesTest.java | 70 +++++++++ .../java/com/baeldung/java9/process/Main.java | 18 +++ .../baeldung/java9/process/ProcessApi.java | 112 ++++++++++++++ core-java-9/src/test/resources/.gitignore | 13 ++ 18 files changed, 767 insertions(+) create mode 100644 core-java-9/.gitignore create mode 100644 core-java-9/README.md create mode 100644 core-java-9/pom.xml create mode 100644 core-java-9/src/main/java/.gitignore create mode 100644 core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java create mode 100644 core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java create mode 100644 core-java-9/src/main/resources/logback.xml create mode 100644 core-java-9/src/test/build.bat create mode 100644 core-java-9/src/test/java/com/baeldung/java9/Main.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/process/Main.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java create mode 100644 core-java-9/src/test/resources/.gitignore diff --git a/core-java-9/.gitignore b/core-java-9/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/.gitignore @@ -0,0 +1,13 @@ +*.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/core-java-9/README.md b/core-java-9/README.md new file mode 100644 index 0000000000..b5d4dbef95 --- /dev/null +++ b/core-java-9/README.md @@ -0,0 +1,5 @@ +========= + +## Core Java 9 Examples + +http://inprogress.baeldung.com/java-9-new-features/ \ No newline at end of file diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml new file mode 100644 index 0000000000..06421915a3 --- /dev/null +++ b/core-java-9/pom.xml @@ -0,0 +1,138 @@ + + 4.0.0 + com.baeldung + core-java9 + 0.1-SNAPSHOT + + core-java9 + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + core-java-9 + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + true + C:\develop\jdks\jdk-9_ea122\bin\javac + 1.9 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + 1.7.13 + 1.0.13 + + + 5.1.3.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + + 3.5.1 + + + 2.6 + 2.19.1 + 2.7 + + + + diff --git a/core-java-9/src/main/java/.gitignore b/core-java-9/src/main/java/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/src/main/java/.gitignore @@ -0,0 +1,13 @@ +*.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/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java new file mode 100644 index 0000000000..b9c1cf1880 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -0,0 +1,48 @@ +package com.baeldung.java9.process; + +import java.io.File; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +public class ProcessUtils { + + public static String getClassPath(){ + String cp = System.getProperty("java.class.path"); + System.out.println("ClassPath is "+cp); + return cp; + } + + public static File getJavaCmd() throws IOException{ + String javaHome = System.getProperty("java.home"); + File javaCmd; + if(System.getProperty("os.name").startsWith("Win")){ + javaCmd = new File(javaHome, "bin/java.exe"); + }else{ + javaCmd = new File(javaHome, "bin/java"); + } + if(javaCmd.canExecute()){ + return javaCmd; + }else{ + throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable"); + } + } + + public static String getMainClass(){ + return System.getProperty("sun.java.command"); + } + + public static String getSystemProperties(){ + StringBuilder sb = new StringBuilder(); + System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) ); + return sb.toString(); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java new file mode 100644 index 0000000000..458f746496 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -0,0 +1,22 @@ +package com.baeldung.java9.process; + +import java.util.Optional; + +public class ServiceMain { + + public static void main(String[] args) throws InterruptedException { + ProcessHandle thisProcess = ProcessHandle.current(); + long pid = thisProcess.getPid(); + + + Optional opArgs = Optional.ofNullable(args); + String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); + + for (int i = 0; i < 10000; i++) { + System.out.println("Process " + procName + " with ID " + pid + " is running!"); + Thread.sleep(10000); + } + + } + +} diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml new file mode 100644 index 0000000000..eefdc7a337 --- /dev/null +++ b/core-java-9/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-9/src/test/build.bat b/core-java-9/src/test/build.bat new file mode 100644 index 0000000000..c6208b89d2 --- /dev/null +++ b/core-java-9/src/test/build.bat @@ -0,0 +1,10 @@ +@echo off +REM C:\develop\jdks\jdk-9_ea123\bin\javac +REM +REM C:\develop\jdks\jdk1.8.0_45\bin\javac +@echo on +C:\develop\jdks\jdk-9_ea123\bin\javac -Werror -cp C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\i032048\.m2\repository\junit\junit\4.4\junit-4.4.jar;C:\develop\git-repos\baeldung-tutorials\core-java-9\target\test-classes;C:\develop\git-repos\baeldung-tutorials\core-java-9\src\test %1 + + +@echo off +REM com\baeldung\java9\language\TryWithResourcesTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/Main.java b/core-java-9/src/test/java/com/baeldung/java9/Main.java new file mode 100644 index 0000000000..a41541f000 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/Main.java @@ -0,0 +1,22 @@ +package com.baeldung.java9; + +import com.baeldung.java9.language.PrivateInterface; +import com.baeldung.java9.language.TryWithResourcesTest; + +public class Main { + + public static void main(String args[]){ + PrivateInterface pi =new PrivateInterface() { + }; + pi.check(); + } + +// public static void main(String[] args) throws Exception { +// MultiResultionImageTest mri = new MultiResultionImageTest(); +// mri.baseMultiResImageTest(); +// +// TryWithResourcesTest tt = new TryWithResourcesTest(); +// // tt.test1(); +// } + +} 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 new file mode 100644 index 0000000000..d6c16b91bc --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -0,0 +1,48 @@ +package com.baeldung.java9; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import java.awt.Image; +import java.awt.image.BaseMultiResolutionImage; +import java.awt.image.BufferedImage; +import java.awt.image.MultiResolutionImage; +import java.util.List; + +import org.junit.Test; + +public class MultiResultionImageTest { + + + @Test + public void baseMultiResImageTest() { + int baseIndex = 1; + int length = 4; + BufferedImage[] resolutionVariants = new BufferedImage[length]; + for (int i = 0; i < length; i++) { + resolutionVariants[i] = createImage(i); + } + MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants); + List rvImageList = bmrImage.getResolutionVariants(); + assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length); + + for (int i = 0; i < length; i++) { + int imageSize = getSize(i); + Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize); + assertSame("Images should be the same", testRVImage, resolutionVariants[i]); + } + + } + + private static int getSize(int i) { + return 8 * (i + 1); + } + + + private static BufferedImage createImage(int i) { + return new BufferedImage(getSize(i), getSize(i), + BufferedImage.TYPE_INT_RGB); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java new file mode 100644 index 0000000000..c7d2f43800 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java @@ -0,0 +1,14 @@ +package com.baeldung.java9.httpclient; + +public class Main { + + public static void main(String[] args) throws Exception { + SimpleHttpRequests shr = new SimpleHttpRequests(); + shr.quickGet(); + shr.PostMehtod(); + + shr.configureHttpClient(); + shr.asyncGet(); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java new file mode 100644 index 0000000000..78a38f3357 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java @@ -0,0 +1,146 @@ +package com.baeldung.java9.httpclient; + +import static java.net.HttpURLConnection.HTTP_OK; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; + +import org.junit.Before; +import org.junit.Test; + +public class SimpleHttpRequests { + + // private URI httpURI = + + @Before + public void init() { + + } + + @Test + public void quickGet() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET(); + HttpResponse response = request.response(); + System.out.println(printHeaders(response.headers())); + String responseBody = response.body(HttpResponse.asString()); + assertTrue("Get response body size", responseBody.length() > 10); + } + + @Test + public void asyncGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET(); + long before = System.currentTimeMillis(); + CompletableFuture futureResponse = request.responseAsync(); + futureResponse.thenAccept( response -> { + HttpHeaders hs = response.headers(); + System.out.println(Thread.currentThread()+"\nHeaders:----------------------\n"+ printHeaders(hs)); + String responseBody = response.body(HttpResponse.asString()); + + + //System.out.println(responseBody); + }); + + + + + long after = System.currentTimeMillis(); + System.out.println(Thread.currentThread()+" waits "+ (after - before)); + assertTrue("Thread waits", (after - before) < 1500); + + futureResponse.join(); + + // Calculate some other thing in this Thread + //HttpResponse response = futureResponse.get(); + long afterAfter = System.currentTimeMillis(); + System.out.println(Thread.currentThread()+ "(afterAfter - before)"+ (afterAfter - before)); + + //String responseBody = response.body(HttpResponse.asString()); + //HttpHeaders hs = response.headers(); + //System.out.println(responseBody); + // assertTrue("Get response body size", responseBody.length() > 10); + } + + @Test + public void PostMehtod() throws URISyntaxException, IOException, InterruptedException { + HttpRequest.Builder requestBuilder = HttpRequest.create(new URI("http://localhost:8080")); + requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE); + HttpRequest request = requestBuilder.POST(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + @Test + public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{ + CookieManager cManager = new CookieManager(); + cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); + + SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); + + HttpClient.Builder hcBuilder = HttpClient.create(); + hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); + HttpClient httpClient = hcBuilder.build(); + HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://localhost:8443")); + + HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + System.out.println(response.body(HttpResponse.asString())); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{ + SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters(); + String [] proto = sslP1.getApplicationProtocols(); + String [] cifers = sslP1.getCipherSuites(); + System.out.println(printStringArr(proto)); + System.out.println(printStringArr(cifers)); + return sslP1; + } + + String printStringArr(String ... args ){ + if(args == null){ + return null; + } + StringBuilder sb = new StringBuilder(); + for (String s : args){ + sb.append(s); + sb.append("\n"); + } + return sb.toString(); + } + + String printHeaders(HttpHeaders h){ + if(h == null){ + return null; + } + + StringBuilder sb = new StringBuilder(); + Map> hMap = h.map(); + for(String k : hMap.keySet()){ + sb.append(k).append(":"); + List l = hMap.get(k); + if( l != null ){ + l.forEach( s -> { sb.append(s).append(","); } ); + } + sb.append("\n"); + } + return sb.toString(); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java new file mode 100644 index 0000000000..33da6486f4 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java @@ -0,0 +1,36 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +public class DiamondTest { + + static class FooClass { + FooClass(X x) { + } + + FooClass(X x, Z z) { + } + } + + @Test + public void diamondTest() { + FooClass fc = new FooClass<>(1) { + }; + FooClass fc0 = new FooClass<>(1) { + }; + FooClass fc1 = new FooClass<>(1) { + }; + FooClass fc2 = new FooClass<>(1) { + }; + + FooClass fc3 = new FooClass<>(1, "") { + }; + FooClass fc4 = new FooClass<>(1, "") { + }; + FooClass fc5 = new FooClass<>(1, "") { + }; + FooClass fc6 = new FooClass<>(1, "") { + }; + + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java new file mode 100644 index 0000000000..fd6a496b18 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java @@ -0,0 +1,23 @@ +package com.baeldung.java9.language; + +public interface PrivateInterface { + + private static String staticPrivate() { + return "static private"; + } + + private String instancePrivate() { + return "instance private"; + } + + public default void check(){ + String result = staticPrivate(); + if (!result.equals("static private")) + throw new AssertionError("Incorrect result for static private interface method"); + PrivateInterface pvt = new PrivateInterface() { + }; + result = pvt.instancePrivate(); + if (!result.equals("instance private")) + throw new AssertionError("Incorrect result for instance private interface method"); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java new file mode 100644 index 0000000000..687dfbc390 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java @@ -0,0 +1,70 @@ +package com.baeldung.java9.language; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class TryWithResourcesTest { + + static int closeCount = 0; + + static class MyAutoCloseable implements AutoCloseable{ + final FinalWrapper finalWrapper = new FinalWrapper(); + + public void close() { + closeCount++; + } + + static class FinalWrapper { + public final AutoCloseable finalCloseable = new AutoCloseable() { + @Override + public void close() throws Exception { + closeCount++; + } + }; + } + } + + @Test + public void tryWithResourcesTest() { + MyAutoCloseable mac = new MyAutoCloseable(); + + try (mac) { + assertEquals("Expected and Actual does not match", 0, closeCount); + } + + try (mac.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 1, closeCount); + } catch (Exception ex) { + } + + try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 2, closeCount); + } catch (Exception ex) { + } + + try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 3, closeCount); + } catch (Exception ex) { + } + + try { + throw new CloseableException(); + } catch (CloseableException ex) { + try (ex) { + assertEquals("Expected and Actual does not match", 4, closeCount); + } + } + assertEquals("Expected and Actual does not match", 5, closeCount); + } + + + static class CloseableException extends Exception implements AutoCloseable { + @Override + public void close() { + closeCount++; + } + } + +} + + diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/Main.java b/core-java-9/src/test/java/com/baeldung/java9/process/Main.java new file mode 100644 index 0000000000..b16baf4676 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/Main.java @@ -0,0 +1,18 @@ +package com.baeldung.java9.process; + +import java.security.NoSuchAlgorithmException; + +public class Main { + + public static void main(String[] args) throws Exception { + ProcessApi procApi = new ProcessApi(); + procApi.createAndDestroyProcess(); + + procApi.processInfoExample(); + + Thread.sleep(40200); + System.out.println("_______END!___________"); + + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java new file mode 100644 index 0000000000..419516cb64 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java @@ -0,0 +1,112 @@ +package com.baeldung.java9.process; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ProcessApi { + + + @Before + public void init() { + + } + + @Test + public void processInfoExample()throws NoSuchAlgorithmException{ + ProcessHandle self = ProcessHandle.current(); + long PID = self.getPid(); + ProcessHandle.Info procInfo = self.info(); + Optional args = procInfo.arguments(); + Optional cmd = procInfo.commandLine(); + Optional startTime = procInfo.startInstant(); + Optional cpuUsage = procInfo.totalCpuDuration(); + + waistCPU(); + System.out.println("Args "+ args); + System.out.println("Command " +cmd.orElse("EmptyCmd")); + System.out.println("Start time: "+ startTime.get().toString()); + System.out.println(cpuUsage.get().toMillis()); + + Stream allProc = ProcessHandle.current().children(); + allProc.forEach(p -> { + System.out.println("Proc "+ p.getPid()); + }); + + } + + @Test + public void createAndDestroyProcess() throws IOException, InterruptedException{ + int numberOfChildProcesses = 5; + for(int i=0; i < numberOfChildProcesses; i++){ + createNewJVM(ServiceMain.class, i).getPid(); + } + + Stream childProc = ProcessHandle.current().children(); + assertEquals( childProc.count(), numberOfChildProcesses); + + childProc = ProcessHandle.current().children(); + childProc.forEach(processHandle -> { + assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive()); + CompletableFuture onProcExit = processHandle.onExit(); + onProcExit.thenAccept(procHandle -> { + System.out.println("Process with PID "+ procHandle.getPid() + " has stopped"); + }); + }); + + Thread.sleep(10000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy()); + }); + + Thread.sleep(5000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive()); + }); + + } + + private Process createNewJVM(Class mainClass, int number) throws IOException{ + ArrayList cmdParams = new ArrayList(5); + cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath()); + cmdParams.add("-cp"); + cmdParams.add(ProcessUtils.getClassPath()); + cmdParams.add(mainClass.getName()); + cmdParams.add("Service "+ number); + ProcessBuilder myService = new ProcessBuilder(cmdParams); + myService.inheritIO(); + return myService.start(); + } + + private void waistCPU() throws NoSuchAlgorithmException{ + ArrayList randArr = new ArrayList(4096); + SecureRandom sr = SecureRandom.getInstanceStrong(); + Duration somecpu = Duration.ofMillis(4200L); + Instant end = Instant.now().plus(somecpu); + while (Instant.now().isBefore(end)) { + //System.out.println(sr.nextInt()); + randArr.add( sr.nextInt() ); + } + } + +} diff --git a/core-java-9/src/test/resources/.gitignore b/core-java-9/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file From 94f08d43af8890b2a53b76c26b9a468b8f00f1d3 Mon Sep 17 00:00:00 2001 From: maverick Date: Mon, 22 Aug 2016 13:21:24 +0530 Subject: [PATCH 04/68] sort variant and parallel sort added --- .../java/org/baeldung/java/sorting/ArraySort.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java index 3e55ab7f6a..cacbcdb727 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java @@ -84,5 +84,20 @@ public class ArraySort { }); } + + @Test + public void arraySortVariant() { + System.out.println(Arrays.toString(numbers)); + Arrays.sort(numbers, 3, 7); + System.out.println(Arrays.toString(numbers)); + + } + + @Test + public void arrayParallelSortVariant() { + + Arrays.parallelSort(numbers); + + } } From 9cf6ea22537a8e5c1f1bd0de8bb5b045d8d45e25 Mon Sep 17 00:00:00 2001 From: antonk Date: Sat, 27 Aug 2016 10:42:13 +0300 Subject: [PATCH 05/68] Fixed Maven build with experimental java 9 Maven compiler plug-in. Minor code changes --- .../java9/language/PrivateInterface.java | 23 ------------------- .../PrivateInterfaceTest.java} | 0 pom.xml | 1 + 3 files changed, 1 insertion(+), 23 deletions(-) delete mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java rename core-java-9/src/test/java/com/baeldung/java9/{Main.java => language/PrivateInterfaceTest.java} (100%) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java deleted file mode 100644 index fd6a496b18..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterface.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.java9.language; - -public interface PrivateInterface { - - private static String staticPrivate() { - return "static private"; - } - - private String instancePrivate() { - return "instance private"; - } - - public default void check(){ - String result = staticPrivate(); - if (!result.equals("static private")) - throw new AssertionError("Incorrect result for static private interface method"); - PrivateInterface pvt = new PrivateInterface() { - }; - result = pvt.instancePrivate(); - if (!result.equals("instance private")) - throw new AssertionError("Incorrect result for instance private interface method"); - } -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/Main.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java similarity index 100% rename from core-java-9/src/test/java/com/baeldung/java9/Main.java rename to core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java diff --git a/pom.xml b/pom.xml index d2f5d83b46..cbe3055dbe 100644 --- a/pom.xml +++ b/pom.xml @@ -18,6 +18,7 @@ apache-fop core-java core-java-8 + core-java-9 couchbase-sdk-intro couchbase-sdk-spring-service From 9c5404ead8e1799ee5da18892fc07b3ae134f5f6 Mon Sep 17 00:00:00 2001 From: Christian Raedel Date: Wed, 31 Aug 2016 03:18:02 +0200 Subject: [PATCH 06/68] BAEL-305: Runnable demo application --- .../front-controller-pattern/pom.xml | 41 +++++++++++++++++ .../controller/FrontControllerServlet.java | 45 +++++++++++++++++++ .../controller/commands/BookCommand.java | 22 +++++++++ .../controller/commands/FrontCommand.java | 32 +++++++++++++ .../controller/commands/UnknownCommand.java | 11 +++++ .../patterns/front/controller/data/Book.java | 40 +++++++++++++++++ .../front/controller/data/Bookshelf.java | 32 +++++++++++++ .../src/main/webapp/WEB-INF/jboss-web.xml | 6 +++ .../main/webapp/WEB-INF/jsp/book-found.jsp | 4 ++ .../main/webapp/WEB-INF/jsp/book-notfound.jsp | 2 + .../src/main/webapp/WEB-INF/jsp/unknown.jsp | 1 + .../src/main/webapp/WEB-INF/web.xml | 11 +++++ enterprise-patterns/pom.xml | 35 +++++++++++++++ 13 files changed, 282 insertions(+) create mode 100644 enterprise-patterns/front-controller-pattern/pom.xml create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml create mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp create mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp create mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp create mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml create mode 100644 enterprise-patterns/pom.xml diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml new file mode 100644 index 0000000000..eefd52a52d --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + front-controller-pattern + war + + + enterprise-patterns-parent + com.baeldung.enterprise.patterns + 1.0.0-SNAPSHOT + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + ${env.DEPLOYMENTS} + + + + + 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 new file mode 100644 index 0000000000..4dfc12c050 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.enterprise.patterns.front.controller; + +import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; +import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FrontControllerServlet extends HttpServlet { + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(getServletContext(), request, response); + command.process(); + } + + 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( + String.format( + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + request.getParameter("command") + ) + ); + } catch (ClassNotFoundException e) { + return UnknownCommand.class; + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java new file mode 100644 index 0000000000..e858cd98a9 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java @@ -0,0 +1,22 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import com.baeldung.enterprise.patterns.front.controller.data.Book; +import com.baeldung.enterprise.patterns.front.controller.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class BookCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + Book book = Bookshelf.getInstance() + .findByTitle(request.getParameter("title")); + if (book != null) { + request.setAttribute("book", book); + forward("book-found"); + } else { + request.setAttribute("books", Bookshelf.getInstance().getBooks()); + forward("book-notfound"); + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java new file mode 100644 index 0000000000..12a008faeb --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java @@ -0,0 +1,32 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand { + protected ServletContext context; + protected HttpServletRequest request; + protected HttpServletResponse response; + + public void init( + ServletContext servletContext, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse + ) { + this.context = servletContext; + this.request = servletRequest; + this.response = servletResponse; + } + + public abstract void process() throws ServletException, IOException; + + protected void forward(String target) throws ServletException, IOException { + target = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = context.getRequestDispatcher(target); + dispatcher.forward(request, response); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java new file mode 100644 index 0000000000..90103c8f42 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java @@ -0,0 +1,11 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + forward("unknown"); + } +} 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 new file mode 100644 index 0000000000..634e05c3a0 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public class Book { + private String author; + private String title; + private Double price; + + public Book() { + } + + public Book(String author, String title, Double price) { + this.author = author; + this.title = title; + this.price = price; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + 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; + } +} 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 new file mode 100644 index 0000000000..142435e2e3 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,32 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +import java.util.ArrayList; +import java.util.List; + +public class Bookshelf { + private static Bookshelf INSTANCE = new Bookshelf(); + private List books = new ArrayList<>(); + + public static Bookshelf getInstance() { + if (INSTANCE.books.size() == 0) { + INSTANCE.init(); + } + return INSTANCE; + } + + private void init() { + books.add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + books.add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + public Book findByTitle(String title) { + return books.stream() + .filter(book -> book.getTitle().equalsIgnoreCase(title)) + .findFirst() + .orElse(null); + } + + public List getBooks() { + return books; + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000..db2d804135 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,6 @@ + + + + /front-controller/ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..8fa82ee816 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,4 @@ +

Our Bookshelf contains this title:

+

${book.getTitle()}

+

Author: ${book.getAuthor()}

+ diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..e8ce67ac96 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -0,0 +1,2 @@ +

Our Bookshelf doesn't contains this title:

+

${param.get("title")}

diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..d348f757d9 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1 @@ +

Sorry, this command is not known!

diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..372ee42800 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + front-controller + com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + + + front-controller + / + + diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml new file mode 100644 index 0000000000..2fba12547f --- /dev/null +++ b/enterprise-patterns/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + enterprise-patterns-parent + pom + + front-controller-pattern + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + From ed03a59711764bbf5b90fc4761e19c1b2f84b605 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Wed, 31 Aug 2016 03:38:46 +0200 Subject: [PATCH 07/68] BAEL-305: Some minor changes --- .../{BookCommand.java => SearchCommand.java} | 2 +- .../front/controller/data/Bookshelf.java | 2 +- .../src/main/webapp/WEB-INF/jsp/book-found.jsp | 16 ++++++++++++---- .../main/webapp/WEB-INF/jsp/book-notfound.jsp | 12 ++++++++++-- .../src/main/webapp/WEB-INF/jsp/unknown.jsp | 10 +++++++++- 5 files changed, 33 insertions(+), 9 deletions(-) rename enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/{BookCommand.java => SearchCommand.java} (93%) diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java similarity index 93% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java rename to enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java index e858cd98a9..4d9e5f7b79 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/BookCommand.java +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java @@ -6,7 +6,7 @@ import com.baeldung.enterprise.patterns.front.controller.data.Bookshelf; import javax.servlet.ServletException; import java.io.IOException; -public class BookCommand extends FrontCommand { +public class SearchCommand extends FrontCommand { @Override public void process() throws ServletException, IOException { Book book = Bookshelf.getInstance() 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 142435e2e3..ad9758bf76 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 @@ -21,7 +21,7 @@ public class Bookshelf { public Book findByTitle(String title) { return books.stream() - .filter(book -> book.getTitle().equalsIgnoreCase(title)) + .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) .findFirst() .orElse(null); } diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp index 8fa82ee816..42e08b4a46 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -1,4 +1,12 @@ -

Our Bookshelf contains this title:

-

${book.getTitle()}

-

Author: ${book.getAuthor()}

- + + + + Bookshelf: Title found + + +

Our Bookshelf contains this title:

+

${book.getTitle()}

+

Author: ${book.getAuthor()}

+ + + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp index e8ce67ac96..2f8ac01755 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -1,2 +1,10 @@ -

Our Bookshelf doesn't contains this title:

-

${param.get("title")}

+ + + + Bookshelf: Title not found + + +

Our Bookshelf doesn't contains this title:

+

${param.get("title")}

+ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp index d348f757d9..b52b2de8d5 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -1 +1,9 @@ -

Sorry, this command is not known!

+ + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + From d18e64037ed837ab89b49e4e17a859ce8bb2e71e Mon Sep 17 00:00:00 2001 From: maverick Date: Wed, 31 Aug 2016 19:29:25 +0530 Subject: [PATCH 08/68] Changes for naming conventions in test functions --- .../src/test/java/org/baeldung/java/sorting/ArraySort.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java index cacbcdb727..35e6c8b46d 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java @@ -51,7 +51,7 @@ public class ArraySort { } @Test - public void comparatorSortIntArray_Java8Lambda() { + public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { Arrays.sort(integers, (a, b) -> { return a - b; }); @@ -86,7 +86,7 @@ public class ArraySort { } @Test - public void arraySortVariant() { + public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { System.out.println(Arrays.toString(numbers)); Arrays.sort(numbers, 3, 7); System.out.println(Arrays.toString(numbers)); @@ -94,7 +94,7 @@ public class ArraySort { } @Test - public void arrayParallelSortVariant() { + public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { Arrays.parallelSort(numbers); From ffe5ce630c2d1e991dde66c3be3b9759af6ad464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Thu, 1 Sep 2016 14:09:51 +0200 Subject: [PATCH 09/68] BAEL-305: Included embedded Jetty. Use more recent version of servlet api. --- .../front-controller-pattern/pom.xml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml index eefd52a52d..dbcd4f1b1d 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -16,8 +16,8 @@ javax.servlet - servlet-api - 2.5 + javax.servlet-api + 3.1.0 provided @@ -29,11 +29,13 @@ maven-compiler-plugin - org.apache.maven.plugins - maven-war-plugin - 3.0.0 + org.eclipse.jetty + jetty-maven-plugin + 9.4.0.M1 - ${env.DEPLOYMENTS} + + /front-controller + From 525c93059c32f92da575177d0ec6c79d4b77f6fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Thu, 1 Sep 2016 21:41:37 +0200 Subject: [PATCH 10/68] BAEL-305: Refactored Book and Bookshelf as interfaces and implemented them. --- .../front-controller-pattern/pom.xml | 2 +- .../controller/commands/SearchCommand.java | 5 +- .../patterns/front/controller/data/Book.java | 39 +++------------- .../front/controller/data/BookImpl.java | 46 +++++++++++++++++++ .../front/controller/data/Bookshelf.java | 31 +++---------- .../front/controller/data/BookshelfImpl.java | 24 ++++++++++ 6 files changed, 87 insertions(+), 60 deletions(-) create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java create mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml index dbcd4f1b1d..5f9152ad42 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -17,7 +17,7 @@ javax.servlet javax.servlet-api - 3.1.0 + 4.0.0-b01 provided diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java index 4d9e5f7b79..0c5bd64bbc 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java @@ -1,7 +1,7 @@ package com.baeldung.enterprise.patterns.front.controller.commands; import com.baeldung.enterprise.patterns.front.controller.data.Book; -import com.baeldung.enterprise.patterns.front.controller.data.Bookshelf; +import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; import javax.servlet.ServletException; import java.io.IOException; @@ -9,13 +9,12 @@ import java.io.IOException; public class SearchCommand extends FrontCommand { @Override public void process() throws ServletException, IOException { - Book book = Bookshelf.getInstance() + Book book = new BookshelfImpl().getInstance() .findByTitle(request.getParameter("title")); if (book != null) { request.setAttribute("book", book); forward("book-found"); } else { - request.setAttribute("books", Bookshelf.getInstance().getBooks()); forward("book-notfound"); } } 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 ad9758bf76..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 @@ -1,32 +1,15 @@ package com.baeldung.enterprise.patterns.front.controller.data; -import java.util.ArrayList; -import java.util.List; +public interface Bookshelf { -public class Bookshelf { - private static Bookshelf INSTANCE = new Bookshelf(); - private List books = new ArrayList<>(); - - public static Bookshelf getInstance() { - if (INSTANCE.books.size() == 0) { - INSTANCE.init(); - } - return INSTANCE; + default void init() { + add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); } - private void init() { - books.add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); - books.add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); - } + Bookshelf getInstance(); - public Book findByTitle(String title) { - return books.stream() - .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) - .findFirst() - .orElse(null); - } + boolean add(E book); - public List getBooks() { - return books; - } + Book findByTitle(String title); } diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java new file mode 100644 index 0000000000..3862418857 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java @@ -0,0 +1,24 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +import java.util.ArrayList; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + private static Bookshelf INSTANCE; + + @Override + public Bookshelf getInstance() { + if (INSTANCE == null) { + INSTANCE = new BookshelfImpl(); + INSTANCE.init(); + } + return INSTANCE; + } + + @Override + public Book findByTitle(String title) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) + .findFirst() + .orElse(null); + } +} From 3f204ebd59d754a66b018e16dd6c291a6a4b3009 Mon Sep 17 00:00:00 2001 From: anton-k Date: Fri, 2 Sep 2016 01:43:49 +0300 Subject: [PATCH 11/68] Running maven build and changes to some of tests. --- .../java/com/baeldung/java9/httpclient/Main.java | 14 -------------- ...tpRequests.java => SimpleHttpRequestsTest.java} | 0 2 files changed, 14 deletions(-) delete mode 100644 core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java rename core-java-9/src/test/java/com/baeldung/java9/httpclient/{SimpleHttpRequests.java => SimpleHttpRequestsTest.java} (100%) diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java deleted file mode 100644 index c7d2f43800..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/httpclient/Main.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.java9.httpclient; - -public class Main { - - public static void main(String[] args) throws Exception { - SimpleHttpRequests shr = new SimpleHttpRequests(); - shr.quickGet(); - shr.PostMehtod(); - - shr.configureHttpClient(); - shr.asyncGet(); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java similarity index 100% rename from core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequests.java rename to core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java From 27f540c9bfe15c16c156eeed3098feef3ddb2c10 Mon Sep 17 00:00:00 2001 From: anton-k Date: Fri, 2 Sep 2016 01:48:15 +0300 Subject: [PATCH 12/68] Fixed maven build and modifications ot some tests --- core-java-9/pom.xml | 192 +++++++----------- .../java9/language/PrivateInterface.java | 23 +++ .../baeldung/java9/process/ProcessUtils.java | 4 - .../httpclient/SimpleHttpRequestsTest.java | 58 ++---- .../java9/language/PrivateInterfaceTest.java | 21 +- 5 files changed, 127 insertions(+), 171 deletions(-) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 06421915a3..b29838d283 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -1,138 +1,102 @@ - - 4.0.0 - com.baeldung - core-java9 - 0.1-SNAPSHOT + + 4.0.0 + com.baeldung + core-java9 + 0.2-SNAPSHOT - core-java9 + core-java9 - + + + apache.snapshots + http://repository.apache.org/snapshots/ + + - - - org.slf4j - slf4j-api - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - + - - core-java-9 - - - src/main/resources - true - - + + core-java-9 - + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - true - C:\develop\jdks\jdk-9_ea122\bin\javac - 1.9 - - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.9 + 1.9 - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + true + + - + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + - - - 1.7.13 - 1.0.13 + - - 5.1.3.Final + - - 19.0 - 3.4 + + + 1.7.13 + 1.0.13 - - 1.3 - 4.12 - 1.10.19 - - 3.5.1 - - - 2.6 - 2.19.1 - 2.7 + + + 3.6-jigsaw-SNAPSHOT - + + 2.19.1 + + + 1.3 + 4.12 + 1.10.19 + diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java new file mode 100644 index 0000000000..fd6a496b18 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java @@ -0,0 +1,23 @@ +package com.baeldung.java9.language; + +public interface PrivateInterface { + + private static String staticPrivate() { + return "static private"; + } + + private String instancePrivate() { + return "instance private"; + } + + public default void check(){ + String result = staticPrivate(); + if (!result.equals("static private")) + throw new AssertionError("Incorrect result for static private interface method"); + PrivateInterface pvt = new PrivateInterface() { + }; + result = pvt.instancePrivate(); + if (!result.equals("instance private")) + throw new AssertionError("Incorrect result for instance private interface method"); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java index b9c1cf1880..d6682bd0c8 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -8,10 +8,6 @@ import java.time.Duration; import java.time.Instant; import java.util.stream.Stream; -import org.junit.Before; -import org.junit.Test; - -import junit.framework.Assert; public class ProcessUtils { diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java index 78a38f3357..ab28b0a805 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java @@ -1,4 +1,6 @@ -package com.baeldung.java9.httpclient; +package com.baeldung.java9.httpclient; + + import static java.net.HttpURLConnection.HTTP_OK; import static org.junit.Assert.assertTrue; @@ -24,61 +26,40 @@ import javax.net.ssl.SSLParameters; import org.junit.Before; import org.junit.Test; -public class SimpleHttpRequests { +public class SimpleHttpRequestsTest { - // private URI httpURI = + private URI httpURI; @Before - public void init() { - + public void init() throws URISyntaxException { + httpURI = new URI("http://www.baeldung.com/"); } @Test public void quickGet() throws IOException, InterruptedException, URISyntaxException { - HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET(); + HttpRequest request = HttpRequest.create( httpURI ).GET(); HttpResponse response = request.response(); - System.out.println(printHeaders(response.headers())); + int responseStatusCode = response.statusCode(); String responseBody = response.body(HttpResponse.asString()); - assertTrue("Get response body size", responseBody.length() > 10); + assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); } @Test - public void asyncGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ - HttpRequest request = HttpRequest.create(new URI("http://localhost:8080")).GET(); + public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + HttpRequest request = HttpRequest.create(httpURI).GET(); long before = System.currentTimeMillis(); CompletableFuture futureResponse = request.responseAsync(); futureResponse.thenAccept( response -> { - HttpHeaders hs = response.headers(); - System.out.println(Thread.currentThread()+"\nHeaders:----------------------\n"+ printHeaders(hs)); String responseBody = response.body(HttpResponse.asString()); - - - //System.out.println(responseBody); - }); - - - - - long after = System.currentTimeMillis(); - System.out.println(Thread.currentThread()+" waits "+ (after - before)); - assertTrue("Thread waits", (after - before) < 1500); - - futureResponse.join(); - - // Calculate some other thing in this Thread - //HttpResponse response = futureResponse.get(); - long afterAfter = System.currentTimeMillis(); - System.out.println(Thread.currentThread()+ "(afterAfter - before)"+ (afterAfter - before)); - - //String responseBody = response.body(HttpResponse.asString()); - //HttpHeaders hs = response.headers(); - //System.out.println(responseBody); - // assertTrue("Get response body size", responseBody.length() > 10); + }); + HttpResponse resp = futureResponse.get(); + HttpHeaders hs = resp.headers(); + assertTrue("There should be more then 1 header.", hs.map().size() >1); } @Test - public void PostMehtod() throws URISyntaxException, IOException, InterruptedException { - HttpRequest.Builder requestBuilder = HttpRequest.create(new URI("http://localhost:8080")); + public void postMehtod() throws URISyntaxException, IOException, InterruptedException { + HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI); requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE); HttpRequest request = requestBuilder.POST(); HttpResponse response = request.response(); @@ -96,12 +77,11 @@ public class SimpleHttpRequests { HttpClient.Builder hcBuilder = HttpClient.create(); hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); HttpClient httpClient = hcBuilder.build(); - HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://localhost:8443")); + HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com")); HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); HttpResponse response = request.response(); int statusCode = response.statusCode(); - System.out.println(response.body(HttpResponse.asString())); assertTrue("HTTP return code", statusCode == HTTP_OK); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java index a41541f000..29ef3930f8 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java @@ -1,22 +1,15 @@ -package com.baeldung.java9; +package com.baeldung.java9.language; import com.baeldung.java9.language.PrivateInterface; -import com.baeldung.java9.language.TryWithResourcesTest; +import org.junit.Test; -public class Main { +public class PrivateInterfaceTest { - public static void main(String args[]){ - PrivateInterface pi =new PrivateInterface() { + @Test + public void test() { + PrivateInterface piClass = new PrivateInterface() { }; - pi.check(); + piClass.check(); } - -// public static void main(String[] args) throws Exception { -// MultiResultionImageTest mri = new MultiResultionImageTest(); -// mri.baseMultiResImageTest(); -// -// TryWithResourcesTest tt = new TryWithResourcesTest(); -// // tt.test1(); -// } } From 7b6200728d93a528c0be27f075becf7c121a6446 Mon Sep 17 00:00:00 2001 From: anton-k11 Date: Fri, 2 Sep 2016 02:08:55 +0300 Subject: [PATCH 13/68] Removing unnecessary files --- core-java-9/src/test/build.bat | 10 ---------- .../java/com/baeldung/java9/process/Main.java | 18 ------------------ 2 files changed, 28 deletions(-) delete mode 100644 core-java-9/src/test/build.bat delete mode 100644 core-java-9/src/test/java/com/baeldung/java9/process/Main.java diff --git a/core-java-9/src/test/build.bat b/core-java-9/src/test/build.bat deleted file mode 100644 index c6208b89d2..0000000000 --- a/core-java-9/src/test/build.bat +++ /dev/null @@ -1,10 +0,0 @@ -@echo off -REM C:\develop\jdks\jdk-9_ea123\bin\javac -REM -REM C:\develop\jdks\jdk1.8.0_45\bin\javac -@echo on -C:\develop\jdks\jdk-9_ea123\bin\javac -Werror -cp C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;C:\Users\i032048\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\i032048\.m2\repository\junit\junit\4.4\junit-4.4.jar;C:\develop\git-repos\baeldung-tutorials\core-java-9\target\test-classes;C:\develop\git-repos\baeldung-tutorials\core-java-9\src\test %1 - - -@echo off -REM com\baeldung\java9\language\TryWithResourcesTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/Main.java b/core-java-9/src/test/java/com/baeldung/java9/process/Main.java deleted file mode 100644 index b16baf4676..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/process/Main.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.java9.process; - -import java.security.NoSuchAlgorithmException; - -public class Main { - - public static void main(String[] args) throws Exception { - ProcessApi procApi = new ProcessApi(); - procApi.createAndDestroyProcess(); - - procApi.processInfoExample(); - - Thread.sleep(40200); - System.out.println("_______END!___________"); - - } - -} From 747c3169ee026fd68012eacdcc3378895331face Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Sat, 3 Sep 2016 19:40:09 +0200 Subject: [PATCH 14/68] BAEL-305: Updated servlet spec to 3.1. --- enterprise-patterns/front-controller-pattern/pom.xml | 2 +- .../src/main/webapp/WEB-INF/web.xml | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml index 5f9152ad42..dbcd4f1b1d 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -17,7 +17,7 @@ javax.servlet javax.servlet-api - 4.0.0-b01 + 3.1.0 provided diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml index 372ee42800..77113db09b 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml @@ -1,5 +1,9 @@ - + front-controller com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet From eb6f0214ca6a08fbab2631e169667e7b6208be99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Sat, 3 Sep 2016 20:13:55 +0200 Subject: [PATCH 15/68] BAEL-305: Simplified FrontControllerServlet. Removed unused JBoss deployment descriptor. --- .../controller/FrontControllerServlet.java | 19 ++++++------------- .../src/main/webapp/WEB-INF/jboss-web.xml | 6 ------ 2 files changed, 6 insertions(+), 19 deletions(-) delete mode 100644 enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml 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/webapp/WEB-INF/jboss-web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml deleted file mode 100644 index db2d804135..0000000000 --- a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jboss-web.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - /front-controller/ - From 491a4b1f95e1ea117c22fc07b47a678a689fec4f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 4 Sep 2016 19:18:58 +0300 Subject: [PATCH 16/68] BAEL-10 custom model, dao, service, userdetails service, controller and views for register and login, configurations --- ....eclipse.wst.common.project.facet.core.xml | 2 +- spring-jpa/.springBeans | 16 ++++ spring-jpa/pom.xml | 81 +++++++++++++++++ .../org/baeldung/custom/config/MvcConfig.java | 42 +++++++++ .../config/PersistenceDerbyJPAConfig.java | 87 +++++++++++++++++++ .../custom/config/SecSecurityConfig.java | 75 ++++++++++++++++ .../baeldung/persistence/model/MyUser.java | 76 ++++++++++++++++ .../multiple/dao/user/MyUserDAO.java | 40 +++++++++ .../persistence/service/MyUserService.java | 48 ++++++++++ .../security/MyUserDetailsService.java | 36 ++++++++ .../org/baeldung/security/UserController.java | 52 +++++++++++ .../main/java/org/baeldung/web/MyUserDto.java | 41 +++++++++ .../resources/persistence-derby.properties | 10 +++ .../webapp/WEB-INF/mvc-dispatcher-servlet.xml | 86 ++++++++++++++++++ .../src/main/webapp/WEB-INF/views/index.jsp | 35 ++++++++ .../src/main/webapp/WEB-INF/views/login.jsp | 29 +++++++ .../main/webapp/WEB-INF/views/register.jsp | 24 +++++ spring-jpa/src/main/webapp/WEB-INF/web.xml | 50 +++++++++++ 18 files changed, 829 insertions(+), 1 deletion(-) create mode 100644 spring-jpa/.springBeans create mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java create mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java create mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java create mode 100644 spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java create mode 100644 spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java create mode 100644 spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java create mode 100644 spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java create mode 100644 spring-jpa/src/main/java/org/baeldung/security/UserController.java create mode 100644 spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java create mode 100644 spring-jpa/src/main/resources/persistence-derby.properties create mode 100644 spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml create mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/index.jsp create mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/login.jsp create mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/register.jsp create mode 100644 spring-jpa/src/main/webapp/WEB-INF/web.xml diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml index b1c99d7726..a8a65de481 100644 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,7 +1,7 @@ - + diff --git a/spring-jpa/.springBeans b/spring-jpa/.springBeans new file mode 100644 index 0000000000..85bcd37cff --- /dev/null +++ b/spring-jpa/.springBeans @@ -0,0 +1,16 @@ + + + 1 + + + + + + + src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml + + + + + + diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 25dd960435..531cfe3468 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -6,6 +6,7 @@ 0.1-SNAPSHOT spring-jpa + war @@ -115,6 +116,78 @@ test + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + javax.servlet + servlet-api + 3.0-alpha-1 + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + @@ -138,6 +211,12 @@ + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + org.apache.maven.plugins maven-surefire-plugin @@ -180,6 +259,7 @@ 4.2.5.RELEASE + 4.0.4.RELEASE 3.20.0-GA @@ -210,6 +290,7 @@ 3.5.1 + 2.6 2.19.1 2.7 1.4.18 diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java new file mode 100644 index 0000000000..4a9e737a92 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.custom.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/"); + registry.addViewController("/index"); + registry.addViewController("/login"); + registry.addViewController("/register"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java new file mode 100644 index 0000000000..19bf952e70 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -0,0 +1,87 @@ +package org.baeldung.custom.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceDerbyJPAConfig { + + @Autowired + private Environment env; + + public PersistenceDerbyJPAConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public MyUserDAO myUserDAO() { + final MyUserDAO myUserDAO = new MyUserDAO(); + return myUserDAO; + } +} \ No newline at end of file diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java new file mode 100644 index 0000000000..d20674844a --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.custom.config; + +import org.baeldung.persistence.service.MyUserService; +import org.baeldung.security.MyUserDetailsService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.authenticationProvider(authenticationProvider()); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/*").permitAll() + .and() + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .defaultSuccessUrl("/",true) + .failureUrl("/login?error=true") + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/"); + // @formatter:on + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(myUserDetailsService()); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public MyUserDetailsService myUserDetailsService() { + return new MyUserDetailsService(); + } + + @Bean + public MyUserService myUserService() { + return new MyUserService(); + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java new file mode 100644 index 0000000000..0a097f2782 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -0,0 +1,76 @@ +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; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_custom_user_service") +public class MyUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + private String name; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + private boolean enabled; + + public MyUser() { + } + + public int 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; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + @Override + public String toString() { + return "MyUser [name=" + name + ", username=" + username + ", password=" + password + ", enabled=" + enabled + "]"; + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java new file mode 100644 index 0000000000..1de8c61442 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java @@ -0,0 +1,40 @@ +package org.baeldung.persistence.multiple.dao.user; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.MyUser; +import org.springframework.stereotype.Repository; + +@Repository +public class MyUserDAO { + + @PersistenceContext + private EntityManager entityManager; + + public MyUser findByUsername(final String username) { + final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); + query.setParameter("username", username); + final List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public MyUser save(final MyUser user) { + entityManager.persist(user); + return user; + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(final EntityManager entityManager) { + this.entityManager = entityManager; + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java b/spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java new file mode 100644 index 0000000000..a382e92664 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java @@ -0,0 +1,48 @@ +package org.baeldung.persistence.service; + +import javax.transaction.Transactional; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.baeldung.web.MyUserDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class MyUserService { + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + MyUserDAO myUserDAO; + + public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { + if (usernameExists(accountDto.getUsername())) { + throw new Exception("There is an account with that username: " + accountDto.getUsername()); + } + final MyUser user = new MyUser(); + + user.setUsername(accountDto.getUsername()); + user.setPassword(passwordEncoder.encode(accountDto.getPassword())); + user.setName(accountDto.getName()); + user.setEnabled(true); + return myUserDAO.save(user); + } + + public MyUser getUserByUsername(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + return user; + } + + private boolean usernameExists(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + if (user != null) { + return true; + } + return false; + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..0299d7cdcf --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,36 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Collection; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service("userDetailsService") +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + MyUserDAO myUserDAO; + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final MyUser user = myUserDAO.findByUsername(username); + + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + username); + } + else { + final Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority("ROLE_USER")); + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities); + } + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/security/UserController.java b/spring-jpa/src/main/java/org/baeldung/security/UserController.java new file mode 100644 index 0000000000..8664816a32 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/security/UserController.java @@ -0,0 +1,52 @@ +package org.baeldung.security; + +import javax.annotation.Resource; + +import org.baeldung.persistence.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class UserController { + + @Resource + MyUserService myUserService; + + @RequestMapping(value = "/register", method = RequestMethod.POST) + public String registerUserAccount(final MyUserDto accountDto, final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + try { + myUserService.registerNewUserAccount(accountDto); + model.addAttribute("message", "Registration successful"); + return "index"; + } + catch(final Exception exc){ + model.addAttribute("message", "Registration failed"); + + return "index"; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHomepage(final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + return "index"; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String getRegister() { + return "register"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String getLogin() { + return "login"; + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java b/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java new file mode 100644 index 0000000000..ec95ec43bf --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java @@ -0,0 +1,41 @@ +package org.baeldung.web; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class MyUserDto { + @NotNull + @Size(min = 1) + private String username; + + @NotNull + @Size(min = 1) + private String name; + + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + +} diff --git a/spring-jpa/src/main/resources/persistence-derby.properties b/spring-jpa/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..2e2dee983b --- /dev/null +++ b/spring-jpa/src/main/resources/persistence-derby.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml new file mode 100644 index 0000000000..2b33a1384a --- /dev/null +++ b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + + + + + diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000000..0c89257cd2 --- /dev/null +++ b/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + +Welcome! + + + + + + + +Register +

+ +Login + +

+${message } +

+ +Hello, ${name }! +
+
+Logout +
+ + + \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..29431f426d --- /dev/null +++ b/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,29 @@ +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + + +

Login

+ +
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ Username or password invalid! + + \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp new file mode 100644 index 0000000000..68b3ac14b0 --- /dev/null +++ b/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Welcome! + + + + + +Register here:

+
+Username:
+Password:
+Name:

+ +
+ + + \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/web.xml b/spring-jpa/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..2eb6e88c31 --- /dev/null +++ b/spring-jpa/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,50 @@ + + + + Spring MVC Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.custom.config + + + + org.springframework.web.context.ContextLoaderListener + + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + index.jsp + + + \ No newline at end of file From ff3d29a8f30b44c9ff16e4b6e0fba96711412dea Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 4 Sep 2016 19:44:26 +0300 Subject: [PATCH 17/68] fix conflict with existing tests --- .../baeldung/custom/config/PersistenceDerbyJPAConfig.java | 2 +- .../java/org/baeldung/custom/config/SecSecurityConfig.java | 2 +- .../java/org/baeldung/security/MyUserDetailsService.java | 2 +- .../src/main/java/org/baeldung/security/UserController.java | 2 +- .../multiple/dao/user => user/dao}/MyUserDAO.java | 2 +- .../{persistence => user}/service/MyUserService.java | 4 ++-- .../src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml | 2 +- spring-jpa/src/main/webapp/WEB-INF/web.xml | 5 +++-- 8 files changed, 11 insertions(+), 10 deletions(-) rename spring-jpa/src/main/java/org/baeldung/{persistence/multiple/dao/user => user/dao}/MyUserDAO.java (95%) rename spring-jpa/src/main/java/org/baeldung/{persistence => user}/service/MyUserService.java (93%) diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java index 19bf952e70..812709111d 100644 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -5,7 +5,7 @@ import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.baeldung.user.dao.MyUserDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java index d20674844a..44df02980f 100644 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -1,7 +1,7 @@ package org.baeldung.custom.config; -import org.baeldung.persistence.service.MyUserService; import org.baeldung.security.MyUserDetailsService; +import org.baeldung.user.service.MyUserService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; diff --git a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java index 0299d7cdcf..21e3985bac 100644 --- a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.Collection; import org.baeldung.persistence.model.MyUser; -import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.baeldung.user.dao.MyUserDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; diff --git a/spring-jpa/src/main/java/org/baeldung/security/UserController.java b/spring-jpa/src/main/java/org/baeldung/security/UserController.java index 8664816a32..b1c96e72c0 100644 --- a/spring-jpa/src/main/java/org/baeldung/security/UserController.java +++ b/spring-jpa/src/main/java/org/baeldung/security/UserController.java @@ -2,7 +2,7 @@ package org.baeldung.security; import javax.annotation.Resource; -import org.baeldung.persistence.service.MyUserService; +import org.baeldung.user.service.MyUserService; import org.baeldung.web.MyUserDto; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java b/spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java similarity index 95% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java rename to spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java index 1de8c61442..5741d19bf2 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/MyUserDAO.java +++ b/spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.multiple.dao.user; +package org.baeldung.user.dao; import java.util.List; diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java similarity index 93% rename from spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java rename to spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java index a382e92664..866ac88f29 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/service/MyUserService.java +++ b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java @@ -1,9 +1,9 @@ -package org.baeldung.persistence.service; +package org.baeldung.user.service; import javax.transaction.Transactional; import org.baeldung.persistence.model.MyUser; -import org.baeldung.persistence.multiple.dao.user.MyUserDAO; +import org.baeldung.user.dao.MyUserDAO; import org.baeldung.web.MyUserDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; diff --git a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml index 2b33a1384a..47082453b9 100644 --- a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -40,7 +40,7 @@ - + diff --git a/spring-jpa/src/main/webapp/WEB-INF/web.xml b/spring-jpa/src/main/webapp/WEB-INF/web.xml index 2eb6e88c31..b526774179 100644 --- a/spring-jpa/src/main/webapp/WEB-INF/web.xml +++ b/spring-jpa/src/main/webapp/WEB-INF/web.xml @@ -6,7 +6,8 @@ Spring MVC Application - + + mvc-dispatcher From 6a25a24eaebb08e792d52c945ca9216216f7d95d Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 4 Sep 2016 20:44:10 +0300 Subject: [PATCH 18/68] fix issues after merge --- .../.settings/org.eclipse.wst.common.project.facet.core.xml | 5 +++-- spring-jpa/pom.xml | 2 +- .../baeldung/custom/config/PersistenceDerbyJPAConfig.java | 2 ++ .../main/java/org/baeldung/user/service/MyUserService.java | 3 +-- spring-jpa/src/main/resources/persistence-derby.properties | 4 +++- .../src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml | 4 +++- 6 files changed, 13 insertions(+), 7 deletions(-) diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml index a8a65de481..5f3c0f7702 100644 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,7 +1,8 @@ - + - + + diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 9d497774ca..71dd3df270 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -268,7 +268,7 @@ - 4.0.4.RELEASE + 4.1.3.RELEASE 4.3.2.RELEASE 3.20.0-GA diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java index 812709111d..6be7053b78 100644 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -75,6 +75,8 @@ public class PersistenceDerbyJPAConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } diff --git a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java index 866ac88f29..edbb1651a3 100644 --- a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java +++ b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java @@ -1,13 +1,12 @@ package org.baeldung.user.service; -import javax.transaction.Transactional; - import org.baeldung.persistence.model.MyUser; import org.baeldung.user.dao.MyUserDAO; import org.baeldung.web.MyUserDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service @Transactional diff --git a/spring-jpa/src/main/resources/persistence-derby.properties b/spring-jpa/src/main/resources/persistence-derby.properties index 2e2dee983b..e808fdc288 100644 --- a/spring-jpa/src/main/resources/persistence-derby.properties +++ b/spring-jpa/src/main/resources/persistence-derby.properties @@ -7,4 +7,6 @@ jdbc.pass=tutorialpass # hibernate.X hibernate.dialect=org.hibernate.dialect.DerbyDialect hibernate.show_sql=false -hibernate.hbm2ddl.auto=create \ No newline at end of file +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml index 47082453b9..25d1d4d22f 100644 --- a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -5,7 +5,7 @@ xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" - xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd + xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd @@ -65,6 +65,8 @@ ${hibernate.hbm2ddl.auto} ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} From 6b7b8be33309ecc101fcff0dfae4a4f7412c8059 Mon Sep 17 00:00:00 2001 From: anton-k11 Date: Tue, 6 Sep 2016 08:56:29 +0300 Subject: [PATCH 19/68] Comment out the new project until Java 9 is available on the build server. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cbe3055dbe..60f33c4e2a 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ apache-fop core-java core-java-8 - core-java-9 + couchbase-sdk-intro couchbase-sdk-spring-service From 657d1a507f25b8e7f1163c76e109735002843315 Mon Sep 17 00:00:00 2001 From: Kiran Date: Tue, 6 Sep 2016 21:16:06 -0400 Subject: [PATCH 20/68] Add files via upload --- spring-mvc-tiles/pom.xml | 99 +++++++++++++++++++ .../springmvc/ApplicationConfiguration.java | 47 +++++++++ .../springmvc/ApplicationController.java | 27 +++++ .../springmvc/ApplicationInitializer.java | 22 +++++ .../WEB-INF/views/pages/apachetiles.jsp | 12 +++ .../main/webapp/WEB-INF/views/pages/home.jsp | 12 +++ .../webapp/WEB-INF/views/pages/springmvc.jsp | 12 +++ .../views/tiles/layouts/defaultLayout.jsp | 25 +++++ .../views/tiles/templates/defaultFooter.jsp | 2 + .../views/tiles/templates/defaultHeader.jsp | 3 + .../views/tiles/templates/defaultMenu.jsp | 8 ++ .../main/webapp/WEB-INF/views/tiles/tiles.xml | 34 +++++++ .../src/main/webapp/static/css/app.css | 36 +++++++ 13 files changed, 339 insertions(+) create mode 100644 spring-mvc-tiles/pom.xml create mode 100644 spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java create mode 100644 spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java create mode 100644 spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp create mode 100644 spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml create mode 100644 spring-mvc-tiles/src/main/webapp/static/css/app.css diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml new file mode 100644 index 0000000000..abbb9a2870 --- /dev/null +++ b/spring-mvc-tiles/pom.xml @@ -0,0 +1,99 @@ + + 4.0.0 + com.baeldung + spring-mvc-tiles + 0.0.1-SNAPSHOT + war + spring-mvc-tiles + Integrating Spring MVC with Apache Tiles + + + 4.3.2.RELEASE + 3.0.5 + + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.tiles + tiles-core + ${apachetiles.version} + + + org.apache.tiles + tiles-api + ${apachetiles.version} + + + org.apache.tiles + tiles-servlet + ${apachetiles.version} + + + org.apache.tiles + tiles-jsp + ${apachetiles.version} + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-mvc-tiles + false + + + + + spring-mvc-tiles + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java new file mode 100644 index 0000000000..1ae6d1b23c --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java @@ -0,0 +1,47 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") +public class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java new file mode 100644 index 0000000000..b85ad54587 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java @@ -0,0 +1,27 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + + +@Controller +@RequestMapping("/") +public class ApplicationController { + + @RequestMapping(value = { "/"}, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles"}, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc"}, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java new file mode 100644 index 0000000000..ababe0ae07 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java @@ -0,0 +1,22 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { ApplicationConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp new file mode 100644 index 0000000000..9936957c04 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

Tiles with Spring MVC Demo

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp new file mode 100644 index 0000000000..b501d4968e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

Welcome to Apache Tiles integration with Spring MVC

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp new file mode 100644 index 0000000000..209b1004de --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

Spring MVC configured to work with Apache Tiles

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp new file mode 100644 index 0000000000..9b727473f9 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
+ + +
+ +
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp new file mode 100644 index 0000000000..3849cc5230 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -0,0 +1,2 @@ + +
copyright © Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp new file mode 100644 index 0000000000..8a878c857d --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -0,0 +1,3 @@ +
+

Welcome to Spring MVC integration with Apache Tiles

+
\ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp new file mode 100644 index 0000000000..fdfbdc8a14 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml new file mode 100644 index 0000000000..789fbd809a --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-tiles/src/main/webapp/static/css/app.css new file mode 100644 index 0000000000..9976e5406e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/static/css/app.css @@ -0,0 +1,36 @@ +.flex-container { + display: -webkit-flex; + display: flex; + -webkit-flex-flow: row wrap; + flex-flow: row wrap; + text-align: center; +} + +.flex-container > * { + padding: 15px; + -webkit-flex: 1 100%; + flex: 1 100%; +} + +.article { + text-align: left; +} + +header {background: black;color:white;} +footer {background: #aaa;color:white;} +.nav {background:#eee;} + +.nav ul { + list-style-type: none; + padding: 0; +} + +.nav ul a { + text-decoration: none; +} + +@media all and (min-width: 768px) { + .nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;} + .article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;} + footer {-webkit-order:3;order:3;} +} \ No newline at end of file From 739502694fd0192a24581762e999b1ad31ea3358 Mon Sep 17 00:00:00 2001 From: maverick Date: Wed, 7 Sep 2016 09:30:34 +0530 Subject: [PATCH 21/68] md5 changes --- core-java/pom.xml | 341 +++++++++--------- .../org/baeldung/java/md5/JavaMD5Test.java | 90 +++++ 2 files changed, 265 insertions(+), 166 deletions(-) create mode 100644 core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java diff --git a/core-java/pom.xml b/core-java/pom.xml index bc533607e7..802436e606 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,205 +1,214 @@ - - 4.0.0 - com.baeldung - core-java - 0.1.0-SNAPSHOT + + 4.0.0 + com.baeldung + core-java + 0.1.0-SNAPSHOT - core-java + core-java - + - - - net.sourceforge.collections - collections-generic - 4.01 - - - com.google.guava - guava - ${guava.version} - + + + net.sourceforge.collections + collections-generic + 4.01 + + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-math3 - 3.3 - + + org.apache.commons + commons-math3 + 3.3 + - + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.assertj - assertj-core - ${assertj.version} - test - + + org.assertj + assertj-core + ${assertj.version} + test + - - org.testng - testng - ${testng.version} - test - + + org.testng + testng + ${testng.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - + + + commons-codec + commons-codec + 1.10 + - - core-java - - - src/main/resources - true - - - + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + + core-java + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - + - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + - - - 4.3.11.Final - 5.1.38 + - - 2.7.2 +
- - 1.7.13 - 1.1.3 + + + 4.3.11.Final + 5.1.38 - - 5.1.3.Final + + 2.7.2 - - 19.0 - 3.4 + + 1.7.13 + 1.1.3 - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 + + 5.1.3.Final - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + 4.4.1 + 4.5 - + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + +
\ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java new file mode 100644 index 0000000000..83f1fb33b6 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java @@ -0,0 +1,90 @@ +package org.baeldung.java.md5; + +import static org.junit.Assert.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +import java.io.File; +import java.io.IOException; +import java.nio.*; +import static org.assertj.core.api.Assertions.assertThat; + + +public class JavaMD5Test { + + + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + + + @Test + public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(password.getBytes()); + byte[] digest = md.digest(); + String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myHash.equals(hash)).isTrue(); + } + + @Test + public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter + .printHexBinary(digest).toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + @Test + public void givenPassword_whenHashingUsingCommons_thenVerifying() { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + String md5Hex = DigestUtils + .md5Hex(password).toUpperCase(); + + assertThat(md5Hex.equals(hash)).isTrue(); + } + + + @Test + public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + HashCode hash = com.google.common.io.Files + .hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString() + .toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + +} From 2da3ca4e7cf6a131bbbc47fa826b99970a983e08 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 13 Sep 2016 23:20:44 +0300 Subject: [PATCH 22/68] update MyUser and User constructor --- .../baeldung/persistence/model/MyUser.java | 26 ------------------- .../security/MyUserDetailsService.java | 3 ++- .../baeldung/user/service/MyUserService.java | 2 -- .../main/java/org/baeldung/web/MyUserDto.java | 14 +--------- .../main/webapp/WEB-INF/views/register.jsp | 1 - 5 files changed, 3 insertions(+), 43 deletions(-) diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java index 0a097f2782..804d391641 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java +++ b/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -15,16 +15,12 @@ public class MyUser { @GeneratedValue(strategy = GenerationType.AUTO) private int id; - private String name; - @Column(unique = true, nullable = false) private String username; @Column(nullable = false) private String password; - private boolean enabled; - public MyUser() { } @@ -36,14 +32,6 @@ public class MyUser { this.id = id; } - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - public String getUsername() { return username; } @@ -59,18 +47,4 @@ public class MyUser { public void setPassword(final String password) { this.password = password; } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(final boolean enabled) { - this.enabled = enabled; - } - - @Override - public String toString() { - return "MyUser [name=" + name + ", username=" + username + ", password=" + password + ", enabled=" + enabled + "]"; - } - } diff --git a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java index 21e3985bac..4c02f53d20 100644 --- a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -8,6 +8,7 @@ import org.baeldung.user.dao.MyUserDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; @@ -29,7 +30,7 @@ public class MyUserDetailsService implements UserDetailsService { else { final Collection authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); - return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities); + return new User(user.getUsername(), user.getPassword(), authorities); } } diff --git a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java index edbb1651a3..f4705f3193 100644 --- a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java +++ b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java @@ -26,8 +26,6 @@ public class MyUserService { user.setUsername(accountDto.getUsername()); user.setPassword(passwordEncoder.encode(accountDto.getPassword())); - user.setName(accountDto.getName()); - user.setEnabled(true); return myUserDAO.save(user); } diff --git a/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java b/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java index ec95ec43bf..c572208913 100644 --- a/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java +++ b/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java @@ -8,10 +8,6 @@ public class MyUserDto { @Size(min = 1) private String username; - @NotNull - @Size(min = 1) - private String name; - private String password; public String getUsername() { @@ -21,15 +17,7 @@ public class MyUserDto { public void setUsername(final String username) { this.username = username; } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - + public String getPassword() { return password; } diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp index 68b3ac14b0..e6e9d373a0 100644 --- a/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp +++ b/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp @@ -16,7 +16,6 @@ Register here:

Username:
Password:
-Name:

From 678d99b6e5f33535b781b31612ac9f5cd2a7d493 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 14 Sep 2016 21:52:09 +0300 Subject: [PATCH 23/68] custom userservice new project --- spring-userservice/.springBeans | 15 + spring-userservice/pom.xml | 310 ++++++++++++++++++ .../org/baeldung/custom/config/MvcConfig.java | 42 +++ .../config/PersistenceDerbyJPAConfig.java | 89 +++++ .../custom/config/SecSecurityConfig.java | 75 +++++ .../baeldung/persistence/model/MyUser.java | 50 +++ .../security/MyUserDetailsService.java | 37 +++ .../org/baeldung/security/UserController.java | 52 +++ .../java/org/baeldung/user/dao/MyUserDAO.java | 40 +++ .../baeldung/user/service/MyUserService.java | 45 +++ .../main/java/org/baeldung/web/MyUserDto.java | 29 ++ .../resources/persistence-derby.properties | 12 + .../src/main/webapp/META-INF/MANIFEST.MF | 3 + .../webapp/WEB-INF/mvc-dispatcher-servlet.xml | 88 +++++ .../src/main/webapp/WEB-INF/views/index.jsp | 35 ++ .../src/main/webapp/WEB-INF/views/login.jsp | 29 ++ .../main/webapp/WEB-INF/views/register.jsp | 23 ++ .../src/main/webapp/WEB-INF/web.xml | 51 +++ 18 files changed, 1025 insertions(+) create mode 100644 spring-userservice/.springBeans create mode 100644 spring-userservice/pom.xml create mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java create mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java create mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java create mode 100644 spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java create mode 100644 spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java create mode 100644 spring-userservice/src/main/java/org/baeldung/security/UserController.java create mode 100644 spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java create mode 100644 spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java create mode 100644 spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java create mode 100644 spring-userservice/src/main/resources/persistence-derby.properties create mode 100644 spring-userservice/src/main/webapp/META-INF/MANIFEST.MF create mode 100644 spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml create mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/index.jsp create mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/login.jsp create mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/register.jsp create mode 100644 spring-userservice/src/main/webapp/WEB-INF/web.xml diff --git a/spring-userservice/.springBeans b/spring-userservice/.springBeans new file mode 100644 index 0000000000..ff32b84d3b --- /dev/null +++ b/spring-userservice/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml new file mode 100644 index 0000000000..5edaf15d9b --- /dev/null +++ b/spring-userservice/pom.xml @@ -0,0 +1,310 @@ + + 4.0.0 + spring-userservice + spring-userservice + 0.0.1-SNAPSHOT + war + + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + org.hibernate + hibernate-ehcache + ${hibernate.version} + + + xml-apis + xml-apis + 1.4.01 + + + org.javassist + javassist + ${javassist.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + runtime + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + com.h2database + h2 + ${h2.version} + + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + 2.2.5 + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + javax.servlet + servlet-api + 3.0-alpha-1 + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + + + + spring-userservice + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + + 4.1.3.RELEASE + 4.3.2.RELEASE + 3.20.0-GA + + + 5.2.2.Final + 5.1.38 + 1.10.2.RELEASE + 1.4.192 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + + + + + \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java new file mode 100644 index 0000000000..4a9e737a92 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.custom.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/"); + registry.addViewController("/index"); + registry.addViewController("/login"); + registry.addViewController("/register"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java new file mode 100644 index 0000000000..6be7053b78 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -0,0 +1,89 @@ +package org.baeldung.custom.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceDerbyJPAConfig { + + @Autowired + private Environment env; + + public PersistenceDerbyJPAConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public MyUserDAO myUserDAO() { + final MyUserDAO myUserDAO = new MyUserDAO(); + return myUserDAO; + } +} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java new file mode 100644 index 0000000000..44df02980f --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.custom.config; + +import org.baeldung.security.MyUserDetailsService; +import org.baeldung.user.service.MyUserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.authenticationProvider(authenticationProvider()); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/*").permitAll() + .and() + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .defaultSuccessUrl("/",true) + .failureUrl("/login?error=true") + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/"); + // @formatter:on + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(myUserDetailsService()); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public MyUserDetailsService myUserDetailsService() { + return new MyUserDetailsService(); + } + + @Bean + public MyUserService myUserService() { + return new MyUserService(); + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java new file mode 100644 index 0000000000..804d391641 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -0,0 +1,50 @@ +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; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_custom_user_service") +public class MyUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + public MyUser() { + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..4c02f53d20 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,37 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Collection; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service("userDetailsService") +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + MyUserDAO myUserDAO; + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final MyUser user = myUserDAO.findByUsername(username); + + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + username); + } + else { + final Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority("ROLE_USER")); + return new User(user.getUsername(), user.getPassword(), authorities); + } + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java new file mode 100644 index 0000000000..b1c96e72c0 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/UserController.java @@ -0,0 +1,52 @@ +package org.baeldung.security; + +import javax.annotation.Resource; + +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class UserController { + + @Resource + MyUserService myUserService; + + @RequestMapping(value = "/register", method = RequestMethod.POST) + public String registerUserAccount(final MyUserDto accountDto, final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + try { + myUserService.registerNewUserAccount(accountDto); + model.addAttribute("message", "Registration successful"); + return "index"; + } + catch(final Exception exc){ + model.addAttribute("message", "Registration failed"); + + return "index"; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHomepage(final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + return "index"; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String getRegister() { + return "register"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String getLogin() { + return "login"; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java new file mode 100644 index 0000000000..5741d19bf2 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -0,0 +1,40 @@ +package org.baeldung.user.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.MyUser; +import org.springframework.stereotype.Repository; + +@Repository +public class MyUserDAO { + + @PersistenceContext + private EntityManager entityManager; + + public MyUser findByUsername(final String username) { + final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); + query.setParameter("username", username); + final List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public MyUser save(final MyUser user) { + entityManager.persist(user); + return user; + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(final EntityManager entityManager) { + this.entityManager = entityManager; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java new file mode 100644 index 0000000000..f4705f3193 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -0,0 +1,45 @@ +package org.baeldung.user.service; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.baeldung.web.MyUserDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class MyUserService { + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + MyUserDAO myUserDAO; + + public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { + if (usernameExists(accountDto.getUsername())) { + throw new Exception("There is an account with that username: " + accountDto.getUsername()); + } + final MyUser user = new MyUser(); + + user.setUsername(accountDto.getUsername()); + user.setPassword(passwordEncoder.encode(accountDto.getPassword())); + return myUserDAO.save(user); + } + + public MyUser getUserByUsername(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + return user; + } + + private boolean usernameExists(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + if (user != null) { + return true; + } + return false; + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java new file mode 100644 index 0000000000..c572208913 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java @@ -0,0 +1,29 @@ +package org.baeldung.web; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class MyUserDto { + @NotNull + @Size(min = 1) + private String username; + + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + +} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-userservice/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml new file mode 100644 index 0000000000..25d1d4d22f --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} + + + + + + + + + + + + + + + + + + + diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000000..0c89257cd2 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + +Welcome! + + + + + + + +Register +

+ +Login + +

+${message } +

+ +Hello, ${name }! +
+
+Logout +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..29431f426d --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,29 @@ +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + + +

Login

+ +
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ Username or password invalid! + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp new file mode 100644 index 0000000000..e6e9d373a0 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Welcome! + + + + + +Register here:

+
+Username:
+Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b526774179 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + Spring MVC Application + + + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + index.jsp + + + \ No newline at end of file From 4b7e5066d88a43307616b4e2eb01446af027a2da Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 14 Sep 2016 22:10:29 +0300 Subject: [PATCH 24/68] clean up spring-jpa --- ....eclipse.wst.common.project.facet.core.xml | 2 +- spring-jpa/.springBeans | 1 - spring-jpa/pom.xml | 81 ----------------- .../org/baeldung/custom/config/MvcConfig.java | 42 --------- .../config/PersistenceDerbyJPAConfig.java | 89 ------------------- .../custom/config/SecSecurityConfig.java | 75 ---------------- .../baeldung/persistence/model/MyUser.java | 50 ----------- .../security/MyUserDetailsService.java | 37 -------- .../org/baeldung/security/UserController.java | 52 ----------- .../java/org/baeldung/user/dao/MyUserDAO.java | 40 --------- .../baeldung/user/service/MyUserService.java | 45 ---------- .../main/java/org/baeldung/web/MyUserDto.java | 29 ------ .../resources/persistence-derby.properties | 12 --- .../webapp/WEB-INF/mvc-dispatcher-servlet.xml | 88 ------------------ .../src/main/webapp/WEB-INF/views/index.jsp | 35 -------- .../src/main/webapp/WEB-INF/views/login.jsp | 29 ------ .../main/webapp/WEB-INF/views/register.jsp | 23 ----- spring-jpa/src/main/webapp/WEB-INF/web.xml | 51 ----------- 18 files changed, 1 insertion(+), 780 deletions(-) delete mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/security/UserController.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java delete mode 100644 spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java delete mode 100644 spring-jpa/src/main/resources/persistence-derby.properties delete mode 100644 spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml delete mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/index.jsp delete mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/login.jsp delete mode 100644 spring-jpa/src/main/webapp/WEB-INF/views/register.jsp delete mode 100644 spring-jpa/src/main/webapp/WEB-INF/web.xml diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml index 5f3c0f7702..24342c1b93 100644 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-jpa/.springBeans b/spring-jpa/.springBeans index 85bcd37cff..ff32b84d3b 100644 --- a/spring-jpa/.springBeans +++ b/spring-jpa/.springBeans @@ -7,7 +7,6 @@ - src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 71dd3df270..5acdae7765 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -6,7 +6,6 @@ 0.1-SNAPSHOT spring-jpa - war @@ -126,78 +125,6 @@ test - - org.springframework - spring-core - ${org.springframework.version} - - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - - javax.servlet - servlet-api - 3.0-alpha-1 - - - org.springframework.security - spring-security-core - ${org.springframework.security.version} - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - - org.apache.derby - derby - 10.12.1.1 - - - org.apache.derby - derbyclient - 10.12.1.1 - - - org.apache.derby - derbynet - 10.12.1.1 - - - org.apache.derby - derbytools - 10.12.1.1 - - - taglibs - standard - 1.1.2 - - - org.springframework.security - spring-security-taglibs - 4.1.3.RELEASE - - - javax.servlet.jsp.jstl - jstl-api - 1.2 - @@ -221,12 +148,6 @@ - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - org.apache.maven.plugins maven-surefire-plugin @@ -268,7 +189,6 @@ - 4.1.3.RELEASE 4.3.2.RELEASE 3.20.0-GA @@ -301,7 +221,6 @@ 3.5.1 - 2.6 2.19.1 2.7 1.4.18 diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java deleted file mode 100644 index 4a9e737a92..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.custom.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = { "org.baeldung.security" }) -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/"); - registry.addViewController("/index"); - registry.addViewController("/login"); - registry.addViewController("/register"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java deleted file mode 100644 index 6be7053b78..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.custom.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-derby.properties" }) -public class PersistenceDerbyJPAConfig { - - @Autowired - private Environment env; - - public PersistenceDerbyJPAConfig() { - super(); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean myEmf() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - - @Bean - public MyUserDAO myUserDAO() { - final MyUserDAO myUserDAO = new MyUserDAO(); - return myUserDAO; - } -} \ No newline at end of file diff --git a/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java deleted file mode 100644 index 44df02980f..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.custom.config; - -import org.baeldung.security.MyUserDetailsService; -import org.baeldung.user.service.MyUserService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -@EnableWebSecurity -@Profile("!https") -public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - - public SecSecurityConfig() { - super(); - } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.authenticationProvider(authenticationProvider()); - // @formatter:on - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/*").permitAll() - .and() - .formLogin() - .loginPage("/login") - .loginProcessingUrl("/login") - .defaultSuccessUrl("/",true) - .failureUrl("/login?error=true") - .and() - .logout() - .logoutUrl("/logout") - .deleteCookies("JSESSIONID") - .logoutSuccessUrl("/"); - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(myUserDetailsService()); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - - @Bean - public MyUserDetailsService myUserDetailsService() { - return new MyUserDetailsService(); - } - - @Bean - public MyUserService myUserService() { - return new MyUserService(); - } -} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java deleted file mode 100644 index 804d391641..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/persistence/model/MyUser.java +++ /dev/null @@ -1,50 +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; -import javax.persistence.Table; - -@Entity -@Table(schema = "spring_custom_user_service") -public class MyUser { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(unique = true, nullable = false) - private String username; - - @Column(nullable = false) - private String password; - - public MyUser() { - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } -} diff --git a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java deleted file mode 100644 index 4c02f53d20..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.baeldung.security; - -import java.util.ArrayList; -import java.util.Collection; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service("userDetailsService") -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - MyUserDAO myUserDAO; - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - final MyUser user = myUserDAO.findByUsername(username); - - if (user == null) { - throw new UsernameNotFoundException("No user found with username: " + username); - } - else { - final Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority("ROLE_USER")); - return new User(user.getUsername(), user.getPassword(), authorities); - } - } - -} diff --git a/spring-jpa/src/main/java/org/baeldung/security/UserController.java b/spring-jpa/src/main/java/org/baeldung/security/UserController.java deleted file mode 100644 index b1c96e72c0..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/security/UserController.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.baeldung.security; - -import javax.annotation.Resource; - -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -public class UserController { - - @Resource - MyUserService myUserService; - - @RequestMapping(value = "/register", method = RequestMethod.POST) - public String registerUserAccount(final MyUserDto accountDto, final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - try { - myUserService.registerNewUserAccount(accountDto); - model.addAttribute("message", "Registration successful"); - return "index"; - } - catch(final Exception exc){ - model.addAttribute("message", "Registration failed"); - - return "index"; - } - } - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String getHomepage(final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - return "index"; - } - - @RequestMapping(value = "/register", method = RequestMethod.GET) - public String getRegister() { - return "register"; - } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String getLogin() { - return "login"; - } -} diff --git a/spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java deleted file mode 100644 index 5741d19bf2..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/user/dao/MyUserDAO.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.user.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.baeldung.persistence.model.MyUser; -import org.springframework.stereotype.Repository; - -@Repository -public class MyUserDAO { - - @PersistenceContext - private EntityManager entityManager; - - public MyUser findByUsername(final String username) { - final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); - query.setParameter("username", username); - final List result = query.getResultList(); - if (result != null && result.size() > 0) { - return result.get(0); - } else - return null; - } - - public MyUser save(final MyUser user) { - entityManager.persist(user); - return user; - } - - public EntityManager getEntityManager() { - return entityManager; - } - - public void setEntityManager(final EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java deleted file mode 100644 index f4705f3193..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/user/service/MyUserService.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.user.service; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.baeldung.web.MyUserDto; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class MyUserService { - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - MyUserDAO myUserDAO; - - public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { - if (usernameExists(accountDto.getUsername())) { - throw new Exception("There is an account with that username: " + accountDto.getUsername()); - } - final MyUser user = new MyUser(); - - user.setUsername(accountDto.getUsername()); - user.setPassword(passwordEncoder.encode(accountDto.getPassword())); - return myUserDAO.save(user); - } - - public MyUser getUserByUsername(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - return user; - } - - private boolean usernameExists(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - if (user != null) { - return true; - } - return false; - } - -} diff --git a/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java b/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java deleted file mode 100644 index c572208913..0000000000 --- a/spring-jpa/src/main/java/org/baeldung/web/MyUserDto.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -public class MyUserDto { - @NotNull - @Size(min = 1) - private String username; - - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - -} diff --git a/spring-jpa/src/main/resources/persistence-derby.properties b/spring-jpa/src/main/resources/persistence-derby.properties deleted file mode 100644 index e808fdc288..0000000000 --- a/spring-jpa/src/main/resources/persistence-derby.properties +++ /dev/null @@ -1,12 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver -jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true -jdbc.user=tutorialuser -jdbc.pass=tutorialpass - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.DerbyDialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml deleted file mode 100644 index 25d1d4d22f..0000000000 --- a/spring-jpa/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /WEB-INF/views/ - - - .jsp - - - - - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} - - - - - - - - - - - - - - - - - - - diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp deleted file mode 100644 index 0c89257cd2..0000000000 --- a/spring-jpa/src/main/webapp/WEB-INF/views/index.jsp +++ /dev/null @@ -1,35 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - - -Welcome! - - - - - - - -Register -

- -Login - -

-${message } -

- -Hello, ${name }! -
-
-Logout -
- - - \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp deleted file mode 100644 index 29431f426d..0000000000 --- a/spring-jpa/src/main/webapp/WEB-INF/views/login.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - - -

Login

- -
- - - - - - - - - - - - - -
User:
Password:
- -
- Username or password invalid! - - \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp deleted file mode 100644 index e6e9d373a0..0000000000 --- a/spring-jpa/src/main/webapp/WEB-INF/views/register.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - -Welcome! - - - - - -Register here:

-
-Username:
-Password:
- -
- - - \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/web.xml b/spring-jpa/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b526774179..0000000000 --- a/spring-jpa/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - Spring MVC Application - - - - - - mvc-dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc-dispatcher - / - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - index.jsp - - - \ No newline at end of file From ef54cd43cbaa2b938aa3595fb415dab933503812 Mon Sep 17 00:00:00 2001 From: sanketmeghani Date: Sun, 18 Sep 2016 17:05:52 +0530 Subject: [PATCH 25/68] Add sample code to get current date in Java 8 --- .../com/baeldung/util/GetCurrentDate.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java new file mode 100644 index 0000000000..7bbf8b48bb --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java @@ -0,0 +1,20 @@ +package com.baeldung.util; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; + +public class GetCurrentDate { + + public static void main(String args[]) { + + LocalDate localDate = LocalDate.now(); + System.out.println("Today's date is: " + localDate); + + localDate = LocalDate.now(ZoneId.of("GMT+02:30")); + System.out.println("Current date in GMT +02:30 timezone: " + localDate); + + LocalDateTime localDateTime = LocalDateTime.now(); + System.out.println("Today's date is: " + localDateTime.toLocalDate()); + } +} From ba4fb5bf42c062bcd38b51e6e2d4625337894f41 Mon Sep 17 00:00:00 2001 From: sanketmeghani Date: Sun, 18 Sep 2016 17:06:12 +0530 Subject: [PATCH 26/68] Add sample code to get current time in Java 8 --- .../com/baeldung/util/GetCurrentTime.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java new file mode 100644 index 0000000000..39934c94bf --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java @@ -0,0 +1,20 @@ +package com.baeldung.util; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; + +public class GetCurrentTime { + + public static void main(String args[]) { + + LocalTime localTime = LocalTime.now(); + System.out.println("Current time is: " + localTime); + + localTime = LocalTime.now(ZoneId.of("GMT+02:30")); + System.out.println("Current time in GMT +02:30 timezone: " + localTime); + + LocalDateTime localDateTime = LocalDateTime.now(); + System.out.println("Current time is: " + localDateTime.toLocalTime()); + } +} From 1b4714c214236ae4d7a8a25bdfce3feff74e0932 Mon Sep 17 00:00:00 2001 From: sanketmeghani Date: Sun, 18 Sep 2016 17:06:34 +0530 Subject: [PATCH 27/68] Add sample code to get current timestamp in Java 8 --- .../com/baeldung/util/GetCurrentTimestamp.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java new file mode 100644 index 0000000000..2387a721cf --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java @@ -0,0 +1,14 @@ +package com.baeldung.util; + +import java.time.Instant; + +public class GetCurrentTimestamp { + + public static void main(String args[]) { + + Instant instant = Instant.now(); + System.out.println("Current timestamp is: " + instant.toEpochMilli()); + + System.out.println("Number of seconds: " + instant.getEpochSecond()); + } +} From f1cfc706df085310b50fcd3df1f9690e34d8257c Mon Sep 17 00:00:00 2001 From: anton-k11 Date: Tue, 20 Sep 2016 17:59:43 +0300 Subject: [PATCH 28/68] Adding Optional 2 Stream and Set.of examples. --- .../baeldung/java9/OptionalToStreamTest.java | 21 +++++++++++++++ .../com/baeldung/java9/SetExamplesTest.java | 27 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java 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..966c03fe17 --- /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..c534ba9d47 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java @@ -0,0 +1,27 @@ +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); + } +} From a497c42f90b4fb2898a55dab34d30cf5467935c5 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 20 Sep 2016 13:03:27 -0400 Subject: [PATCH 29/68] readme file --- spring-userservice/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 spring-userservice/README.md diff --git a/spring-userservice/README.md b/spring-userservice/README.md new file mode 100644 index 0000000000..097afc5fc1 --- /dev/null +++ b/spring-userservice/README.md @@ -0,0 +1 @@ +spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file From be6939bd97e23f7bda3c9c540dd61a5824e7347f Mon Sep 17 00:00:00 2001 From: anton-k11 Date: Thu, 22 Sep 2016 00:04:53 +0300 Subject: [PATCH 30/68] Removing comments, reformatting. --- core-java-9/pom.xml | 11 +---------- .../baeldung/java9/MultiResultionImageTest.java | 1 - .../com/baeldung/java9/OptionalToStreamTest.java | 12 ++++++------ .../java/com/baeldung/java9/SetExamplesTest.java | 15 +++++++-------- 4 files changed, 14 insertions(+), 25 deletions(-) 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 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/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java index d6c16b91bc..0805e06794 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 index 966c03fe17..56b4bb7b8c 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java @@ -7,15 +7,15 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; public class OptionalToStreamTest { - + @Test - public void testOptionalToStream(){ + public void testOptionalToStream() { Optional op = Optional.ofNullable("String value"); Stream strOptionalStream = op.stream(); - Stream filteredStream = strOptionalStream.filter( - (str) -> { return str != null && str.startsWith("String"); } - ); + 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 index c534ba9d47..0f8db83d9c 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java @@ -1,6 +1,5 @@ package com.baeldung.java9; - import java.util.Set; import org.junit.Test; @@ -9,18 +8,18 @@ import static org.junit.Assert.assertEquals; public class SetExamplesTest { @Test - public void testUnmutableSet(){ + public void testUnmutableSet() { Set strKeySet = Set.of("key1", "key2", "key3"); - try{ + try { strKeySet.add("newKey"); - }catch(UnsupportedOperationException uoe){ + } catch (UnsupportedOperationException uoe) { } - assertEquals(strKeySet.size(), 3); + assertEquals(strKeySet.size(), 3); } - + @Test - public void testArrayToSet(){ - Integer [] intArray = new Integer[]{1,2,3,4,5,6,7,8,9,0}; + 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); } From 51c438b469859fb4a6f357b3107f46ffcef002a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20R=C3=A4del?= Date: Sun, 25 Sep 2016 11:07:55 +0200 Subject: [PATCH 31/68] BAEL-305: Use release versions as dependencies. --- enterprise-patterns/front-controller-pattern/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml index dbcd4f1b1d..5fbe5730cb 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -31,7 +31,7 @@ org.eclipse.jetty jetty-maven-plugin - 9.4.0.M1 + 9.3.11.v20160721 /front-controller From 11292acceb5e3479b216121245ad2f4ce786c571 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sun, 25 Sep 2016 12:24:56 +0200 Subject: [PATCH 32/68] BAEL-657 - FrontController image resize --- .../src/main/resources/front controller.png | Bin 9492 -> 5338 bytes .../src/main/resources/front controller.puml | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) 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 bd475bf3f32a2a82cc0d5d31acc3e09344109f1f..af22a38e37c8735a0d2a0a05e4a774edbb2ab706 100644 GIT binary patch literal 5338 zcmYjVbyO726F<5`Q5peJx)h{AB?OKX>24&C?vj)|y2AqwIO>R#?oR1A5D%n0Kw9bJ z$M^gF=eKX)zJ2p%XWq=t?0jZpG}RT!i0O#|005b?lDrlGfMtKbUn0c0U!TbTqy+$Q z0Gg`W3U_yR7|geFfXJ`Ta&*`IoapH2SYBTK^5qLGB))pO9s+?>R8-ubg58hrC_Fse zo11Y00{pA1F>D-cYMO`h^VJU@Qmn5x?eBMohdUw=DHj(bq@=`>k^*nv3U6<>adENM z)g?7HriqI35)lzlP>^D-Zxj{9x3;!EeX?(EP9GX7LZdrQPWsu|nVFbqSXt@$_?`(0 za(wt8S6W)i!^4)D8L*TXj|9in*Vk8ls~sF1-0hy2oSeM=J9>LHuBBNZ?7|;=a8D}yH=XBx{5%dP{u%_^GQamzJIy@k~o!U$K!}FEG%0*fexCs|JazJv$q$U{QhdXm$au zDxJMYt=;3|+{Wypq0p!rNJdpvJRAV^F*Z>t`yX_##o9UVR2*{`OMGc{Fpa?(4V z|8csq@pohQ`t&aoJG+d`%X&uDN`Vj6Z;X9>%m;M*W`lF)!}HHj+w?39qH^NBY92+t zk-53S%?Y^+(O>rZrY`mlVN8m)wps&*&c%LFiHV*QPI0g~Ez*I(qI|bVdXL9nG6MIEG0l!QY*{GXKGhh z4=0g)l2Q#qx|MQv?Xsp_@@8;NH!m-yogZAA{Oytx|Q){bZ@87yy_LoClP ziUU;|gOYxf<|5`7-h9y3c6KTHoaCEV5C|!Ws;O&*R!t*1=6Z+okE8VffCuTy@^7_$ zm-q7t0w3u-8QSU6qIr^y%xKJAJp;g=MSSd!c=Rx3Ds{?In}vvo5*s47$#c*}?cS4U2fjfVaZ}es z+2=Pl+(A2`$$BP1`4pvELBKh!t6y?sJG=Sg)j2w@e)Cq{UwUq@uFbjU?GQj9^Qy${ zwSUZr5sEL##C}A(LZiSC$QJ%(VXOGghhZa^oHYSbqd~1K9jU)O*(%H!}z}lTK8# znRgVR4(nC=hnv|{A@0rcKVJ z15M}eP@ZgHkRB~O;FxDK+o|w$dQqj)J1xRrfR}~rNq+#fQx9!^$>`;Z;S4&<&kUht zce}{H_An{(87jBCQTVVh$k!v^?6in~%{AqYbt?>REq=%XYrC?l!j&cE>x>?jK@@Frin1* zdq@xo26H-I6P|w3uN&hZ)cqQbfQknNzh#?vF3#-GPA+NY@JO%rx+Fslj1qs$_O3N8~d5Puy5#W#`cgAl<&a3Rrm>7U1_s0T7{nQ!_GWI7A*rQF27 zwhzPGL3UKTSO@jlaR64_)LqgHA}X?M1;FF%b*4a6s}q|!`|)gOLQMB`V8G9t^_D2h zCQZh#)oerUJph*6-In3&Nc#-eP5~%2;fD#BaT-&%v2Bd-bKZn_HLe1V~YBCPg{prq*j~m32Z^(-U(o}gG6$V>u zfr(kxJgy1}l@B)5Owngm!T=nC-gfV$3x|{-N|CwVW<9_{-QT<{GV=y({PXNL&mNrf zHoWCCQ?xvCjBw;k1P)Z=(ewih?;{Jy0jw>i2%tqHj2w6P1LQNiJ9mbguXIVCIR{qVXD+{i{a zF=Ntx;M1jON8pu-%%?_;Ka&58pTG!N<*IGoX`FcP9dXjP4s-XMD#dfP8-~ zn^po{OK($WZ^nynjif(Q+}Qyrf(>`I#<~ZaCVg1rx}lNw7hA4m1Mjn&)6ty!7<6Vg+f!p+w;<9evz=m)Bq>oxq5t~abuF!|pt zVMs*M=`{`2m9Av6M;~jLWKA)j-Y2O?E7;f={rvWzgQ06)8-w2Kvj7F3rhnwN&(C1J zo%Do~b>sjm5XNZHU!Ep#y?|S>3Pd0}M0Xj=(_zJ?BXNWdS(uN7XKjHrp&)hP;NfPBF;1I{4Ts5E0Zu(pF zY-`O#?s>-N`!~DhK8HW!8Zm}_rVW0bn1CO;9KP0^KVj?nWoq~Mu1Z)UJB98{ zDbOQq2GFlBkJ)OaRa6yZ>Ye&l8H7CHYgty{XCv-HuO)DIeo8ui2*sX^eI6zmulu;8dzS~ijr zj#ME&)ojH$`ne&WQBP18`S5=-7?b04#EOYQ76A!t`M|$`_l)H;ScYS4ttnYqe5pDj z&{thnd#xFYY3wgv7*UbcbE)|_rC$PPn2cH-fa#^c4^Y_58C>ArId^{)3h-|cHz7f9 zZ#|FZ&?(c!iYV!$PDz5ReuGs3{Hxf5{7=Eh@=82vzeIhfLRn>w`aM@+tTG>XBWuK1I9IiO}Zr3>a$n3ouckjP%+Vt-S1yA@ySoJ zJ)k(4;I;kx0o2O$42P4)&WH6=rQEpD0k7*?wyUN`5a@5*hhk`736h=_{y9oXLSIJeBA{*3zu zQOULRBMzu<`&b7xN?!b~P9WXV$`f$T+%79jI($3w_ro>qC{(Gy4O`Fg4nzrE4lZ#9 zS*g90YrzEzu+AHvJP7{5e&8e-J}F5HJj`?XAz$I;hvPvfEV9VU)w8oHV))wME~ue= zifA=>`(^pUtE9DRkzHwjwierHp>|csf@FBdiaqQgGXK?lyfMP_mzn&w7 z+;P!_twEWEoOm^}=|{i3={-M zAdx%ftZ>B9xfHa?7TX5ZwpW>kpyj(X3un%W-fQ{c~yvP29+ zs0X^nK?nyooYID`@(BaHeAMX9_>(k*x5MG0&wPsn)AVRX!PPa3U!Rl7dA7L zZ8_(#rnw>*Sym2HynkRRYh_cza|0bVI9+8E+^b_$w2Z#aKUX_MRg2m0VqT-Qb6 zV#K^8Gik_<$IyoA@ae*KLj2V}+==uSIx|bZ6rowj;{UGa8)cJ!evb!Ng}wP)NeSqU zz0*N^p2hP|O4pt?#UVJGYHe_STDl2ySx)B^chf?1HgE}}mVN3_Fad*JQkopg?=_7} zmlMKCN+rpq4^KFyGemG_{wg7_zV{gcy;}WV=W3OEkDe=o4aw6H&@`}g&=-gK1X1*9 zNQc8%`;LzKr8@d}oi(K~?PNMSV{%?H+vrs#ixS4n`afFrY!^H;tNqVv*qV~K=L|d7 z{{eZ$QAnzY@+Er9+CfRx)XiD5gz=?)YFahH_O8IT-UdmJPxBk-zodI0Z`c3-K)$TNTY3O5eKf@bE36sz`oBs51bbWp zLHVRw#bbI(@hG(z+=wJvzeL*fN2W%3BZF;`Fl1HB&t9-f1BWh4=y=<|lKsRM6rn1h znbZAu;FGdzyHr>a4q)Xa%XcAWZr3Lt8E7W4H|NwQdK1XWZU2S)VfP}N=k@ah3Bc|o zR&f?4Gm*@q4dFZ+JHo!)OgHwYCD#&VUjA5AGi|+P<6%l-1iBcZcv*juz+SBA>tkfR zoZY7QQxnE5dg3o6eD}RUU>OZGT*f(zY6q3~&V>s#UdC8Jp5=M+f>)f?{UO7BLy$7O zNBG9Y!g{Vq9~M2paR|Kkol4W?uC#7a7)@fqoQl*KO*>iOWlj!OQvavvcfqy7;(+sT zz|-U*LJ-%#O@sgVpy{^fQQ7Y-`!gN%;;_OEi8aQi6Eh;+7P(+mc{wRUK`{3DJ-}*1 z>GEk|vJfgofnJF1zKVycaokH0;Nsx_nxQOhQ@j=g`bRy7N0rR=KW##0thYV*h%b+o zc6J@P-y7a-W`~SPrjaR@VUsEle)?hQ0d*)NPK?w$UuAKA5t#aJ45L-Sp&EKkLz2oO zP`lOjhq3!=uxsOp=Uw<^;LZ3&uX%GdSvEp>^r(FZyO(4(%nFP3pGfTMpy7+X4Yo<* zjg3@V)*8j*S*7+j)4wccG5AH6d>`zPwUFQ6yHpq~XbD_9IhFg3TLQk?H>V0G>!%1Q zRJ=;C?0;q=u{orR8!pk(Oo-P5lVg;)B+xGN{;dm)_C^;@L#FOZ*g2%+fYIbb0btbO zQPOc=rtA3=igxBfiVn_V5WL#J^rHm{9j*7|YZU+HJ5<-cPju*WYiTD|tHYtm+m+`Y z=du~&)Ja~oky1?8xdr68wzEzW3#CoAPAXQhdDe|d&hbf)Yqus}I2tvU4v(0hicg3> z{f8+>t-)SoqV&*t_FEYTgP$0I*CvSzE7%fMHLuz3F8YJTm1a?+nC`U!iP5lKK?pX- z(bUPho}k!ih6*k2FXNsF{UGXzixI;mS<~KLVnzzVCsINMfcOnDep9KyOgZ5V4o3?T zWNy;X_y}C`e|90yUgx+xJC#~p^UK*mckS3TAltLAFM_{S1U|0k_U4u>^fT9ssEX}q z=*X_)b)d%N8vnM78nZZ;G4yUHY41*B6~iC)c5Gf9ri)2Rc4E28b&-1Vg; kFnqn%b#ze{7|9R-7Q?j*$mNXc{`V1}te`GmBWoV^KLaV8sQ>@~ literal 9492 zcmZvCWn5I<7cPi^3Jih>5(Cm8-7$nncS}fjgVHdBq!L4Sr-XEOccTbHcMdIG_wc^& z|99_)`(@6VefC*<@3q%@*4ocH-<1?3v0f0pKte*ol9m!vK|(^d1ny^^Jpq36F9W@R z3%!%LrjxO~gS(BXnG=$vsh#N;Lnl*{w?^)7Eu5Sj_*qySYz*z3oNaBGjqPo5Souf* zDQ`T~G@bs}j)dfv8XhTP?f?E|;339+FyF4o=kQt1*yxW`b z{=!b+Qq?sN&)LgW9|=#oP~clH)6VRO-pJ@>aU9IVW7|kblz!4;B5H24`)OF3YEzAU4My(G8xw=Z zdTY4vf=Ibex0N{~qEtv?)i~P*i%GL#`5OZ#mr++ZSD#hcMzCY$UZR@4c|-E-nJ6bN z?$hDnSgF77+`oC??bD%;I6nM3f!mtf8@x}1bDa8QT&!sQ)Z(ZzD|5a3)AXn5eAezE zUx_X@D3q85Iq(BHgbwcoTqH}WAM_&dgNxFC|B?g1Tm&o{CIpRse{>o`% zj_pu%MB0Rv`X3t-!L-w5CH*khkAj4)@rX>Nf zXJ_~M^Ji&kX?J&bb@kUJUx8tF&4az+{4oQuadB}O8Q4&@j~^$A=wi)GB+qJYDZ0=t zf9c6@bJ4U;8B`o3&N#2P(wC)<&D=ST;7A%u4tK^?R8&ah;9UA%AW!@Md7s6J0V#dZ zi6yQO*&@t5C5&UWPA9i=H1bwiCCKm2HW5W|-_46(3mM1oqo>0b4qhT=Y7E5H)bNgw z4^d(gDl02#+UiSR9hpU@BMRcc3B@PT5-kOL0u+Wr9vm!I%3ZZs&lmiJ(pXQgr=a0g zqIFJ8GdN&y$@Jcehr#URI>EH_lSRzQ81OCvi5K@Se;Z0m1nQkehJ8v-_|}<$nNp+$ zok;|bg8w%{Vo{pZP2EXs|-t(ePVAxN>nr$}}&3MET%a{lbmZ zfzWOk&9qQIsM25L+RPkK5H!vF{em?~jpdj1-q=z~t~c)FkbV%_PD&bBJP6xKC?{6u z+Zc~rD&Lhz1nhumL9p@mA~ntt9Yp-MKSv0^N98)4MKLsLc6elDB>Qz7AC}6_KGrqK zetAw~WBGW2B9^=A!*=fF$B3mDZk`cv9_PiY2xBnC@_s$SAhOjRZn)UTW}S|T<0KjF z`<#cXf-b4mLfU&dKIE)qH1T!YvX}1C z7O)Fxuy7L%*ZH?CvQ?B>TW?N zBg1}*CImY{M)r@4_fbe-#5q ztVjuFlFdzrC0GXRcPwKH+u^bl@k1PB2j}HqMx!-j!xXE6z=9r5ql2?S0UhPFwsW3& z8e3x--fO)$z9_selQ_&_OI7C7>|4X`3Im{Kj{_Yv+<}2T<@X-y&EgmcR)6Emu**LE z@z*597$hGe(!^F2gXAfJ?Ugh}&tD4Zf#EZ0)9HrI{`LdQ6nfIAsHz%7J?|4!TAs`! zp@z)X+0%L{^ue&D%4C+ySs<+HU;7Nv`YK}1{6)75?Y~Bh(XGT(J0xCi{w9|n>;b54r?eO!`39a{v{{8b{9g?o?(JH zS0nc(=24XU-kEO2F);?q&#%`Ux9`GpJS<4NNK40XPk3SP_*=^|y>z|7?0jeEePdBJB-6m41BeP ziQH$ce$c1#HE6G$*M;)n2)KxC7FiJ#OTYnE93kPI7`y`myUOvZ|&wcAEGIR$eT4K{k8t=~GNUoQs2fuT`<={Fx}ClYBmsPea|g)0rLq{^`fW7d9BK7uXmP?=W&( z&eBP`qd}zew49umc?rETd}v*>Tj?0p`H&h*N5!0`?7xeVkrUqDcM;%UlwK>Htu@wL zrP^mjXz;HqVmkPhUHAy!nAG2VN)2Udu2h!0^KDLdEp?u{r+Q zYW4>VcV|Yso{H>;Yf316`Tm<%(?f@)x(UWu$d_r_RC7dG$Nuqp`=X6>~h_9Xj8aoJEWVx)d){}SFhGGXRm(lhQRq`o9K14-C4pA%u zqW1H=elTQC5`H``r){!a=-)=W1pyIcJk9FuKyp#iS6ACMM;I_N9wf5PU`aMhSd~$a zjWXtj$O|f^lXOpQ%CC!a0RDu8Fs>t!om_Mdp){zKIVvlYw9>KI6BOa#b7L^ZP?(mr zoC_486HG3&pytO@Q+r0m?`qj2n_^{MLJjaV)&Ms)S(QC5`e81qhT^y~k#pw|s7zSd z<%00t6yTX-wWvJ1n8+tnTo9(9a-AGvZdJ?2berZjv|K8Tfu09j4xvki#P%@Ge7yo+ z&#)Ai2j>w!y~gZycOt%OqX@tEU%B2^PFwF9OXXV>NRnB2h9*shLHi`Je-zfu%1r0a z)7epR^w8tELZrzH{&I+-=P%CXi$vv1n(K2-Phj!#=Cc?PnYul&2_a)FO!7FE%DAmF zFz}F_{2NuCY~N>7G2mL`zO&*hIHexz+8Rd-7b$vs)V^@|maFEDDNL`T5mI4usp zCt6l^15ppXs$$k9{Xh^6eKEntT0Q9Xl9%X29P2HTYS_^cPh>hjmsCCGwn5^ilr{CX z@sZB*t#LM+SEGA;fFX%nw7%$0i^^M_!uG+b;*3yEkJbXTMe2+RsnVyDEuNmARNvPG z1!MQUWs>ouPt4U+BTjO|SYxa;3vQP@I4z^{L?@(NEDk5iUn{)2mXcFn{(Lmgy3r%I z%c1Pt(#7NO)S!ahvh33JW()PQ4scHVp2|t#_%c^Ut&?a}yY5-m{J$s8s>5PphtbPV zwlg&-k$p%lsg#hs1Lz`#0Z5vh|H1uU>TrJ|r%FxF!ff;7glyht(nixE3SJf|Mtvd2 z{n-YU1u8RgrXt-(jjn3Q&V5^f1qOuG79a_!Uei@}YGq ztgvO=NVI%dOye8sWJgz!J0o@P6&Yoy5rkCg=@f)jNu@vpyr5P?IM+LKD=Mj|%!2$S z&`RG5B1#Tihu>^M8GAVB{P9wB|c5WccO@neeg2F zamlNV>0L+{?bxHcyGCrjj@W={%GYlph;|T;dqZTy z4~O$5j+=<-n!m5>!choW_fD$cp!3r%oFjN2KL0$pcx5#=PagFl$rx0bD#V2C794~Y z>K2^akMl`@mC=|^0v#XLQhkJ+++IvDVeO0Lg>Bl+j(#1tKG)aX?C*1oo9X+Mm3$M! z7uBOo(<8D?V;RNrl7=n7M4+6Js%$h4UJNUU??LL+QjW z{M;%_M>kq3ZTwMxI1(?aBEcrXvKf4dr}M?nMTs29Y^`>9ZX^S&xR>Qo-a_m+E>!oX zSFibtLnzPpdq9ruo+br^Wa51#$Gk`&AnO-&)81O9&=|x!t!tv*(rQ<~+TJP$y!ZYjSZYO3hEe|90-@;?+oU!0GwB{DcgZ(?3 z>s#0G=axounqMq;Xm`kbu3hSLo<5G@zXuLyOY=cMY|f3eFXO!uCzV`yCEHUFZz26K ziR96pH2S*q@S{1}(5=>s(;AzAjcqkaEcZ6f@<+5 zAlBu;m&gCFNpKCKVC}ih>bIwO77LAWZZjc8Avg4CHZy$o!+#pEJNuFa{DeGAQdiPx zPee6RVfX#w|K`}?=91d8G;c)(TA1i9byK)6zTMCei;3FaX1HG1=G znSMlcbW4f$g6--F)4SJn}cu+*YL`j>+GgB|+0abu#9 zsTczjzTaLkqy>T1^%K&x$y_&59K+`{WT+uJe&E$_MZ3E|Xn)_z+pch5;8Af)F7-8f zQki+QaZ$wO(cl^zB8YjQKms#4i3eoB*;~fx6eC96sp734L!@6!8Ws7$u?G9ees3Nu zcKXqnpvNH`6kHycNqCYN5ivcH!*5yQ)b6Wy#2CpkniT`ZV&jQ|zHEMB(tZ<3`kN+w zP}D_f0Ca$rvl9vCL;^O{!px)u)IahmezCWiMP#0BY`RmDNr*ig7tRISQR!2A8 z@r0q}b=3^mF(SOKaClS^pBnI@gPY4Ept=pOa*ScV=G)#i+Seky1%bT3Ok@)r6}ieKkO0a2i~BZj^cDLsL`T(UF@{tMpI1 znjyg&7jyJ$0Vul9!`D?2^Ap)3Oz(sQ^XscKNrka=U5pp!1wk#RCobPfNLDd_a_+2x*h+>7{j>QJDhmk%&y-us90yILuL3d9Niw$V&wQ z-sh<5O1`m(!&8b^Mg#4CQ7j3EcT~aL|5WT%{__Cw|2z=c(CQ1Dm^8JGUHYdF8(hT2 zp~WBV{o_gUANTDChJG|PwaPAK_{zMYcuL?l@ThBJrsJjVt4frD)%X_&hYo~oU4>mC z+!zy|eb6sl0TImB#<`o5afjG=FGik4{AT$?Q01^uipp>_Rr_ZdzL_B~Myk*Bcf@r> z@Vt<~*}kOW6PVFyi}}$|e0P{zpXdjabtUZD(9a3|zEWVjnB!L5M!Y*-kVs)^I>cKD zp5V8A2F!~W3G&6!QJzNC#>OTV%XIo@-6|>6>Z01+Gd;1@6M>*>k{Q;&C%u^oNc`?2 z8s{>C5jq)^DL&3@kycsBzUqq@r+|cnh8{BkEJ81lEeaeD=caFc9-GS50g^rs?8D)nhu>5 zr+-KB))RiLmy7bVLJ*`x%j}+_8xOdZDlL8ScJj^ccR?pp_LMQgSjoj{v-rcBcj_}B zQ=x*oF&-*mr=Bwg4LB1x9b5~-a!6|Vs-o+TbI|MEMkpNTrSXXnuf3o&jlZh_iPFmR zY$$K;m#6$a`JwE&T%TDmlPHRgnSDWO_)tKT@=2@S)WS=@LYYqcASAZgLYEfxC%lu5 zioW(LeTUf=Y2e!DSTo8bPD#4;#PIv7JqMnjgzNj%XN?~cYe~}YxvffdTC;f3AT}?F z%FB3H**!;kh5!nT{YJ6MOtaMXb4RPu2Cm$S%_&nTpo9*+T{lFgg({#QWUs^JjIG~u zWorIJE(so@!fu7z_A5saAYu=0(m?3s8O@C*PkhkjkUd7PIRj!;{S8dizm2gt9O?lebY69$9Y<_Hvwd>v|(1)@r zZ=1R%IZHJB_@O%^WJUHqCHmNtflr!}8%Mx2!^$;i%+V|>%R|-Ev z8Y81F1|kUv)2JbIBh31YGpRhLg;GNr@2hLm)aX?(pZOqzEQK|_w?m9WDQ7AHVT2pa z$4C-7>*w^n0?_J@G`p}*q%imc?0lqO=kCoSleZ7Yt>KVN4)~;{MlBW6Ec^i(ZbNTjB zPx^uTNRaAgJdZ8Er0EB0lZui7kW9?;P5Rz*MaZ4me#T&{>>26MCv8AmF=uo!lH>4t zIgQJTAFlbD?pvThMCR|q0iOzks=eFAu3t++fM#nUaFGT|zKVA**2*1O95uf^gMUfj zhl^M?-)cHgR4h0UG}qt>3-nl5L$RL$0yG(pxL9w~ze_ugWau|?;lywyBLlt5*X6ae zS&eHL^uO9Xz^M=SET01kGR(2-HCENJN)n}?X1+Bzc{aJMEMbB!p7W*RQq8DoMS%Zy zsg2|?b)GE}gAC~J{k5!OjOVF0I!j<=C)`>GdLZGV^b_}Q3^3WvO*-jP{f6XKF736t zXE9(r2!@AL(S_!sLQ!fr;heDU;VCtpNpPsl)U@d~xz46i91Fh9=CKhloOlrfOTKeP zyD5y{q-_Z^VKzk(5F0%&ZT}@H$F3t4)tfMafD%I2HV9;WH&9U>C{HjK#fMsFlDA^y z5FM$aR%TJ3<*e5qWjey9g41=|_ujkIHyT8Dn!?be0WT;eDJ$txpRLn$B>JVVy{K%+jh=`W{XrnOFEk3w zOuL#NS2m5<%(JMzRXYbS4>?W^fTpAU2#Zhi88_Jbz%r(z6WuOdY4?|ImHuC3TV=<% z+@D(B657Ei0;{GS%J_lcn9gmlZTSwFi=8y(i;+4W3o3kNm?ECf4W{>NFwTAyP?T52 z<-g6K^A6#$EdPb|CnP^SA~pb31v?G`1~cn=Dt(a4^Ejw8khjWr3ueBC2R7r4P#Kjq zh6=dHARJzIP?-XnEZyR&1I)zF6%GVoYJt;1vl9Th^sFkoq}Ku0xJaLy>_LHSuSS7E zEC5<1ta2qw>cUmJ!#^}{ngkmU0U)N&yfC_FV0_ir+J$Ku1%?S;Y}$c5rB@JKn1E0a z{ZSIz-_IjUdSBLN+W@FB?vF<}u;N6p-!Ka%By_^Q0BNGYv&S|*fje8~Gi#Any(&*& zY6`>ypuR}ey|rbgUwT{=e8!u{-<3>)QTlsURcRvLrc3023rm~7CCR$WfB+?B>Ei4; zZiS<}(Q{HGp<{odfN(NhWiiyJh^9O)Dad936#l3i<{?Y1aely`j`(N3{#O-HQ9o;{ zp2r(gHb2X-Xo%)YDCMlPwS-HJQk#VaVkcYYgy%*f+P8X}urm2ey?rv_ir86Eyme9Y zI1q(W{ZCO~MQ28!Xz&N98bt9HKQ|@SoWbpc=5m1NHDV%KH*AKLqkJPPY*RU z^~S~q5ZFx6YeXbIxYQSDZ6}m)B*|%MX(C z=oznm!ortj`K~K@ka9A36}BKeO=5UDGtFp(Um6x3&P5bnj)}?mM%`u%MD$&hSo&Ah z+Vz-t0}ioMIx>HT^7E=q!fbBZOHxcbFMPWE`Nm7Oy#1@i<$z%xu5_$kqm`I_d6@0 zxdCRgtWS;jX8%?a*oxXIYX~70RHKGe@&lk5vFs(hv_rA3j!S-<)%Z>7>?7K){7H75 z5I}ro*CgX|U^4ovrSF^PrPDM4_|#qOLMgm4@*5O@P9wqZ%nZ|8T}Tb548Gj7N6&lx zCRDK2_5bh9qOy%W0hHbJ)<5|JQN*f^u-~28*WtvH7WgB5Afo5+EF=8?$_VnL8TN_1 zjwk-4;Dt|(o=#VXd<G+go9(s$+!fp2@pX!o1wi*EHbWW#C z$cwbF$ye8EO3B&LF=jG>dBbVvBvN8VgmNM?YJDC0P2Xu+mkG$Yy>II~KnT|0ZS#>T z3!8-~Dox*%WX)JP{c0c+C{?q+MN=GuSz4yFUxtMIY;W%a4ghoY)AUn%HCBJi>KzQ1 zmOH#+g$MP3Wm}9(H9DUPxH+KXrf@TDPnQLQXQIX(!}!E}JdG8T&jgBQ&hKkO>liuk z4j0mhBUZ$x7^BbTel)CNKM^PH zl@4a$eml&~b?K9*r^&T`dYV!XHO|mR61J; zH;_En$sZp#*pV3l_#9!<1nKL$wLW3gSW>~Fm{b?MxhnI##In&;zWezGOseRZ>8`qJ z--_Mh@Pa9ZGCAOM`rh;A`dqKVs8$?nk7+zda_i?$Td6mg)`o)4x0-62x17H}Ucc@% z{PVv_{{1Kft|EubqtR_uFlkpS!ANTg=NZ>;tCYqys;!;R46oukdulAStFvS2Td0_v zYV4O31`lVBkwY(vT4%p$>$cu%fw_Lx`4+_#YU3Ki3XmAvSNDmG(8I-wC7$Tk?5e+4 zV(<*v@=D1#*xLG|_z7C&6+Z4}F^6wg`}BnO!j z13au9Yj1qx5;c$3ex<)ewmKy}Jsd;0N9Z&DT29Acp-t2IMOMhlbK*U&P@7*0S86W1 zzu#WvRus^c0#r~GS~)7@t2!o;vkv_fxwwq%vIbM;wN=dTA`vq-gZC_#1vI~cDk~#) zy$N~+kBtorlTCpcr$~HR=@gPPXDs#KpQ#Z3%e8^);n2^kcKj86js^O_Bzmm3ZleI_ zzTD}9xC@#nvzu!rLZ5?A6>mqw!bYSrc%yzd)m_9hg?7u5ljnR+ij9%jh$8|h@ce|n z2;y~Bt-?3Vf8bR+Qr$fzy__mfs@_nm>DxwYbM-T7*V#FrA2$kM_^)7pqbP_riGye2sK8I}aZBh;WfHa8n zwXWMGu}Z5ZgG6iF!}}|vniHA0`25RDw~pXg7A@JHqeWj|kxPa#(rTbGf zh3fvpPfitiv)`0)+okGXG<7En|HKy*sruI=1q303EKT5)xfp7ShK}O+@Y0r5NNC z_V|M8-qrWtF#-@MdUw8?x@AU;CSQAxKk#?05TM-F6+DvUH~24>e@XR&URTw7a|wHP zW0(zH%Gr+?JW1(4&*;q|{1-t*@1*FeKmT8rc;u~IpDLSIAVEk+0QZXDR?vi0KTJEK zqUSef-d=x8i=VK!R}{Tj@eEGvm*Hxk!_ibz!z2{i#|i(PGKGs!0yS;^CpTNklmzS- zc%%28W)H`W@vW=RY&1o^x90)IlQ}Ww5rF*(lK+8dPK;z!xCk|Ha7S0qLGadiGqw8f zYQ7`=Y{%g;E|oeZb?^@)1%p+?99Neqk0!Z>WnwiLdEzWW-^$iVRf%+VP1qOhZ85SuqnlF#x zagOjfP1xGQBAwqVZPH#XbE|0<__gF?0F-oYF5STVc+_8lKzAsEfA^+ya!pvisHpO+ z>bqXx0|dOexn$9%68PKWx@fD=UCsX@ zAi3a`3_FH<%%|oeEBwK}VT0{_Ak=5d}`gb3)w5bN^kj@Bo4_okyFpzwQCnXBkCyoAM42JFeAsW18f4A-Eu8irN3tvFciSv{ky%p?TBTzT7kVpiB5po31f<= z0C*g=bZ5E$T|Cg^tn>b{gK@_G$6zi}m8tbe;yhYL%?K=J1#`jC2atXPdDCdVoqhu; z7-?zC`Tr6&rfPlTX-&x~!0v8wVdb}5TEB}1p iQtAI8YewdtjD-9)PbP`>5Ac~2lC-#jSm_4?zyAY3;H{ Date: Sun, 25 Sep 2016 12:36:45 +0200 Subject: [PATCH 33/68] BAEL-305 - jetty version upgrade --- enterprise-patterns/front-controller-pattern/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml index d1868b81af..dbcd4f1b1d 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -31,11 +31,7 @@ org.eclipse.jetty jetty-maven-plugin -<<<<<<< HEAD - 9.3.11.v20160721 -======= 9.4.0.M1 ->>>>>>> upstream/master /front-controller From a351667adc59e55e31857dc69e7a4fd23eb9e602 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 25 Sep 2016 15:18:08 +0300 Subject: [PATCH 34/68] minor cleanup work --- spring-thymeleaf/pom.xml | 362 +++++++++--------- .../com/baeldung/thymeleaf/config/WebApp.java | 38 +- .../thymeleaf/config/WebMVCConfig.java | 80 ++-- .../thymeleaf/config/WebMVCSecurity.java | 10 +- .../controller/StudentController.java | 74 ++-- .../com/baeldung/thymeleaf/model/Student.java | 66 ++-- .../csrf/CsrfEnabledIntegrationTest.java | 12 +- 7 files changed, 318 insertions(+), 324 deletions(-) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 35d8c37176..f9493a9992 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,189 +1,189 @@ - 4.0.0 - com.baeldung - spring-thymeleaf - 0.1-SNAPSHOT - war - - 1.7 - - 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 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-thymeleaf + 0.1-SNAPSHOT + war + + 1.7 + + 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 - + + 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 - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - 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.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 + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + 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.springframework - spring-test - 4.1.3.RELEASE - test - + + org.springframework + spring-test + 4.1.3.RELEASE + test + - - - org.springframework.security - spring-security-test - 4.1.3.RELEASE - test - + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + - - - junit - junit - 4.12 - test - + + + junit + junit + 4.12 + test + - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-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 - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - 8082 - - - - - - + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-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 + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + + + 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 c7d5e33cb8..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, WebMVCSecurity.class, InitSecurity.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 50c9cf06fe..cdea671c84 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 @@ -24,51 +24,51 @@ import com.baeldung.thymeleaf.formatter.NameFormatter; */ public class WebMVCConfig extends WebMvcConfigurerAdapter { - @Bean - @Description("Thymeleaf Template Resolver") - public ServletContextTemplateResolver templateResolver() { - ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/views/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); + @Bean + @Description("Thymeleaf Template Resolver") + public ServletContextTemplateResolver templateResolver() { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } + return templateResolver; + } - @Bean - @Description("Thymeleaf Template Engine") - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); + @Bean + @Description("Thymeleaf Template Engine") + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); - return templateEngine; - } + return templateEngine; + } - @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + @Bean + @Description("Thymeleaf View Resolver") + public ThymeleafViewResolver viewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } - @Bean - @Description("Spring Message Resolver") - public ResourceBundleMessageSource messageSource() { - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } - @Override - @Description("Custom Conversion Service") - public void addFormatters(FormatterRegistry registry) { - registry.addFormatter(new NameFormatter()); - } + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } } 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 index 00c42831de..46bff38a3f 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -14,7 +14,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class WebMVCSecurity extends WebSecurityConfigurerAdapter { - + @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { @@ -37,13 +37,7 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .httpBasic() - ; + 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/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index bd70881dd8..46a28c3c74 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -30,17 +30,17 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class CsrfEnabledIntegrationTest { - - @Autowired + + @Autowired WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; - + @Autowired private Filter springSecurityFilterChain; - + protected RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } @@ -52,12 +52,12 @@ public class CsrfEnabledIntegrationTest { @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()); + 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()); + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); } } From 1e6083a13c4649ef463dd20a434f6470c0a3e9f9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 25 Sep 2016 15:19:09 +0300 Subject: [PATCH 35/68] minor cleanup work --- spring-thymeleaf/pom.xml | 44 +++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index f9493a9992..96508eb15e 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,26 +5,6 @@ spring-thymeleaf 0.1-SNAPSHOT war - - 1.7 - - 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 - @@ -68,7 +48,6 @@ ${org.thymeleaf-version} - org.slf4j slf4j-api @@ -135,6 +114,7 @@ + @@ -186,4 +166,26 @@ + + + 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 + + From eae09bb13a8ae70aecf237650f3ed82245efeebb Mon Sep 17 00:00:00 2001 From: maibin Date: Sun, 25 Sep 2016 22:45:22 +0200 Subject: [PATCH 36/68] Fixed both Thymeleaf and Interceptors articles (#699) * Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part * UserInterceptor (adding user information to model) * Spring Handler Interceptor - session timers * Spring Security CSRF attack protection with Thymeleaf * Fix and(); * Logger update * Changed config for Thymeleaf --- .../interceptor/SessionTimerInterceptor.java | 7 +- spring-thymeleaf/pom.xml | 53 ++++++----- .../thymeleaf/config/WebMVCConfig.java | 93 ++++++++++--------- .../thymeleaf/config/WebMVCSecurity.java | 8 +- 4 files changed, 87 insertions(+), 74 deletions(-) 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-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 96508eb15e..a13f1de4c7 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,10 +1,30 @@ - 4.0.0 - com.baeldung - spring-thymeleaf - 0.1-SNAPSHOT - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-thymeleaf + 0.1-SNAPSHOT + war + + 1.8 + + 4.3.3.RELEASE + 3.0.1 + + 1.7.12 + 1.1.3 + + 3.0.1.RELEASE + + 1.1.0.Final + 5.1.2.Final + + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + @@ -167,25 +187,4 @@
- - 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 - - 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 cdea671c84..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,17 +1,23 @@ package com.baeldung.thymeleaf.config; +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; @@ -22,53 +28,56 @@ import com.baeldung.thymeleaf.formatter.NameFormatter; * 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()); + @Bean + public ViewResolver viewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine()); + resolver.setCharacterEncoding("UTF-8"); + resolver.setOrder(1); + return resolver; + } - return templateEngine; - } + @Bean + public TemplateEngine templateEngine() { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setEnableSpringELCompiler(true); + engine.setTemplateResolver(templateResolver()); + return engine; + } - @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + 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 - @Description("Spring Message Resolver") - public ResourceBundleMessageSource messageSource() { - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } - @Override - @Description("Custom Conversion Service") - public void addFormatters(FormatterRegistry registry) { - registry.addFormatter(new NameFormatter()); - } + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } } 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 index 46bff38a3f..37844a2976 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -37,7 +37,13 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); + http + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .httpBasic() + ; } } From 52911fede4c93f1ae7ab2f561778df335149712c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Fern=C3=A1ndez=20Gonz=C3=A1lez?= Date: Mon, 26 Sep 2016 14:01:52 +0200 Subject: [PATCH 37/68] Remove module and try-catch (#701) * Add new module for mocks comparison. * Add sources for testing. * Changes on testCase. * Enter some tests for mockito. * More tests for Mockito. * Even more tests. * Add the rest of the mocking libraries. * Javadoc on test. * Test bare bones for EasyMock. * Fist kind of test and setup. * Add tests using EasyMock with a change on LoginService. * Create LoginControllerTest.java * Test setup * [JMockit] No method called test. * [JMockit] Two methods called test. * [JMockit] One method called test. * [JMockit] Exception mock test * [JMockit] Mocked object to pass around test. * [JMockit] Custom matcher test. * [JMockit] Partial mocking test. * [JMockit] Fix with IDE. * Not stubs. Mocks. MOCKS!!! * Remove unnecesary import. * Use correct encoding. Was having problems with buildings. * Remove failing module. * Create new module mocks and move mock-comparisons there. * Add jmockit module. * Add model class. * Add collaborator class. * Add performer class. * Add performer test. * Fix * Add interface for tests. * Test for any. * Test for with. * Test for null. * Test for times. * Test for arg that. * Test for result and returns. * Test for delegate. * Add verifications to any tests. * Add verifications to with test. * Add verification examples to methods using null. * Add verifications to methods using times. * Formatting. * Compress tests and fix one test. * Adding new article to readme. * [BAEL-178] Add collaborator for advanced article. * [BAEL-178] Add link to readme. * [BAEL-178] Add test for mockUp. * [BAEL-178] Add test for invoke method. * [BAEL-178] Add constructors and tests for mockup for constructors. * [BAEL-178] Add private fields and more test for deencapsulation. * [BAEL-178] Add inner class and test for instantiating inner classes. * [BAEL-178] Multimocks. * [BAEL-178] Add test for expectation reusing. * [BAEL-178] Move test class to tests folders. * Add postgresql dependency. * Add test and config with properties. * [BAEL-114] Add new project for JPA with JNDI. * [BAEL-114] Config without xml. * [BAEL-114] Bring part of Foo, FooServie and FooDao. * [BAEL-114] Show all foos. * [BAEL-114] Readme. * [BAEL-114] Undo changes on main jpa project. * [BAEL-114] Remove unnecesary dependencies. * [BAEL-114] Add tomcat config. * [BAEL-114] Fixes. * Add tests for Optional streams. * Add Java 9 version of the test. * Rename and move to new core-java-9 module. * Move contents from spring-jpa-jndi to spring-jpa and make necessary changes. * Do not use try-catch on configuration. --- spring-jpa-jndi/.gitignore | 13 -- spring-jpa-jndi/README.md | 7 - spring-jpa-jndi/pom.xml | 145 ------------------ .../org/baeldung/persistence/dao/FooDao.java | 22 --- .../org/baeldung/persistence/model/Foo.java | 34 ---- .../persistence/service/FooService.java | 22 --- .../src/main/resources/logback.xml | 20 --- spring-jpa/pom.xml | 33 ++++ .../config/PersistenceJNDIConfig.java | 10 +- .../org/baeldung/config/SpringWebConfig.java | 0 .../org/baeldung/config/WebInitializer.java | 0 .../java/org/baeldung/web/MainController.java | 0 .../src/main/resources/context.xml | 0 .../resources/persistence-jndi.properties | 0 .../src/main/resources/server.xml | 0 .../main/webapp/WEB-INF/views/jsp/index.jsp | 0 16 files changed, 36 insertions(+), 270 deletions(-) delete mode 100644 spring-jpa-jndi/.gitignore delete mode 100644 spring-jpa-jndi/README.md delete mode 100644 spring-jpa-jndi/pom.xml delete mode 100644 spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java delete mode 100644 spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java delete mode 100644 spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java delete mode 100644 spring-jpa-jndi/src/main/resources/logback.xml rename {spring-jpa-jndi => spring-jpa}/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java (90%) rename {spring-jpa-jndi => spring-jpa}/src/main/java/org/baeldung/config/SpringWebConfig.java (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/java/org/baeldung/config/WebInitializer.java (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/java/org/baeldung/web/MainController.java (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/resources/context.xml (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/resources/persistence-jndi.properties (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/resources/server.xml (100%) rename {spring-jpa-jndi => spring-jpa}/src/main/webapp/WEB-INF/views/jsp/index.jsp (100%) 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 - 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 From b576a4da400e98607648325c404800391cd23991 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 26 Sep 2016 14:50:24 +0200 Subject: [PATCH 38/68] Fixed pom.xml --- pom.xml | 1 - 1 file changed, 1 deletion(-) 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 From c774468720f6b849e26c0d9e2de6d81fee4c710a Mon Sep 17 00:00:00 2001 From: Slavisa Baeldung Date: Mon, 26 Sep 2016 17:17:07 +0200 Subject: [PATCH 39/68] NOJIRA - adding some glue text to README --- spring-cloud/README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 86f67cf26e..3e8cd21b82 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -1,8 +1,18 @@ ## The Module Holds Sources for the Following Articles - [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) -- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) + + Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. + + In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. + - [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) + + In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. + + Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. + - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) From d9f89bdad3b572d7e8c82aa93bdef96d95f3017e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 26 Sep 2016 20:55:17 -0400 Subject: [PATCH 40/68] removed extra files --- .../org.eclipse.wst.common.project.facet.core.xml | 8 -------- spring-jpa/.springBeans | 15 --------------- 2 files changed, 23 deletions(-) delete mode 100644 spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml delete mode 100644 spring-jpa/.springBeans diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 24342c1b93..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/spring-jpa/.springBeans b/spring-jpa/.springBeans deleted file mode 100644 index ff32b84d3b..0000000000 --- a/spring-jpa/.springBeans +++ /dev/null @@ -1,15 +0,0 @@ - - - 1 - - - - - - - - - - - - From 7aaae1d1433995ffd5a25a5d24d817a1bc072737 Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Mon, 26 Sep 2016 22:40:46 -0700 Subject: [PATCH 41/68] Moved project to core-java from eclipse folder (#703) --- .../equalshashcode/entities/ComplexClass.java | 65 +++++++++++++++++++ .../entities/PrimitiveClass.java | 0 .../equalshashcode/entities/Rectangle.java | 2 - .../equalshashcode/entities/Shape.java | 0 .../equalshashcode/entities/Square.java | 0 .../entities/ComplexClassTest.java | 5 +- .../entities/PrimitiveClassTest.java | 5 +- .../entities/SquareClassTest.java | 5 +- .../equalshashcode/entities/ComplexClass.java | 63 ------------------ 9 files changed, 71 insertions(+), 74 deletions(-) create mode 100644 core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java rename {eclipse => core-java}/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java (100%) rename {eclipse => core-java}/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java (96%) rename {eclipse => core-java}/src/main/java/org/baeldung/equalshashcode/entities/Shape.java (100%) rename {eclipse => core-java}/src/main/java/org/baeldung/equalshashcode/entities/Square.java (100%) rename {eclipse => core-java}/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java (90%) rename {eclipse => core-java}/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java (84%) rename {eclipse => core-java}/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java (84%) delete mode 100644 eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java 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/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; - } -} From e1d32226f370c190ce2ef3b379373a2cb79d8535 Mon Sep 17 00:00:00 2001 From: Catalin Date: Tue, 27 Sep 2016 12:24:47 +0300 Subject: [PATCH 42/68] Updated broken link --- spring-data-neo4j/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 ``` From 719d4e5aa1e1830c8d7403bdf64721ce376ac485 Mon Sep 17 00:00:00 2001 From: sanketmeghani Date: Tue, 27 Sep 2016 22:13:11 +0530 Subject: [PATCH 43/68] Converting date/time retrieval methods to JUnits --- .../com/baeldung/util/GetCurrentDate.java | 20 -------- .../com/baeldung/util/GetCurrentTime.java | 20 -------- .../baeldung/util/GetCurrentTimestamp.java | 14 ------ .../baeldung/util/CurrentDateTimeTest.java | 47 +++++++++++++++++++ 4 files changed, 47 insertions(+), 54 deletions(-) delete mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java delete mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java delete mode 100644 core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java create mode 100644 core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java deleted file mode 100644 index 7bbf8b48bb..0000000000 --- a/core-java-8/src/main/java/com/baeldung/util/GetCurrentDate.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.util; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; - -public class GetCurrentDate { - - public static void main(String args[]) { - - LocalDate localDate = LocalDate.now(); - System.out.println("Today's date is: " + localDate); - - localDate = LocalDate.now(ZoneId.of("GMT+02:30")); - System.out.println("Current date in GMT +02:30 timezone: " + localDate); - - LocalDateTime localDateTime = LocalDateTime.now(); - System.out.println("Today's date is: " + localDateTime.toLocalDate()); - } -} diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java deleted file mode 100644 index 39934c94bf..0000000000 --- a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTime.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.util; - -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.ZoneId; - -public class GetCurrentTime { - - public static void main(String args[]) { - - LocalTime localTime = LocalTime.now(); - System.out.println("Current time is: " + localTime); - - localTime = LocalTime.now(ZoneId.of("GMT+02:30")); - System.out.println("Current time in GMT +02:30 timezone: " + localTime); - - LocalDateTime localDateTime = LocalDateTime.now(); - System.out.println("Current time is: " + localDateTime.toLocalTime()); - } -} diff --git a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java b/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java deleted file mode 100644 index 2387a721cf..0000000000 --- a/core-java-8/src/main/java/com/baeldung/util/GetCurrentTimestamp.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.util; - -import java.time.Instant; - -public class GetCurrentTimestamp { - - public static void main(String args[]) { - - Instant instant = Instant.now(); - System.out.println("Current timestamp is: " + instant.toEpochMilli()); - - System.out.println("Number of seconds: " + instant.getEpochSecond()); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java new file mode 100644 index 0000000000..06d9394a5e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -0,0 +1,47 @@ +package com.baeldung.util; + +import static org.junit.Assert.assertEquals; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.GregorianCalendar; + +import org.junit.Test; + +public class CurrentDateTimeTest { + + @Test + public void shouldReturnCurrentDate() { + + final LocalDate now = LocalDate.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals("10-10-2010".length(), now.toString().length()); + assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); + assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR)); + } + + @Test + public void shouldReturnCurrentTime() { + + final LocalTime now = LocalTime.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); + } + + @Test + public void shouldReturnCurrentTimestamp() { + + final Instant now = Instant.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); + } +} From a24db3ac1e4214c67ce85637aa24e8048cca54eb Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 27 Sep 2016 20:45:42 -0400 Subject: [PATCH 44/68] add test for custom user details service --- .../java/org/baeldung/user/dao/MyUserDAO.java | 6 ++ .../baeldung/user/service/MyUserService.java | 10 ++++ .../CustomUserDetailsServiceTest.java | 59 +++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java index 5741d19bf2..4cc9f61b4a 100644 --- a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java +++ b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -29,6 +29,12 @@ public class MyUserDAO { entityManager.persist(user); return user; } + + public void removeUserByUsername(String username) { + final Query query = entityManager.createQuery("delete from MyUser where username=:username"); + query.setParameter("username", username); + query.executeUpdate(); + } public EntityManager getEntityManager() { return entityManager; diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java index f4705f3193..891d6863ce 100644 --- a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -1,5 +1,8 @@ package org.baeldung.user.service; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + import org.baeldung.persistence.model.MyUser; import org.baeldung.user.dao.MyUserDAO; import org.baeldung.web.MyUserDto; @@ -14,6 +17,9 @@ public class MyUserService { @Autowired private PasswordEncoder passwordEncoder; + + @PersistenceContext + private EntityManager entityManager; @Autowired MyUserDAO myUserDAO; @@ -33,6 +39,10 @@ public class MyUserService { final MyUser user = myUserDAO.findByUsername(username); return user; } + + public void removeUserByUsername(String username){ + myUserDAO.removeUserByUsername(username); + } private boolean usernameExists(final String username) { final MyUser user = myUserDAO.findByUsername(username); diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..29998b8fea --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java @@ -0,0 +1,59 @@ +package org.baeldung.userservice; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + + @Autowired + MyUserService myUserService; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Test + public void whenAuthenticateUser_thenRetrieveFromDb() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + myUserService.registerNewUserAccount(userDTO); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + + } catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } finally { + myUserService.removeUserByUsername(USERNAME); + } + } + +} From 9226fdc110579861bb201b3ff77e92db9e5d27c1 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 27 Sep 2016 20:48:05 -0400 Subject: [PATCH 45/68] remove unnecessary code --- .../main/java/org/baeldung/user/service/MyUserService.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java index 891d6863ce..1e05541998 100644 --- a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -1,8 +1,5 @@ package org.baeldung.user.service; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - import org.baeldung.persistence.model.MyUser; import org.baeldung.user.dao.MyUserDAO; import org.baeldung.web.MyUserDto; @@ -17,9 +14,6 @@ public class MyUserService { @Autowired private PasswordEncoder passwordEncoder; - - @PersistenceContext - private EntityManager entityManager; @Autowired MyUserDAO myUserDAO; From 4db012d57ba6b0f0309100ac8662af7bcad7a773 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Wed, 28 Sep 2016 09:51:08 +0600 Subject: [PATCH 46/68] Update README.md --- core-java-8/README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index e6bac2a4c9..c130e6bd41 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,4 +11,14 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) +- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) From d1bd04d2dce4bbf8b67d0f3f0ab4b0ac62c2c85a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 28 Sep 2016 16:22:31 +0200 Subject: [PATCH 47/68] Add example --- .../baeldung/java9/Java9OptionalsStreamTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 index 102ceda18f..b0684a94f8 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -42,6 +42,19 @@ public class Java9OptionalsStreamTest { assertEquals("bar", filteredList.get(1)); } + @Test + public void filterOutPresentOptionalsWithFlatMap2() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.map(Stream::of).orElseGet(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()); From ea85fa99eea7bd0611022e5c85f06f360969daf1 Mon Sep 17 00:00:00 2001 From: Sergey Petunin Date: Wed, 28 Sep 2016 19:24:03 +0500 Subject: [PATCH 48/68] Added samples for annotation processing article. (#705) * Added annotation processing examples. Fixed core-java8 build on OS X * Moved projects to separate submodule --- annotations/annotation-processing/pom.xml | 50 +++++++ .../processor/BuilderProcessor.java | 132 ++++++++++++++++++ .../annotation/processor/BuilderProperty.java | 8 ++ annotations/annotation-user/pom.xml | 51 +++++++ .../java/com/baeldung/annotation/Person.java | 29 ++++ .../annotation/PersonBuilderTest.java | 22 +++ annotations/pom.xml | 20 +++ core-java-8/pom.xml | 6 +- core-java-8/src/test/resources/.gitignore | 13 -- core-java-8/src/test/resources/test.txt | 1 + pom.xml | 1 + 11 files changed, 319 insertions(+), 14 deletions(-) create mode 100644 annotations/annotation-processing/pom.xml create mode 100644 annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java create mode 100644 annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java create mode 100644 annotations/annotation-user/pom.xml create mode 100644 annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java create mode 100644 annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java create mode 100644 annotations/pom.xml delete mode 100644 core-java-8/src/test/resources/.gitignore create mode 100644 core-java-8/src/test/resources/test.txt diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml new file mode 100644 index 0000000000..6d07394b87 --- /dev/null +++ b/annotations/annotation-processing/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + com.baeldung + 1.0.0-SNAPSHOT + annotations + ../ + + + annotation-processing + + + 1.0-rc2 + 3.5.1 + + + + + + com.google.auto.service + auto-service + ${auto-service.version} + provided + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java new file mode 100644 index 0000000000..0883e108e7 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -0,0 +1,132 @@ +package com.baeldung.annotation.processor; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ExecutableType; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.google.auto.service.AutoService; + +@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") +@SupportedSourceVersion(SourceVersion.RELEASE_8) +@AutoService(Processor.class) +public class BuilderProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + + Map> annotatedMethods = annotatedElements.stream() + .collect(Collectors.partitioningBy(element -> + ((ExecutableType) element.asType()).getParameterTypes().size() == 1 + && element.getSimpleName().toString().startsWith("set"))); + + List setters = annotatedMethods.get(true); + List otherMethods = annotatedMethods.get(false); + + otherMethods.forEach(element -> + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + + if (setters.isEmpty()) { + continue; + } + + String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); + + Map setterMap = setters.stream().collect(Collectors.toMap( + setter -> setter.getSimpleName().toString(), + setter -> ((ExecutableType) setter.asType()) + .getParameterTypes().get(0).toString() + )); + + try { + writeBuilderFile(className, setterMap); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return true; + } + + private void writeBuilderFile(String className, Map setterMap) throws IOException { + + String packageName = null; + int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + packageName = className.substring(0, lastDot); + } + + String simpleClassName = className.substring(lastDot + 1); + String builderClassName = className + "Builder"; + String builderSimpleClassName = builderClassName.substring(lastDot + 1); + + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); + try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { + + if (packageName != null) { + out.print("package "); + out.print(packageName); + out.println(";"); + out.println(); + } + + out.print("public class "); + out.print(builderSimpleClassName); + out.println(" {"); + out.println(); + + out.print(" private "); + out.print(simpleClassName); + out.print(" object = new "); + out.print(simpleClassName); + out.println("();"); + out.println(); + + out.print(" public "); + out.print(simpleClassName); + out.println(" build() {"); + out.println(" return object;"); + out.println(" }"); + out.println(); + + setterMap.entrySet().forEach(setter -> { + String methodName = setter.getKey(); + String argumentType = setter.getValue(); + + out.print(" public "); + out.print(builderSimpleClassName); + out.print(" "); + out.print(methodName); + + out.print("("); + + out.print(argumentType); + out.println(" value) {"); + out.print(" object."); + out.print(methodName); + out.println("(value);"); + out.println(" return this;"); + out.println(" }"); + out.println(); + }); + + out.println("}"); + + } + } + +} diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java new file mode 100644 index 0000000000..84fcc73850 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation.processor; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.SOURCE) +public @interface BuilderProperty { +} diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml new file mode 100644 index 0000000000..f76f691f93 --- /dev/null +++ b/annotations/annotation-user/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + + annotations + com.baeldung + 1.0.0-SNAPSHOT + ../ + + + annotation-user + + + + + com.baeldung + annotation-processing + ${project.parent.version} + + + + junit + junit + 4.12 + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java new file mode 100644 index 0000000000..23787ba4f4 --- /dev/null +++ b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java @@ -0,0 +1,29 @@ +package com.baeldung.annotation; + +import com.baeldung.annotation.processor.BuilderProperty; + +public class Person { + + private int age; + + private String name; + + public int getAge() { + return age; + } + + @BuilderProperty + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + @BuilderProperty + public void setName(String name) { + this.name = name; + } + +} diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java new file mode 100644 index 0000000000..72f9ac8bc7 --- /dev/null +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -0,0 +1,22 @@ +package com.baeldung.annotation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PersonBuilderTest { + + @Test + public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { + + Person person = new PersonBuilder() + .setAge(25) + .setName("John") + .build(); + + assertEquals(25, person.getAge()); + assertEquals("John", person.getName()); + + } + +} diff --git a/annotations/pom.xml b/annotations/pom.xml new file mode 100644 index 0000000000..f691674cf1 --- /dev/null +++ b/annotations/pom.xml @@ -0,0 +1,20 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + annotations + pom + + + annotation-processing + annotation-user + + + \ No newline at end of file diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 63df0e1b95..566eb4e43a 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,9 +1,10 @@ 4.0.0 + com.baeldung + 1.0.0-SNAPSHOT core-java8 - 0.1-SNAPSHOT core-java8 @@ -111,6 +112,9 @@ + + UTF-8 + 1.7.13 1.0.13 diff --git a/core-java-8/src/test/resources/.gitignore b/core-java-8/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-8/src/test/resources/.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/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt new file mode 100644 index 0000000000..652d70630f --- /dev/null +++ b/core-java-8/src/test/resources/test.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/pom.xml b/pom.xml index 33162777b7..37ed734567 100644 --- a/pom.xml +++ b/pom.xml @@ -132,6 +132,7 @@ wicket xstream java-cassandra + annotations From e5302d4e75f170b3e220b3bae6c9d0d4abe9193b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 28 Sep 2016 10:35:21 -0400 Subject: [PATCH 49/68] add failed authentication test --- .../CustomUserDetailsServiceTest.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java index 29998b8fea..6e1cd67e06 100644 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java @@ -9,9 +9,12 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.dao.DuplicateKeyException; import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.*; @@ -28,6 +31,7 @@ public class CustomUserDetailsServiceTest { public static final String USERNAME = "user"; public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; @Autowired MyUserService myUserService; @@ -36,7 +40,7 @@ public class CustomUserDetailsServiceTest { AuthenticationProvider authenticationProvider; @Test - public void whenAuthenticateUser_thenRetrieveFromDb() { + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { try { MyUserDto userDTO = new MyUserDto(); userDTO.setUsername(USERNAME); @@ -55,5 +59,27 @@ public class CustomUserDetailsServiceTest { myUserService.removeUserByUsername(USERNAME); } } + + @Test (expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + try { + myUserService.registerNewUserAccount(userDTO); + } + catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + } + finally { + myUserService.removeUserByUsername(USERNAME); + } + } } From e1ffd14c0d4434d1dec983a9a9772c2e9483a037 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 28 Sep 2016 19:46:18 +0200 Subject: [PATCH 50/68] Refactor JavaFolderSizeTest --- .../com/baeldung/java8/JavaFolderSizeTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index efd548a4b1..f2e7452137 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -21,7 +21,7 @@ public class JavaFolderSizeTest { @Before public void init() { final String separator = File.separator; - path = "src" + separator + "test" + separator + "resources"; + path = String.format("src%stest%sresources", separator, separator); } @Test @@ -79,7 +79,9 @@ public class JavaFolderSizeTest { final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length).sum(); assertEquals(expectedSize, size); } @@ -101,13 +103,11 @@ public class JavaFolderSizeTest { long length = 0; final File[] files = folder.listFiles(); - final int count = files.length; - - for (int i = 0; i < count; i++) { - if (files[i].isFile()) { - length += files[i].length(); + for (File file : files) { + if (file.isFile()) { + length += file.length(); } else { - length += getFolderSize(files[i]); + length += getFolderSize(file); } } return length; From 651c40778790d5f34d5a08318495934e1760dbbb Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:47:13 -0400 Subject: [PATCH 51/68] Added 'spring-mvc-tiles' module to parent pom.xml --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 82cf85208c..49d046e483 100644 --- a/pom.xml +++ b/pom.xml @@ -58,6 +58,7 @@ spring-mvc-java spring-mvc-no-xml spring-mvc-xml + spring-mvc-tiles spring-openid spring-protobuf spring-quartz From f6e5e17c9a7f302efec1ee2441a0f086a8535d3a Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:49:17 -0400 Subject: [PATCH 52/68] Updated indentation --- .../springmvc/ApplicationConfiguration.java | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java index 1ae6d1b23c..d2e90a4f53 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java @@ -15,33 +15,33 @@ import org.springframework.web.servlet.view.tiles3.TilesViewResolver; @ComponentScan(basePackages = "com.baeldung.tiles.springmvc") public class ApplicationConfiguration extends WebMvcConfigurerAdapter { - /** - * Configure TilesConfigurer. - */ - @Bean - public TilesConfigurer tilesConfigurer() { - TilesConfigurer tilesConfigurer = new TilesConfigurer(); - tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); - tilesConfigurer.setCheckRefresh(true); - return tilesConfigurer; - } + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } - /** - * Configure ViewResolvers to deliver views. - */ - @Override - public void configureViewResolvers(ViewResolverRegistry registry) { - TilesViewResolver viewResolver = new TilesViewResolver(); - registry.viewResolver(viewResolver); - } + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } - /** - * Configure ResourceHandlers to serve static resources - */ + /** + * Configure ResourceHandlers to serve static resources + */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/static/**").addResourceLocations("/static/"); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } } From 7f58390d53aba4b5472ebc5ba6b1ca4c033c8114 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:50:14 -0400 Subject: [PATCH 53/68] Updated indentation --- .../tiles/springmvc/ApplicationController.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java index b85ad54587..1a348d1c26 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java @@ -4,23 +4,22 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; - @Controller @RequestMapping("/") public class ApplicationController { - @RequestMapping(value = { "/"}, method = RequestMethod.GET) + @RequestMapping(value = { "/" }, method = RequestMethod.GET) public String homePage(ModelMap model) { return "home"; } - - @RequestMapping(value = { "/apachetiles"}, method = RequestMethod.GET) + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) public String productsPage(ModelMap model) { return "apachetiles"; } - - @RequestMapping(value = { "/springmvc"}, method = RequestMethod.GET) + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) public String contactUsPage(ModelMap model) { return "springmvc"; } From d9ae777b2e62e38eda6b04ecc414ebc3c57760f1 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:50:56 -0400 Subject: [PATCH 54/68] Updated indentation --- .../springmvc/ApplicationInitializer.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java index ababe0ae07..79583dbe83 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java @@ -4,19 +4,19 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - @Override - protected Class[] getRootConfigClasses() { - return new Class[] { ApplicationConfiguration.class }; - } + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { ApplicationConfiguration.class }; + } - @Override - protected Class[] getServletConfigClasses() { - return null; - } + @Override + protected Class[] getServletConfigClasses() { + return null; + } - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } } From 6b42940de807ea2fe361bd0519dc8359698951f2 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:51:55 -0400 Subject: [PATCH 55/68] Updated indentation --- spring-mvc-tiles/pom.xml | 184 ++++++++++++++++++--------------------- 1 file changed, 85 insertions(+), 99 deletions(-) diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml index abbb9a2870..1a72549e70 100644 --- a/spring-mvc-tiles/pom.xml +++ b/spring-mvc-tiles/pom.xml @@ -1,99 +1,85 @@ - - 4.0.0 - com.baeldung - spring-mvc-tiles - 0.0.1-SNAPSHOT - war - spring-mvc-tiles - Integrating Spring MVC with Apache Tiles - - - 4.3.2.RELEASE - 3.0.5 - - - - - - org.springframework - spring-core - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - - org.apache.tiles - tiles-core - ${apachetiles.version} - - - org.apache.tiles - tiles-api - ${apachetiles.version} - - - org.apache.tiles - tiles-servlet - ${apachetiles.version} - - - org.apache.tiles - tiles-jsp - ${apachetiles.version} - - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.1 - - - javax.servlet - jstl - 1.2 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - src/main/webapp - spring-mvc-tiles - false - - - - - spring-mvc-tiles - - \ No newline at end of file + + 4.0.0 + com.baeldung + spring-mvc-tiles + 0.0.1-SNAPSHOT + war + spring-mvc-tiles + Integrating Spring MVC with Apache Tiles + + + 4.3.2.RELEASE + 3.0.5 + + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.tiles + tiles-jsp + ${apachetiles.version} + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-mvc-tiles + false + + + + + spring-mvc-tiles + + From 0836270addbc959d6da1f2bfd144a17bdec41184 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:55:18 -0400 Subject: [PATCH 56/68] Updated indentation --- .../main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp index fdfbdc8a14..2c91eace85 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -1,8 +1,8 @@ \ No newline at end of file + From d98f232033638709ffa40446b77441e5d2fc1e13 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 28 Sep 2016 16:57:46 -0400 Subject: [PATCH 57/68] Updated indentation --- .../views/tiles/layouts/defaultLayout.jsp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp index 9b727473f9..2370ad4ab1 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -13,13 +13,13 @@ -
- - -
- -
- -
+
+ + +
+ +
+ +
- \ No newline at end of file + From 4a0233f49aee2ca0a74ca399fd2f00fe53f91bdd Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Wed, 28 Sep 2016 23:40:29 +0200 Subject: [PATCH 58/68] BAEL-314 - removing part 1 module --- .../application-config/discovery.properties | 0 .../application-config/gateway.properties | 0 .../application-config/resource.properties | 0 .../{part-1 => }/config/pom.xml | 0 .../integration/config/ConfigApplication.java | 0 .../src/main/resources/application.properties | 0 .../{part-1 => }/discovery/pom.xml | 0 .../discovery/DiscoveryApplication.java | 0 .../src/main/resources/bootstrap.properties | 0 .../{part-1 => }/gateway/pom.xml | 0 .../resource/GatewayApplication.java | 0 .../src/main/resources/bootstrap.properties | 0 .../spring-cloud-integration/part-1/pom.xml | 25 ------------------- spring-cloud/spring-cloud-integration/pom.xml | 18 ++++++++++--- .../{part-1 => }/resource/pom.xml | 0 .../resource/ResourceApplication.java | 0 .../src/main/resources/bootstrap.properties | 0 17 files changed, 14 insertions(+), 29 deletions(-) rename spring-cloud/spring-cloud-integration/{part-1 => }/application-config/discovery.properties (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/application-config/gateway.properties (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/application-config/resource.properties (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/config/pom.xml (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/config/src/main/resources/application.properties (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/discovery/pom.xml (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/discovery/src/main/resources/bootstrap.properties (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/gateway/pom.xml (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/gateway/src/main/resources/bootstrap.properties (100%) delete mode 100644 spring-cloud/spring-cloud-integration/part-1/pom.xml rename spring-cloud/spring-cloud-integration/{part-1 => }/resource/pom.xml (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java (100%) rename spring-cloud/spring-cloud-integration/{part-1 => }/resource/src/main/resources/bootstrap.properties (100%) diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties b/spring-cloud/spring-cloud-integration/application-config/discovery.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties rename to spring-cloud/spring-cloud-integration/application-config/discovery.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties b/spring-cloud/spring-cloud-integration/application-config/gateway.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties rename to spring-cloud/spring-cloud-integration/application-config/gateway.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties b/spring-cloud/spring-cloud-integration/application-config/resource.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties rename to spring-cloud/spring-cloud-integration/application-config/resource.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/config/pom.xml b/spring-cloud/spring-cloud-integration/config/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/pom.xml rename to spring-cloud/spring-cloud-integration/config/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-integration/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java rename to spring-cloud/spring-cloud-integration/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-integration/config/src/main/resources/application.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties rename to spring-cloud/spring-cloud-integration/config/src/main/resources/application.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml b/spring-cloud/spring-cloud-integration/discovery/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml rename to spring-cloud/spring-cloud-integration/discovery/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-integration/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java rename to spring-cloud/spring-cloud-integration/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/discovery/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-integration/discovery/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml b/spring-cloud/spring-cloud-integration/gateway/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml rename to spring-cloud/spring-cloud-integration/gateway/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-integration/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java rename to spring-cloud/spring-cloud-integration/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/gateway/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-integration/gateway/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/pom.xml b/spring-cloud/spring-cloud-integration/part-1/pom.xml deleted file mode 100644 index 770e26bca2..0000000000 --- a/spring-cloud/spring-cloud-integration/part-1/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - 4.0.0 - - - com.baeldung.spring.cloud - spring-cloud-integration - 1.0.0-SNAPSHOT - - - - config - discovery - gateway - resource - - - part-1 - 1.0.0-SNAPSHOT - pom - - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/pom.xml b/spring-cloud/spring-cloud-integration/pom.xml index 1d56995009..c14c277d7f 100644 --- a/spring-cloud/spring-cloud-integration/pom.xml +++ b/spring-cloud/spring-cloud-integration/pom.xml @@ -4,12 +4,22 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.spring.cloud + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + + + + config + discovery + gateway + resource + + + spring-cloud-integration 1.0.0-SNAPSHOT pom - - part-1 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/pom.xml b/spring-cloud/spring-cloud-integration/resource/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/pom.xml rename to spring-cloud/spring-cloud-integration/resource/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-integration/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java rename to spring-cloud/spring-cloud-integration/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/resource/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-integration/resource/src/main/resources/bootstrap.properties From f3b8bb0f146d8807e53953021a87943a07e2eb68 Mon Sep 17 00:00:00 2001 From: Egima profile Date: Thu, 29 Sep 2016 00:43:59 +0300 Subject: [PATCH 59/68] Moved regex from own module to core-java (#707) * made changes to java reflection * removed redundant method makeSound in Animal abstract class * added project for play-framework article * added project for regex * changed regex project from own model to core-java --- .../java/com/baeldung/java/regex/Result.java | 27 + .../com/baeldung/java/regex/RegexTest.java | 503 ++++++++++++++++++ 2 files changed, 530 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/regex/Result.java create mode 100644 core-java/src/test/java/com/baeldung/java/regex/RegexTest.java diff --git a/core-java/src/main/java/com/baeldung/java/regex/Result.java b/core-java/src/main/java/com/baeldung/java/regex/Result.java new file mode 100644 index 0000000000..d47c94ad2e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/regex/Result.java @@ -0,0 +1,27 @@ +package com.baeldung.java.regex; + +public class Result { + private boolean found = false; + private int count = 0; + + public Result() { + + } + + public boolean isFound() { + return found; + } + + public void setFound(boolean found) { + this.found = found; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java new file mode 100644 index 0000000000..257e486600 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java @@ -0,0 +1,503 @@ +package com.baeldung.java.regex; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class RegexTest { + private static Pattern pattern; + private static Matcher matcher; + + @Test + public void givenText_whenSimpleRegexMatches_thenCorrect() { + Result result = runTest("foo", "foo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + + } + + @Test + public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() { + Result result = runTest("foo", "foofoo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + + } + + @Test + public void givenText_whenMatchesWithDotMetach_thenCorrect() { + Result result = runTest(".", "foo"); + assertTrue(result.isFound()); + } + + @Test + public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() { + Result result = runTest("foo.", "foofoo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenORSet_whenMatchesAny_thenCorrect() { + Result result = runTest("[abc]", "b"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenORSet_whenMatchesAnyAndAll_thenCorrect() { + Result result = runTest("[abc]", "cab"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenORSet_whenMatchesAllCombinations_thenCorrect() { + Result result = runTest("[bcr]at", "bat cat rat"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenNORSet_whenMatchesNon_thenCorrect() { + Result result = runTest("[^abc]", "g"); + assertTrue(result.isFound()); + } + + @Test + public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() { + Result result = runTest("[^bcr]at", "sat mat eat"); + assertTrue(result.isFound()); + } + + @Test + public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() { + Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() { + Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 26); + } + + @Test + public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() { + Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 28); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect() { + Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect2() { + Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenTwoSets_whenMatchesUnion_thenCorrect() { + Result result = runTest("[1-3[7-9]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 6); + } + + @Test + public void givenTwoSets_whenMatchesIntersection_thenCorrect() { + Result result = runTest("[1-6&&[3-9]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 4); + } + + @Test + public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() { + Result result = runTest("[0-9&&[^2468]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 5); + } + + @Test + public void givenDigits_whenMatches_thenCorrect() { + Result result = runTest("\\d", "123"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenNonDigits_whenMatches_thenCorrect() { + Result result = runTest("\\D", "a6c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenWhiteSpace_whenMatches_thenCorrect() { + Result result = runTest("\\s", "a c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenNonWhiteSpace_whenMatches_thenCorrect() { + Result result = runTest("\\S", "a c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenWordCharacter_whenMatches_thenCorrect() { + Result result = runTest("\\w", "hi!"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenNonWordCharacter_whenMatches_thenCorrect() { + Result result = runTest("\\W", "hi!"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a?", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{0,1}", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a*", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{0,}", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a+", "hi"); + assertFalse(result.isFound()); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{1,}", "hi"); + assertFalse(result.isFound()); + } + + @Test + public void givenBraceQuantifier_whenMatches_thenCorrect() { + Result result = runTest("a{3}", "aaaaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() { + Result result = runTest("a{3}", "aa"); + assertFalse(result.isFound()); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() { + Result result = runTest("a{2,3}", "aaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() { + Result result = runTest("a{2,3}?", "aaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect() { + Result result = runTest("(\\d\\d)", "12"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect2() { + Result result = runTest("(\\d\\d)", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect3() { + Result result = runTest("(\\d\\d)(\\d\\d)", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() { + Result result = runTest("(\\d\\d)\\1", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() { + Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() { + Result result = runTest("(\\d\\d)\\1", "1213"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtBeginning_thenCorrect() { + Result result = runTest("^dog", "dogs are friendly"); + assertTrue(result.isFound()); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() { + Result result = runTest("^dog", "are dogs are friendly?"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtEnd_thenCorrect() { + Result result = runTest("dog$", "Man's best friend is a dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() { + Result result = runTest("dog$", "is a dog man's best friend?"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect() { + Result result = runTest("\\bdog\\b", "a dog is friendly"); + assertTrue(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect2() { + Result result = runTest("\\bdog\\b", "dog is man's best friend"); + assertTrue(result.isFound()); + } + + @Test + public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() { + Result result = runTest("\\bdog\\b", "snoop dogg is a rapper"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() { + Result result = runTest("\\bdog\\B", "snoop dogg is a rapper"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() { + Result result = runTest("\u00E9", "\u0065\u0301"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() { + Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() { + Result result = runTest("dog", "This is a Dog"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + Result result = runTest("(?i)dog", "This is a Dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() { + Result result = runTest("dog$ #check for word dog at end of text", "This is a dog"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() { + Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() { + Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(?s)(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text", Pattern.LITERAL); + assertFalse(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() { + Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() { + Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() { + Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertTrue(result.isFound()); + } + + @Test + public void givenMatch_whenGetsIndices_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("This dog is mine"); + matcher.find(); + assertEquals(5, matcher.start()); + assertEquals(8, matcher.end()); + } + + @Test + public void whenStudyMethodsWork_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are friendly"); + assertTrue(matcher.lookingAt()); + assertFalse(matcher.matches()); + + } + + @Test + public void whenMatchesStudyMethodWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dog"); + assertTrue(matcher.matches()); + + } + + @Test + public void whenReplaceFirstWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceFirst("cat"); + assertEquals("cats are domestic animals, dogs are friendly", newStr); + + } + + @Test + public void whenReplaceAllWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceAll("cat"); + assertEquals("cats are domestic animals, cats are friendly", newStr); + + } + + public synchronized static Result runTest(String regex, String text) { + pattern = Pattern.compile(regex); + matcher = pattern.matcher(text); + Result result = new Result(); + while (matcher.find()) + result.setCount(result.getCount() + 1); + if (result.getCount() > 0) + result.setFound(true); + return result; + } + + public synchronized static Result runTest(String regex, String text, int flags) { + pattern = Pattern.compile(regex, flags); + matcher = pattern.matcher(text); + Result result = new Result(); + while (matcher.find()) + result.setCount(result.getCount() + 1); + if (result.getCount() > 0) + result.setFound(true); + return result; + } +} From 25ea6ef7eeedad91acb7e452c7b19fe60c9c5380 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Thu, 29 Sep 2016 00:12:05 +0200 Subject: [PATCH 60/68] BAEL-314 - renaming module --- spring-cloud/pom.xml | 2 +- .../application-config/discovery.properties | 0 .../application-config/gateway.properties | 0 .../application-config/resource.properties | 0 .../config/pom.xml | 0 .../spring/cloud/integration/config/ConfigApplication.java | 0 .../config/src/main/resources/application.properties | 0 .../discovery/pom.xml | 0 .../cloud/integration/discovery/DiscoveryApplication.java | 0 .../discovery/src/main/resources/bootstrap.properties | 0 .../gateway/pom.xml | 0 .../spring/cloud/integration/resource/GatewayApplication.java | 0 .../gateway/src/main/resources/bootstrap.properties | 0 .../pom.xml | 0 .../resource/pom.xml | 0 .../spring/cloud/integration/resource/ResourceApplication.java | 0 .../resource/src/main/resources/bootstrap.properties | 0 17 files changed, 1 insertion(+), 1 deletion(-) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/application-config/discovery.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/application-config/gateway.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/application-config/resource.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/config/pom.xml (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/config/src/main/resources/application.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/discovery/pom.xml (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/discovery/src/main/resources/bootstrap.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/gateway/pom.xml (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/gateway/src/main/resources/bootstrap.properties (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/pom.xml (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/resource/pom.xml (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java (100%) rename spring-cloud/{spring-cloud-integration => spring-cloud-bootstrap}/resource/src/main/resources/bootstrap.properties (100%) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 340923cbdf..2349613def 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -10,7 +10,7 @@ spring-cloud-config spring-cloud-eureka spring-cloud-hystrix - spring-cloud-integration + spring-cloud-bootstrap pom diff --git a/spring-cloud/spring-cloud-integration/application-config/discovery.properties b/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/application-config/discovery.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties diff --git a/spring-cloud/spring-cloud-integration/application-config/gateway.properties b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/application-config/gateway.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties diff --git a/spring-cloud/spring-cloud-integration/application-config/resource.properties b/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/application-config/resource.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/resource.properties diff --git a/spring-cloud/spring-cloud-integration/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/config/pom.xml rename to spring-cloud/spring-cloud-bootstrap/config/pom.xml diff --git a/spring-cloud/spring-cloud-integration/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java rename to spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java diff --git a/spring-cloud/spring-cloud-integration/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/config/src/main/resources/application.properties rename to spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties diff --git a/spring-cloud/spring-cloud-integration/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/discovery/pom.xml rename to spring-cloud/spring-cloud-bootstrap/discovery/pom.xml diff --git a/spring-cloud/spring-cloud-integration/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java rename to spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java diff --git a/spring-cloud/spring-cloud-integration/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/discovery/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/gateway/pom.xml rename to spring-cloud/spring-cloud-bootstrap/gateway/pom.xml diff --git a/spring-cloud/spring-cloud-integration/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java rename to spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java diff --git a/spring-cloud/spring-cloud-integration/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/gateway/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/pom.xml rename to spring-cloud/spring-cloud-bootstrap/pom.xml diff --git a/spring-cloud/spring-cloud-integration/resource/pom.xml b/spring-cloud/spring-cloud-bootstrap/resource/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/resource/pom.xml rename to spring-cloud/spring-cloud-bootstrap/resource/pom.xml diff --git a/spring-cloud/spring-cloud-integration/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java rename to spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java diff --git a/spring-cloud/spring-cloud-integration/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/resource/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties From e0d9cd41a2e0fae80d6be324767f295517ba8fac Mon Sep 17 00:00:00 2001 From: maverick Date: Thu, 29 Sep 2016 14:57:30 +0530 Subject: [PATCH 61/68] Changes in pom.xml as suggested to remove formating changes in pom.xml commit. --- core-java/pom.xml | 347 +++++++++++++++++++++++----------------------- 1 file changed, 172 insertions(+), 175 deletions(-) diff --git a/core-java/pom.xml b/core-java/pom.xml index 802436e606..bce97d1148 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,214 +1,211 @@ - - 4.0.0 - com.baeldung - core-java - 0.1.0-SNAPSHOT + + 4.0.0 + com.baeldung + core-java + 0.1.0-SNAPSHOT - core-java + core-java - + - - - net.sourceforge.collections - collections-generic - 4.01 - - - com.google.guava - guava - ${guava.version} - + + + net.sourceforge.collections + collections-generic + 4.01 + + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-math3 - 3.3 - + + org.apache.commons + commons-math3 + 3.3 + - + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.assertj - assertj-core - ${assertj.version} - test - + + org.assertj + assertj-core + ${assertj.version} + test + - - org.testng - testng - ${testng.version} - test - + + org.testng + testng + ${testng.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + + + + commons-codec + commons-codec + 1.10 + - - - commons-codec - commons-codec - 1.10 - + + + core-java + + + src/main/resources + true + + - + - - core-java - - - src/main/resources - true - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - + - + + + 4.3.11.Final + 5.1.38 - + + 2.7.2 - - - 4.3.11.Final - 5.1.38 + + 1.7.13 + 1.1.3 - - 2.7.2 + + 5.1.3.Final - - 1.7.13 - 1.1.3 + + 19.0 + 3.4 - - 5.1.3.Final + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 - - 19.0 - 3.4 + 4.4.1 + 4.5 - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 + 2.9.0 - 4.4.1 - 4.5 + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 - 2.9.0 - - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 - - + \ No newline at end of file From 758c5f7319765ed5b1fb352dfd6eca7d67c57162 Mon Sep 17 00:00:00 2001 From: maverick Date: Thu, 29 Sep 2016 15:06:45 +0530 Subject: [PATCH 62/68] Removed files not useful in this branch for MD5 article. --- .../java/com/baeldung/beans/Employee.java | 49 --------- .../org/baeldung/java/sorting/ArraySort.java | 103 ----------------- .../baeldung/java/sorting/ComparingTest.java | 38 ------- .../org/baeldung/java/sorting/Employee.java | 54 --------- .../org/baeldung/java/sorting/ListSort.java | 59 ---------- .../org/baeldung/java/sorting/MapSort.java | 104 ------------------ .../java/sorting/NaturalOrderExample.java | 34 ------ .../org/baeldung/java/sorting/SetSort.java | 54 --------- 8 files changed, 495 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/beans/Employee.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/ListSort.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/MapSort.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/SetSort.java diff --git a/core-java/src/main/java/com/baeldung/beans/Employee.java b/core-java/src/main/java/com/baeldung/beans/Employee.java deleted file mode 100644 index 78d65e18fe..0000000000 --- a/core-java/src/main/java/com/baeldung/beans/Employee.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.beans; - -public class Employee implements Comparable{ - private String name; - private int age; - private double salary; - - public Employee() { - - } - - public Employee(String name, int age, double salary) { - super(); - this.name = name; - this.age = age; - this.salary = salary; - } - - public int getAge() { - return age; - } - public void setAge(int age) { - this.age = age; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public double getSalary() { - return salary; - } - public void setSalary(double salary) { - this.salary = salary; - } - - @Override - public String toString() { - return "("+name+","+age+","+salary+")"; - - } - - @Override - public int compareTo(Object o) { - Employee e = (Employee) o; - return getAge() - e.getAge() ; - } -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java b/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java deleted file mode 100644 index 35e6c8b46d..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/ArraySort.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.baeldung.java.sorting; - -import static org.junit.Assert.*; - -import java.sql.Array; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class ArraySort { - - private int[] numbers; - private Integer[] integers; - private String[] names; - private Employee[] employees; - - @Before - public void initData() { - numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; - integers = new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; - - names = new String[] { "John", "Apple", "Steve", "Frank", "Earl", "Jessica", "Jake", "Pearl" }; - - employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; - - } - - @Test - public void naturalSortIntArray() { - - Arrays.sort(numbers); - - } - - @Test - public void comparatorSortIntArray() { - - Arrays.sort(integers, new Comparator() { - - @Override - public int compare(Integer a, Integer b) { - return a - b; - } - }); - - } - - @Test - public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { - Arrays.sort(integers, (a, b) -> { - return a - b; - }); - - } - - @Test - public void comparableSortEmployeeArrayByAge_NaturalOrder() { - - Arrays.sort(employees); - - } - - @Test - public void comparatorSortEmployeeArrayByName() { - Arrays.sort(employees, new Comparator() { - - @Override - public int compare(Employee o1, Employee o2) { - - return o1.getName().compareTo(o2.getName()); - } - }); - } - - @Test - public void comparatorSortEmployeeArrayByName_Java8Lambda() { - Arrays.sort(employees, (o1, o2) -> { - return o1.getName().compareTo(o2.getName()); - - }); - } - - @Test - public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { - System.out.println(Arrays.toString(numbers)); - Arrays.sort(numbers, 3, 7); - System.out.println(Arrays.toString(numbers)); - - } - - @Test - public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { - - Arrays.parallelSort(numbers); - - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java b/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java deleted file mode 100644 index 02cdede7db..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/ComparingTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.java.sorting; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class ComparingTest { - - private List employees; - - @Before - public void initData() { - - // employees = Arrays.asList(new Employee[] { - // new Employee("John", 23, 5000), - // new Employee("Steve", 26, 6000), - // new Employee("Frank", 33, 7000), - // new Employee("Earl", 43, 10000), - // new Employee("Jessica", 23, 4000), - // new Employee("Pearl", 33, 6000) }); - - } - - @Test - public void testComparing() { - employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); - - employees.sort(Comparator.comparing(Employee::getAge).thenComparing(Employee::getName)); - - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java deleted file mode 100644 index f36e552daf..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.baeldung.java.sorting; - -public class Employee implements Comparable { - private String name; - private int age; - private double salary; - - public Employee() { - - } - - public Employee(String name, int age, double salary) { - super(); - this.name = name; - this.age = age; - this.salary = salary; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getSalary() { - return salary; - } - - public void setSalary(double salary) { - this.salary = salary; - } - - @Override - public String toString() { - return "(" + name + "," + age + "," + salary + ")"; - - } - - @Override - public int compareTo(Object o) { - Employee e = (Employee) o; - return getAge() - e.getAge(); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java b/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java deleted file mode 100644 index 91e1c40607..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/ListSort.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung.java.sorting; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class ListSort { - - private List integers; - private List employees; - - @Before - public void initData() { - integers = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); - - employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }); - } - - @Test - public void naturalOrderIntegerListSort() { - - Collections.sort(integers); - - } - - @Test - public void comparableEmployeeSortByAge() { - - Collections.sort(employees); - - } - - @Test - public void comparatorEmployeeSortByName() { - - Collections.sort(employees, new Comparator() { - @Override - public int compare(Employee e1, Employee e2) { - return e1.getName().compareTo(e2.getName()); - } - }); - - } - - @Test - public void comparatorEmployeeSortByNameJava8() { - - Collections.sort(employees, (e1, e2) -> { - return e1.getName().compareTo(e1.getName()); - }); - - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java b/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java deleted file mode 100644 index 1a9fd30437..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/MapSort.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.baeldung.java.sorting; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.junit.Before; -import org.junit.Test; - -public class MapSort { - - HashMap map; - - @Before - public void initData() { - map = new HashMap<>(); - - map.put(55, "John"); - map.put(22, "Apple"); - map.put(66, "Earl"); - map.put(77, "Pearl"); - map.put(12, "George"); - map.put(6, "Rocky"); - - } - - @Test - public void sortMapByKeys() { - - - List> entries = new ArrayList<>(map.entrySet()); - - Collections.sort(entries, new Comparator>() { - - @Override - public int compare(Entry o1, Entry o2) { - - return o1.getKey().compareTo(o2.getKey()); - } - }); - - HashMap sortedMap = new LinkedHashMap<>(); - - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - - - } - - @Test - public void sortMapByValues() { - - //showMap(map); - - List> entries = new ArrayList<>(map.entrySet()); - - Collections.sort(entries, new Comparator>() { - - @Override - public int compare(Entry o1, Entry o2) { - return o1.getValue().compareTo(o2.getValue()); - } - }); - - HashMap sortedMap = new LinkedHashMap<>(); - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - -/// showMap(sortedMap); - } - - @Test - public void sortMapViaTreeMap() { - -// showMap(map); - Map treeMap = new TreeMap<>(new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return o1 - o2; - } - }); - - treeMap.putAll(map); -// showMap(treeMap); - - } - - public void showMap(Map map1) { - for (Map.Entry entry : map1.entrySet()) { - System.out.println("[Key: " + entry.getKey() + " , " + "Value: " + entry.getValue() + "] "); - - } - - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java b/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java deleted file mode 100644 index bb35557561..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/NaturalOrderExample.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.java.sorting; - -import java.util.Arrays; -import java.util.Comparator; - -import org.junit.Test; - -public class NaturalOrderExample { - - @Test - public void sortArray() { - int[] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; - - Arrays.sort(numbers); - - } - - @Test - public void sortEmployees() { - Employee[] employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; - - Arrays.sort(employees, new Comparator() { - - @Override - public int compare(Employee o1, Employee o2) { - return -(int) (o1.getSalary() - o2.getSalary()); - } - }); - - - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java b/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java deleted file mode 100644 index d892223862..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/SetSort.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.baeldung.java.sorting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.TreeSet; - -import org.junit.Before; -import org.junit.Test; - -public class SetSort { - - private HashSet integers; - private TreeSet employees; - - @Before - public void initData() { - - integers = new HashSet<>(); - integers.addAll(Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 })); - - employees = new TreeSet<>(); - - employees.addAll(Arrays.asList(new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), - new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) })); - - } - - @Test - public void hashSetSortIntegers() { - - - - ArrayList list = new ArrayList(integers); - Collections.sort(list, (i1, i2) -> { - return i2 - i1; - }); - - - } - - @Test - public void treeSetEmployeeSorting() { - - ArrayList list = new ArrayList(employees); - Collections.sort(list, (e1, e2) -> { - return e2.getName().compareTo(e1.getName()); - }); - - } - -} From 769956a808235ba55e0ea2440df38010a85880cf Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 29 Sep 2016 09:35:12 -0400 Subject: [PATCH 63/68] added pom.xml --- spring-userservice/pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 5edaf15d9b..341e232ec6 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -195,7 +195,17 @@ jstl-api 1.2 - + + org.springframework.boot + spring-boot-test + 1.4.1.RELEASE + + + org.springframework.boot + spring-boot + 1.4.1.RELEASE + + spring-userservice From e021ca1be62bbad90c1ca288d9701d2c288c5c5b Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Thu, 29 Sep 2016 16:17:07 +0200 Subject: [PATCH 64/68] BAEL-255 - read file from Java --- core-java-8/src/main/resources/fileTest.txt | 1 + .../com/baeldung/file/FileOperationsTest.java | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 core-java-8/src/main/resources/fileTest.txt create mode 100644 core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java-8/src/main/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-8/src/main/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java new file mode 100644 index 0000000000..b1476b6360 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -0,0 +1,78 @@ +package com.baeldung.file; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; + +import static org.hamcrest.CoreMatchers.containsString; + +public class FileOperationsTest { + + @Test + public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); +} + + @Test + public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Class clazz = FileOperationsTest.class; + InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + @Test + public void givenURLName_whenUsingURL_thenFileData() throws IOException { + String expectedData = "Baeldung"; + + URL urlObject = new URL("http://www.baeldung.com/"); + URLConnection urlConnection = urlObject.openConnection(); + + InputStream inputStream = urlConnection.getInputStream(); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + @Test + public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { + String expectedData = "BSD License"; + + Class clazz = Matchers.class; + InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + private String readFromInputStream(InputStream inputStream) throws IOException { + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + StringBuilder resultStringBuilder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line); + resultStringBuilder.append("\n"); + } + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + return resultStringBuilder.toString(); + } +} \ No newline at end of file From d12d4e6ca56e9127964d71ed9a832047a6be676c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 29 Sep 2016 13:52:11 -0400 Subject: [PATCH 65/68] update dependency --- spring-userservice/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 341e232ec6..93b01ee49c 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -139,11 +139,6 @@ ${org.springframework.version} - - javax.servlet - servlet-api - 3.0-alpha-1 - org.springframework.security spring-security-core @@ -205,6 +200,11 @@ spring-boot 1.4.1.RELEASE + + javax.servlet + javax.servlet-api + 3.1.0 + From 1b57da559b7b0dba3f1bb4daaee143c6368d91d6 Mon Sep 17 00:00:00 2001 From: Slavisa Baeldung Date: Fri, 30 Sep 2016 16:10:03 +0200 Subject: [PATCH 66/68] BAEL-305 - flatten the module structure for patterns section --- .../patterns/front/controller/data/Book.java | 15 -------- enterprise-patterns/pom.xml | 35 ------------------ .../pom.xml | 20 ++++++---- .../controller/FrontControllerServlet.java | 0 .../controller/commands/FrontCommand.java | 0 .../controller/commands/SearchCommand.java | 0 .../controller/commands/UnknownCommand.java | 0 .../patterns/front/controller/data/Book.java | 12 ++---- .../front/controller/data/Bookshelf.java | 4 +- .../front/controller/data/BookshelfImpl.java | 0 .../src/main/resources/front controller.png | Bin .../src/main/resources/front controller.puml | 0 .../main/webapp/WEB-INF/jsp/book-found.jsp | 0 .../main/webapp/WEB-INF/jsp/book-notfound.jsp | 0 .../src/main/webapp/WEB-INF/jsp/unknown.jsp | 0 .../src/main/webapp/WEB-INF/web.xml | 0 16 files changed, 18 insertions(+), 68 deletions(-) delete mode 100644 enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java delete mode 100644 enterprise-patterns/pom.xml rename {enterprise-patterns/front-controller-pattern => patterns}/pom.xml (77%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java (100%) rename enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java => patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java (75%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java (55%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/resources/front controller.png (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/resources/front controller.puml (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/webapp/WEB-INF/jsp/book-found.jsp (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/webapp/WEB-INF/jsp/book-notfound.jsp (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/webapp/WEB-INF/jsp/unknown.jsp (100%) rename {enterprise-patterns/front-controller-pattern => patterns}/src/main/webapp/WEB-INF/web.xml (100%) 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 deleted file mode 100644 index abadcc0d76..0000000000 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.data; - -public interface Book { - String getAuthor(); - - void setAuthor(String author); - - String getTitle(); - - void setTitle(String title); - - Double getPrice(); - - void setPrice(Double price); -} diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml deleted file mode 100644 index 2fba12547f..0000000000 --- a/enterprise-patterns/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - - com.baeldung.enterprise.patterns - enterprise-patterns-parent - pom - - front-controller-pattern - - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - - - diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/patterns/pom.xml similarity index 77% rename from enterprise-patterns/front-controller-pattern/pom.xml rename to patterns/pom.xml index dbcd4f1b1d..7c23b6f55d 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/patterns/pom.xml @@ -4,15 +4,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - front-controller-pattern + com.baeldung.enterprise.patterns + patterns war - - enterprise-patterns-parent - com.baeldung.enterprise.patterns - 1.0.0-SNAPSHOT - - javax.servlet @@ -22,11 +17,22 @@ + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + org.apache.maven.plugins maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + org.eclipse.jetty diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java similarity index 75% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java index b270bc7985..634e05c3a0 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -1,45 +1,39 @@ package com.baeldung.enterprise.patterns.front.controller.data; -public class BookImpl implements Book { +public class Book { private String author; private String title; private Double price; - public BookImpl() { + public Book() { } - public BookImpl(String author, String title, Double price) { + public Book(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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java similarity index 55% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java index 1e30452d95..524e000bd9 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java +++ b/patterns/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 BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); - add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); } Bookshelf getInstance(); diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png b/patterns/src/main/resources/front controller.png similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png rename to patterns/src/main/resources/front controller.png diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml b/patterns/src/main/resources/front controller.puml similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml rename to patterns/src/main/resources/front controller.puml diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/patterns/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml rename to patterns/src/main/webapp/WEB-INF/web.xml From a7340609b2399bd6c1252154844d8925d05ec997 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 30 Sep 2016 12:01:23 -0400 Subject: [PATCH 67/68] update loaduserbyusername --- .../java/org/baeldung/security/MyUserDetailsService.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java index 4c02f53d20..fe97984af8 100644 --- a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -1,6 +1,7 @@ package org.baeldung.security; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import org.baeldung.persistence.model.MyUser; @@ -27,11 +28,8 @@ public class MyUserDetailsService implements UserDetailsService { if (user == null) { throw new UsernameNotFoundException("No user found with username: " + username); } - else { - final Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority("ROLE_USER")); - return new User(user.getUsername(), user.getPassword(), authorities); - } + return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + } } From c8ff59ffe2329c6d3083e427278fac9ea5eb57f0 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Fri, 30 Sep 2016 21:19:27 +0200 Subject: [PATCH 68/68] NOJIRA - fixing build --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7f7a145056..b4158ef67e 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ dependency-injection deltaspike - enterprise-patterns + patterns feign-client