From 0706cd84532d324f6556a19ad259fbae882ba919 Mon Sep 17 00:00:00 2001 From: maverick Date: Thu, 28 Jul 2016 16:38:17 +0530 Subject: [PATCH 01/33] 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/33] 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 94f08d43af8890b2a53b76c26b9a468b8f00f1d3 Mon Sep 17 00:00:00 2001 From: maverick Date: Mon, 22 Aug 2016 13:21:24 +0530 Subject: [PATCH 03/33] 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 d18e64037ed837ab89b49e4e17a859ce8bb2e71e Mon Sep 17 00:00:00 2001 From: maverick Date: Wed, 31 Aug 2016 19:29:25 +0530 Subject: [PATCH 04/33] 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 491a4b1f95e1ea117c22fc07b47a678a689fec4f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 4 Sep 2016 19:18:58 +0300 Subject: [PATCH 05/33] 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 06/33] 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 07/33] 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 657d1a507f25b8e7f1163c76e109735002843315 Mon Sep 17 00:00:00 2001 From: Kiran Date: Tue, 6 Sep 2016 21:16:06 -0400 Subject: [PATCH 08/33] 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 09/33] 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 10/33] 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 11/33] 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 12/33] 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 a497c42f90b4fb2898a55dab34d30cf5467935c5 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 20 Sep 2016 13:03:27 -0400 Subject: [PATCH 13/33] 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 d9f89bdad3b572d7e8c82aa93bdef96d95f3017e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 26 Sep 2016 20:55:17 -0400 Subject: [PATCH 14/33] 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 a24db3ac1e4214c67ce85637aa24e8048cca54eb Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 27 Sep 2016 20:45:42 -0400 Subject: [PATCH 15/33] 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 16/33] 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 e5302d4e75f170b3e220b3bae6c9d0d4abe9193b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 28 Sep 2016 10:35:21 -0400 Subject: [PATCH 17/33] 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 18/33] 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 19/33] 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 20/33] 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 21/33] 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 22/33] 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 23/33] 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 24/33] 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 25/33] 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 26/33] 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 27/33] 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 28/33] 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 29/33] 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 30/33] 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 31/33] 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 32/33] 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 33/33] 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 +