From 065a6e2519d5b52093381a388f9075c5580d8f7f Mon Sep 17 00:00:00 2001 From: jose Date: Tue, 8 Jan 2019 23:55:48 -0300 Subject: [PATCH 01/72] BAEL-2472 code examples --- .../com/baeldung/scope/ClassScopeExample.java | 15 +++++++++++++++ .../com/baeldung/scope/LoopScopeExample.java | 18 ++++++++++++++++++ .../com/baeldung/scope/MethodScopeExample.java | 16 ++++++++++++++++ .../baeldung/scope/NestedScopesExample.java | 13 +++++++++++++ .../com/baeldung/scope/OutOfScopeExample.java | 14 ++++++++++++++ 5 files changed, 76 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java create mode 100644 core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java create mode 100644 core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java create mode 100644 core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java create mode 100644 core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java diff --git a/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java b/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java new file mode 100644 index 0000000000..17ca1e01eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java @@ -0,0 +1,15 @@ +package org.baeldung.variable.scope.examples; + +public class ClassScopeExample { + + Integer amount = 0; + + public void exampleMethod() { + amount++; + } + + public void anotherExampleMethod() { + amount--; + } + +} diff --git a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java new file mode 100644 index 0000000000..2dd3be3333 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java @@ -0,0 +1,18 @@ +package org.baeldung.variable.scope.examples; + +import java.util.Arrays; +import java.util.List; + +public class LoopScopeExample { + + List listOfNames = Arrays.asList("Joe", "Susan", "Pattrick"); + + public void iterationOfNames() { + String allNames = ""; + for (String name : listOfNames) { + allNames = allNames + " " + name; + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java b/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java new file mode 100644 index 0000000000..122d12e2fc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java @@ -0,0 +1,16 @@ +package org.baeldung.variable.scope.examples; + +public class MethodScopeExample { + + Integer size = 2; + + public void methodA() { + Integer area = 2; + area = area + size; + } + + public void methodB() { + size = size + 5; + } + +} diff --git a/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java b/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java new file mode 100644 index 0000000000..9bd2268e52 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java @@ -0,0 +1,13 @@ +package org.baeldung.variable.scope.examples; + +public class NestedScopesExample { + + String title = "Baeldung"; + + public void printTitle() { + System.out.println(title); + String title = "John Doe"; + System.out.println(title); + } + +} diff --git a/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java b/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java new file mode 100644 index 0000000000..774095228c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java @@ -0,0 +1,14 @@ +package org.baeldung.variable.scope.examples; + +public class OutOfScopeExample { + + public void methodWithAVariableDeclaredInside() { + String name = "John Doe"; + System.out.println(name); + } + + public void methodWithoutVariables() { + System.out.println("Pattrick"); + } + +} From f1e3ceaea75f6b5e6efcd2517523baa48b8ccfa8 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 9 Jan 2019 12:21:43 +0400 Subject: [PATCH 02/72] text searching Aho-Corasick algorithm --- java-strings/pom.xml | 6 +++ .../java/com/baeldung/string/MatchWords.java | 48 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 java-strings/src/main/java/com/baeldung/string/MatchWords.java diff --git a/java-strings/pom.xml b/java-strings/pom.xml index f4fb1c0865..9f89ed6d76 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -95,6 +95,12 @@ 1.4 + + org.ahocorasick + ahocorasick + 0.4.0 + + diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java new file mode 100644 index 0000000000..ec926d99c4 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -0,0 +1,48 @@ +package com.baeldung.string; + +import org.ahocorasick.trie.Emit; +import org.ahocorasick.trie.Trie; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.regex.Pattern; + +public class MatchWords { + + // *778*1# *778*00# + public static void main(String[] args) { + String[] items = {"hello", "Baeldung"}; + String inputString = "hello there, Baeldung"; + + boolean isMatch = java8(inputString, new ArrayList<>(Arrays.asList(items))); + + System.out.println(isMatch); + + System.out.println(patternMatch(inputString)); + + ahoCorasick(); + } + + private static void ahoCorasick() { + Trie trie = Trie.builder() + .onlyWholeWords() + .addKeyword("hello") + .addKeyword("Baeldung") + .build(); + Collection emits = trie.parseText("hello there, Baeldung"); + emits.forEach(System.out::println); + } + + private static boolean patternMatch(String inputString) { + Pattern pattern = Pattern.compile("(?=.*hello)(?=.*Baeldung)"); + if (pattern.matcher(inputString).find()) { + return true; + } + return false; + } + + private static boolean java8(String inputString, ArrayList items) { + return Arrays.stream(inputString.split(" ")).allMatch(items::contains); + } +} From 1861e9b94ccadeaed1dd796c5e55bddfbe28607f Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 9 Jan 2019 16:16:48 +0400 Subject: [PATCH 03/72] match words --- .../java/com/baeldung/string/MatchWords.java | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index ec926d99c4..0cdb4cde6a 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -10,18 +10,28 @@ import java.util.regex.Pattern; public class MatchWords { - // *778*1# *778*00# public static void main(String[] args) { String[] items = {"hello", "Baeldung"}; String inputString = "hello there, Baeldung"; - boolean isMatch = java8(inputString, new ArrayList<>(Arrays.asList(items))); + //System.out.println(containsWords(inputString, items)); - System.out.println(isMatch); + System.out.println(java8(new ArrayList<>(Arrays.asList(inputString.split(" "))), new ArrayList<>(Arrays.asList(items)))); - System.out.println(patternMatch(inputString)); + //System.out.println(patternMatch(inputString)); - ahoCorasick(); + //ahoCorasick(); + } + + private static boolean containsWords(String inputString, String[] items) { + boolean found = true; + for (String item : items) { + if (!inputString.contains(item)) { + found = false; + break; + } + } + return found; } private static void ahoCorasick() { @@ -42,7 +52,12 @@ public class MatchWords { return false; } - private static boolean java8(String inputString, ArrayList items) { - return Arrays.stream(inputString.split(" ")).allMatch(items::contains); + private static boolean java8(ArrayList inputString, ArrayList items) { + return items.stream().allMatch(inputString::contains); } + + private static boolean array(ArrayList inputString, ArrayList items) { + return inputString.containsAll(items); + } + } From d413ec768f99a2967075f2dff2d6e456dd7b629c Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 9 Jan 2019 16:18:32 +0400 Subject: [PATCH 04/72] match words final --- .../src/main/java/com/baeldung/string/MatchWords.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 0cdb4cde6a..6e6acb24cf 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -14,13 +14,13 @@ public class MatchWords { String[] items = {"hello", "Baeldung"}; String inputString = "hello there, Baeldung"; - //System.out.println(containsWords(inputString, items)); + System.out.println(containsWords(inputString, items)); System.out.println(java8(new ArrayList<>(Arrays.asList(inputString.split(" "))), new ArrayList<>(Arrays.asList(items)))); - //System.out.println(patternMatch(inputString)); + System.out.println(patternMatch(inputString)); - //ahoCorasick(); + ahoCorasick(); } private static boolean containsWords(String inputString, String[] items) { From 9e9458ea5f000131a76c9105666b77f0c3454fc7 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 9 Jan 2019 17:17:35 +0400 Subject: [PATCH 05/72] indexOf example --- .../java/com/baeldung/string/MatchWords.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 6e6acb24cf..c0f89b635d 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -3,9 +3,7 @@ package com.baeldung.string; import org.ahocorasick.trie.Emit; import org.ahocorasick.trie.Trie; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; +import java.util.*; import java.util.regex.Pattern; public class MatchWords { @@ -21,6 +19,25 @@ public class MatchWords { System.out.println(patternMatch(inputString)); ahoCorasick(); + + wordIndices(inputString); + } + + private static void wordIndices(String inputString) { + Map wordIndices = new TreeMap<>(); + List words = new ArrayList<>(); + words.add("hello"); + words.add("Baeldung"); + + for (String word : words) { + int index = inputString.indexOf(word); + + if (index != -1) { + wordIndices.put(index, word); + } + } + + wordIndices.keySet().forEach(System.out::println); } private static boolean containsWords(String inputString, String[] items) { From ea5039f1a197156e9cb4686f6bd42e9659044e56 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 11 Jan 2019 15:05:34 +0400 Subject: [PATCH 06/72] indexOf changed example --- .../java/com/baeldung/string/MatchWords.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index c0f89b635d..f0b64c19cf 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -20,24 +20,19 @@ public class MatchWords { ahoCorasick(); - wordIndices(inputString); + indexOfWords(inputString, items); } - private static void wordIndices(String inputString) { - Map wordIndices = new TreeMap<>(); - List words = new ArrayList<>(); - words.add("hello"); - words.add("Baeldung"); - + private static boolean indexOfWords(String inputString, String[] words) { + boolean found = true; for (String word : words) { int index = inputString.indexOf(word); - - if (index != -1) { - wordIndices.put(index, word); + if (index == -1) { + found = false; + break; } } - - wordIndices.keySet().forEach(System.out::println); + return found; } private static boolean containsWords(String inputString, String[] items) { From 39f2baab28db45f97309b7cb01e76dcf52227d60 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 11 Jan 2019 21:25:58 +0200 Subject: [PATCH 07/72] Update LoopScopeExample.java --- core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java index 2dd3be3333..04414067ad 100644 --- a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java +++ b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java @@ -12,7 +12,6 @@ public class LoopScopeExample { for (String name : listOfNames) { allNames = allNames + " " + name; } - } } From 16bed6f64b2a55fa36568119a92c3593345b00d1 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 13 Jan 2019 10:42:18 +0400 Subject: [PATCH 08/72] match words refactoring --- .../java/com/baeldung/string/MatchWords.java | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index f0b64c19cf..f4a52ae308 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -9,21 +9,21 @@ import java.util.regex.Pattern; public class MatchWords { public static void main(String[] args) { - String[] items = {"hello", "Baeldung"}; + String[] words = {"hello", "Baeldung"}; String inputString = "hello there, Baeldung"; - System.out.println(containsWords(inputString, items)); + containsWords(inputString, words); - System.out.println(java8(new ArrayList<>(Arrays.asList(inputString.split(" "))), new ArrayList<>(Arrays.asList(items)))); + containsWordsJava8(new ArrayList<>(Arrays.asList(inputString.split(" "))), new ArrayList<>(Arrays.asList(words))); - System.out.println(patternMatch(inputString)); + containsWordsPatternMatch(inputString, words); - ahoCorasick(); + containsWordsAhoCorasick(inputString, words); - indexOfWords(inputString, items); + containsWordsIndexOf(inputString, words); } - private static boolean indexOfWords(String inputString, String[] words) { + private static boolean containsWordsIndexOf(String inputString, String[] words) { boolean found = true; for (String word : words) { int index = inputString.indexOf(word); @@ -46,30 +46,31 @@ public class MatchWords { return found; } - private static void ahoCorasick() { + private static boolean containsWordsAhoCorasick(String inputString, String[] words) { Trie trie = Trie.builder() .onlyWholeWords() - .addKeyword("hello") - .addKeyword("Baeldung") + .addKeyword(words[0]) + .addKeyword(words[1]) .build(); - Collection emits = trie.parseText("hello there, Baeldung"); - emits.forEach(System.out::println); + Collection emits = trie.parseText(inputString); + + return emits.size() == words.length; } - private static boolean patternMatch(String inputString) { - Pattern pattern = Pattern.compile("(?=.*hello)(?=.*Baeldung)"); + private static boolean containsWordsPatternMatch(String inputString, String[] words) { + Pattern pattern = Pattern.compile("(?=.*words[0])(?=.*words[1])"); if (pattern.matcher(inputString).find()) { return true; } return false; } - private static boolean java8(ArrayList inputString, ArrayList items) { - return items.stream().allMatch(inputString::contains); + private static boolean containsWordsJava8(ArrayList inputString, ArrayList words) { + return words.stream().allMatch(inputString::contains); } - private static boolean array(ArrayList inputString, ArrayList items) { - return inputString.containsAll(items); + private static boolean containsWordsArray(ArrayList inputString, ArrayList words) { + return inputString.containsAll(words); } } From 06ffe3b5e42581d28e582d68ebf35f2403789954 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 13 Jan 2019 11:04:42 +0400 Subject: [PATCH 09/72] match words final refactor --- .../main/java/com/baeldung/string/MatchWords.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index f4a52ae308..675f4577c3 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -4,7 +4,10 @@ import org.ahocorasick.trie.Emit; import org.ahocorasick.trie.Trie; import java.util.*; +import java.util.function.Function; import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class MatchWords { @@ -51,14 +54,17 @@ public class MatchWords { .onlyWholeWords() .addKeyword(words[0]) .addKeyword(words[1]) + .ignoreOverlaps() .build(); - Collection emits = trie.parseText(inputString); - + Collection emits = trie.parseText(inputString) + .stream() + .filter(e -> !Objects.equals(e.getKeyword(), e.getKeyword())) + .collect(Collectors.toList()); return emits.size() == words.length; } private static boolean containsWordsPatternMatch(String inputString, String[] words) { - Pattern pattern = Pattern.compile("(?=.*words[0])(?=.*words[1])"); + Pattern pattern = Pattern.compile("(?=.*hello)(?=.*Baeldung)"); if (pattern.matcher(inputString).find()) { return true; } From 04c6cd1215be367f43652a6e771f4bf8eba0032e Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 13 Jan 2019 11:35:54 +0400 Subject: [PATCH 10/72] replace hardcoded strings --- .../src/main/java/com/baeldung/string/MatchWords.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 675f4577c3..0b803da0ae 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -56,15 +56,20 @@ public class MatchWords { .addKeyword(words[1]) .ignoreOverlaps() .build(); + Collection emits = trie.parseText(inputString) .stream() .filter(e -> !Objects.equals(e.getKeyword(), e.getKeyword())) .collect(Collectors.toList()); + + emits.forEach(System.out::println); + return emits.size() == words.length; } private static boolean containsWordsPatternMatch(String inputString, String[] words) { - Pattern pattern = Pattern.compile("(?=.*hello)(?=.*Baeldung)"); + + Pattern pattern = Pattern.compile("(?=.*" + words[0] + ")(?=.*" + words[1] + ")"); if (pattern.matcher(inputString).find()) { return true; } From 9c0363e221aba40d44323fd57eecf4e78edd3243 Mon Sep 17 00:00:00 2001 From: jose Date: Sun, 13 Jan 2019 15:12:40 -0300 Subject: [PATCH 11/72] BAEL-2472 changes after editor-review --- .../com/baeldung/scope/BracketScopeExample.java | 14 ++++++++++++++ .../java/com/baeldung/scope/ClassScopeExample.java | 5 ++--- .../java/com/baeldung/scope/LoopScopeExample.java | 6 +++--- .../com/baeldung/scope/MethodScopeExample.java | 9 +++------ .../com/baeldung/scope/NestedScopesExample.java | 3 +-- .../java/com/baeldung/scope/OutOfScopeExample.java | 14 -------------- 6 files changed, 23 insertions(+), 28 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java delete mode 100644 core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java diff --git a/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java b/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java new file mode 100644 index 0000000000..37ae211dcb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java @@ -0,0 +1,14 @@ +package org.baeldung.variable.scope.examples; + +public class BracketScopeExample { + + public void mathOperationExample() { + Integer sum = 0; + { + Integer number = 2; + sum = sum + number; + } + // compiler error, number cannot be solved as a variable + // number++; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java b/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java index 17ca1e01eb..241c6b466e 100644 --- a/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java +++ b/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java @@ -9,7 +9,6 @@ public class ClassScopeExample { } public void anotherExampleMethod() { - amount--; + Integer anotherAmount = amount + 4; } - -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java index 2dd3be3333..8049a49c4d 100644 --- a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java +++ b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java @@ -12,7 +12,7 @@ public class LoopScopeExample { for (String name : listOfNames) { allNames = allNames + " " + name; } - + // compiler error, name cannot be resolved to a variable + // String lastNameUsed = name; } - -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java b/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java index 122d12e2fc..e62c6a2a1c 100644 --- a/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java +++ b/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java @@ -2,15 +2,12 @@ package org.baeldung.variable.scope.examples; public class MethodScopeExample { - Integer size = 2; - public void methodA() { Integer area = 2; - area = area + size; } public void methodB() { - size = size + 5; + // compiler error, area cannot be resolved to a variable + // area = area + 2; } - -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java b/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java index 9bd2268e52..fcd23e5ae0 100644 --- a/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java +++ b/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java @@ -9,5 +9,4 @@ public class NestedScopesExample { String title = "John Doe"; System.out.println(title); } - -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java b/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java deleted file mode 100644 index 774095228c..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/OutOfScopeExample.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.variable.scope.examples; - -public class OutOfScopeExample { - - public void methodWithAVariableDeclaredInside() { - String name = "John Doe"; - System.out.println(name); - } - - public void methodWithoutVariables() { - System.out.println("Pattrick"); - } - -} From c9275edf90db9fc2c8d22ce7dd6f1f7780401605 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 14 Jan 2019 11:53:53 +0400 Subject: [PATCH 12/72] matching for all keywords --- .../java/com/baeldung/string/MatchWords.java | 51 +++++++++++++------ 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 0b803da0ae..9374ef84a2 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -1,6 +1,7 @@ package com.baeldung.string; import org.ahocorasick.trie.Emit; +import org.ahocorasick.trie.Token; import org.ahocorasick.trie.Trie; import java.util.*; @@ -17,7 +18,7 @@ public class MatchWords { containsWords(inputString, words); - containsWordsJava8(new ArrayList<>(Arrays.asList(inputString.split(" "))), new ArrayList<>(Arrays.asList(words))); + containsWordsJava8(inputString, words); containsWordsPatternMatch(inputString, words); @@ -52,36 +53,56 @@ public class MatchWords { private static boolean containsWordsAhoCorasick(String inputString, String[] words) { Trie trie = Trie.builder() .onlyWholeWords() - .addKeyword(words[0]) - .addKeyword(words[1]) - .ignoreOverlaps() + .addKeywords(words) .build(); - Collection emits = trie.parseText(inputString) - .stream() - .filter(e -> !Objects.equals(e.getKeyword(), e.getKeyword())) - .collect(Collectors.toList()); - + Collection emits = trie.parseText(inputString); emits.forEach(System.out::println); - return emits.size() == words.length; + boolean found = true; + for(String word : words) { + boolean contains = Arrays.toString(emits.toArray()).contains(word); + if (!contains) { + found = false; + break; + } + } + + return found; } private static boolean containsWordsPatternMatch(String inputString, String[] words) { - Pattern pattern = Pattern.compile("(?=.*" + words[0] + ")(?=.*" + words[1] + ")"); + StringBuilder regexp = new StringBuilder(); + for (String word : words) { + regexp.append("(?=.*").append(word).append(")"); + } + Pattern pattern = Pattern.compile(regexp.toString()); if (pattern.matcher(inputString).find()) { return true; } return false; } - private static boolean containsWordsJava8(ArrayList inputString, ArrayList words) { - return words.stream().allMatch(inputString::contains); + private static boolean containsWordsJava8(String inputString, String[] words) { + ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); + ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); + + return wordsList.stream().allMatch(inputStringList::contains); } - private static boolean containsWordsArray(ArrayList inputString, ArrayList words) { - return inputString.containsAll(words); + private static boolean containsWordsArray(String inputString, String[] words) { + ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); + ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); + + return inputStringList.containsAll(wordsList); + } + + private static boolean containsAnyWord(String inputString, String[] words) { + ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); + ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); + + return inputStringList.contains(wordsList); } } From aa125c6c6b4820fd5c2e058071ab169e345e533e Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 14 Jan 2019 11:58:31 +0400 Subject: [PATCH 13/72] remove unnecessary method --- .../src/main/java/com/baeldung/string/MatchWords.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 9374ef84a2..647b60af9a 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -77,6 +77,7 @@ public class MatchWords { for (String word : words) { regexp.append("(?=.*").append(word).append(")"); } + Pattern pattern = Pattern.compile(regexp.toString()); if (pattern.matcher(inputString).find()) { return true; @@ -97,12 +98,4 @@ public class MatchWords { return inputStringList.containsAll(wordsList); } - - private static boolean containsAnyWord(String inputString, String[] words) { - ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); - ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); - - return inputStringList.contains(wordsList); - } - } From 9f798d483d03f07d179dd5542101af8eaa1fd9ef Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 16 Jan 2019 13:18:04 +0400 Subject: [PATCH 14/72] test the methods with Unit test --- .../java/com/baeldung/string/MatchWords.java | 27 ++------- .../baeldung/string/MatchWordsUnitTest.java | 59 +++++++++++++++++++ 2 files changed, 65 insertions(+), 21 deletions(-) create mode 100644 java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 647b60af9a..d322d192fa 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -12,22 +12,7 @@ import java.util.stream.Stream; public class MatchWords { - public static void main(String[] args) { - String[] words = {"hello", "Baeldung"}; - String inputString = "hello there, Baeldung"; - - containsWords(inputString, words); - - containsWordsJava8(inputString, words); - - containsWordsPatternMatch(inputString, words); - - containsWordsAhoCorasick(inputString, words); - - containsWordsIndexOf(inputString, words); - } - - private static boolean containsWordsIndexOf(String inputString, String[] words) { + public static boolean containsWordsIndexOf(String inputString, String[] words) { boolean found = true; for (String word : words) { int index = inputString.indexOf(word); @@ -39,7 +24,7 @@ public class MatchWords { return found; } - private static boolean containsWords(String inputString, String[] items) { + public static boolean containsWords(String inputString, String[] items) { boolean found = true; for (String item : items) { if (!inputString.contains(item)) { @@ -50,7 +35,7 @@ public class MatchWords { return found; } - private static boolean containsWordsAhoCorasick(String inputString, String[] words) { + public static boolean containsWordsAhoCorasick(String inputString, String[] words) { Trie trie = Trie.builder() .onlyWholeWords() .addKeywords(words) @@ -71,7 +56,7 @@ public class MatchWords { return found; } - private static boolean containsWordsPatternMatch(String inputString, String[] words) { + public static boolean containsWordsPatternMatch(String inputString, String[] words) { StringBuilder regexp = new StringBuilder(); for (String word : words) { @@ -85,14 +70,14 @@ public class MatchWords { return false; } - private static boolean containsWordsJava8(String inputString, String[] words) { + public static boolean containsWordsJava8(String inputString, String[] words) { ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); return wordsList.stream().allMatch(inputStringList::contains); } - private static boolean containsWordsArray(String inputString, String[] words) { + public static boolean containsWordsArray(String inputString, String[] words) { ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java new file mode 100644 index 0000000000..0b25a265b3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.string; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MatchWordsUnitTest { + + private final String[] words = {"hello", "Baeldung"}; + private final String inputString = "hello there, Baeldung"; + + @Test + public void givenText_whenCallingStringContains_shouldMatchWords() { + + final boolean result = MatchWords.containsWords(inputString, words); + + assertThat(result).isEqualTo(true); + } + + @Test + public void givenText_whenCallingJava8_shouldMatchWords() { + + final boolean result = MatchWords.containsWordsJava8(inputString, words); + + assertThat(result).isEqualTo(true); + } + + @Test + public void givenText_whenCallingPattern_shouldMatchWords() { + + final boolean result = MatchWords.containsWordsPatternMatch(inputString, words); + + assertThat(result).isEqualTo(true); + } + + @Test + public void givenText_whenCallingAhoCorasick_shouldMatchWords() { + + final boolean result = MatchWords.containsWordsAhoCorasick(inputString, words); + + assertThat(result).isEqualTo(true); + } + + @Test + public void givenText_whenCallingIndexOf_shouldMatchWords() { + + final boolean result = MatchWords.containsWordsIndexOf(inputString, words); + + assertThat(result).isEqualTo(true); + } + + @Test + public void givenText_whenCallingArrayList_shouldMatchWords() { + + final boolean result = MatchWords.containsWordsArray(inputString, words); + + assertThat(result).isEqualTo(true); + } +} From d83101854c35218ea54bbaa5f6ce6747d16d44bf Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 18 Jan 2019 11:05:26 +0400 Subject: [PATCH 15/72] primitive collections libraries added --- core-java-arrays/pom.xml | 16 ++++ .../baeldung/array/PrimitiveCollections.java | 34 ++++++++ .../array/PrimitivesListPerformance.java | 77 +++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java create mode 100644 core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java diff --git a/core-java-arrays/pom.xml b/core-java-arrays/pom.xml index d2d0453e87..6d4109804e 100644 --- a/core-java-arrays/pom.xml +++ b/core-java-arrays/pom.xml @@ -52,6 +52,22 @@ spring-web ${springframework.spring-web.version} + + + net.sf.trove4j + trove4j + 3.0.2 + + + it.unimi.dsi + fastutil + 8.1.0 + + + colt + colt + 1.2.0 + diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java new file mode 100644 index 0000000000..115c5fe5c3 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -0,0 +1,34 @@ +package com.baeldung.array; + +import com.google.common.primitives.ImmutableIntArray; +import com.google.common.primitives.Ints; +import gnu.trove.list.array.TIntArrayList; + +import java.util.Arrays; +import java.util.List; + +public class PrimitiveCollections { + + public static void main(String[] args) { + + int[] primitives = new int[] {5, 10, 0, 2}; + + guavaPrimitives(primitives); + + trovePrimitives(primitives); + } + + private static void trovePrimitives(int[] primitives) { + TIntArrayList list = new TIntArrayList(primitives); + } + + private static void guavaPrimitives(int[] primitives) { + + ImmutableIntArray list = ImmutableIntArray.builder().addAll(primitives).build(); + + List integers = Ints.asList(primitives); + + int[] primitive = Ints.toArray(Arrays.asList(1, 2, 3, 4, 5)); + System.out.println(Arrays.toString(primitive)); + } +} diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java new file mode 100644 index 0000000000..9db3a75574 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java @@ -0,0 +1,77 @@ +package com.baeldung.array; + +import it.unimi.dsi.fastutil.ints.IntArrayList; +import gnu.trove.list.array.TIntArrayList; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 10) +public class PrimitivesListPerformance { + + @State(Scope.Thread) + public static class Initialize { + + List arrayList = new ArrayList<>(); + TIntArrayList tList = new TIntArrayList(); + cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); + IntArrayList fastUtilList = new IntArrayList(); + + int getValue = 10; + + final int iterations = 100000; + + @Setup(Level.Trial) + public void setUp() { + + for (int i = 0; i < iterations; i++) { + arrayList.add(i); + tList.add(i); + coltList.add(i); + fastUtilList.add(i); + } + + arrayList.add(getValue); + tList.add(getValue); + coltList.add(getValue); + fastUtilList.add(getValue); + } + } + + @Benchmark + public boolean containsArrayList(PrimitivesListPerformance.Initialize state) { + return state.arrayList.contains(state.getValue); + } + + @Benchmark + public boolean containsTIntList(PrimitivesListPerformance.Initialize state) { + return state.tList.contains(state.getValue); + } + + @Benchmark + public boolean containsColtIntList(PrimitivesListPerformance.Initialize state) { + return state.coltList.contains(state.getValue); + } + + @Benchmark + public boolean containsFastUtilIntList(PrimitivesListPerformance.Initialize state) { + return state.fastUtilList.contains(state.getValue); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} From 89ff253342752027c17b8088b8940df972a5d17f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 20 Jan 2019 21:56:30 +0200 Subject: [PATCH 16/72] Update TaskScheduler.java --- .../java/com/baeldung/scheduling/shedlock/TaskScheduler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java index b1b1ad921f..060afe660e 100644 --- a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java +++ b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java @@ -7,9 +7,9 @@ import org.springframework.stereotype.Component; @Component class TaskScheduler { - @Scheduled(cron = "*/15 * * * * *") + @Scheduled(cron = "*/15 * * * *") @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); } -} \ No newline at end of file +} From c713ddee6da9f3b3efc13a0b1935582c2581fee0 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 21 Jan 2019 09:26:47 +0400 Subject: [PATCH 17/72] trove list --- .../java/com/baeldung/array/PrimitiveCollections.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java index 115c5fe5c3..b991dcb598 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -2,6 +2,7 @@ package com.baeldung.array; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; +import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import java.util.Arrays; @@ -13,13 +14,16 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; - guavaPrimitives(primitives); + //guavaPrimitives(primitives); trovePrimitives(primitives); } private static void trovePrimitives(int[] primitives) { - TIntArrayList list = new TIntArrayList(primitives); + TIntList tList = new TIntArrayList(primitives); + tList.reverse(); + System.out.println(tList); + System.out.println(tList.size()); } private static void guavaPrimitives(int[] primitives) { From 5c1a0a06292115d99e24493ca1d69e32414e09b6 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 21 Jan 2019 09:57:15 +0400 Subject: [PATCH 18/72] change the ArrayList into List --- .../src/main/java/com/baeldung/string/MatchWords.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index d322d192fa..4baaa49227 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -71,15 +71,15 @@ public class MatchWords { } public static boolean containsWordsJava8(String inputString, String[] words) { - ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); - ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); + List inputStringList = Arrays.asList(inputString.split(" ")); + List wordsList = Arrays.asList(words); return wordsList.stream().allMatch(inputStringList::contains); } public static boolean containsWordsArray(String inputString, String[] words) { - ArrayList inputStringList = new ArrayList<>(Arrays.asList(inputString.split(" "))); - ArrayList wordsList = new ArrayList<>(Arrays.asList(words)); + List inputStringList = Arrays.asList(inputString.split(" ")); + List wordsList = Arrays.asList(words); return inputStringList.containsAll(wordsList); } From 81f23992cb19ef7860cc4faa57df167a5d6d8ecd Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 21 Jan 2019 13:08:09 +0400 Subject: [PATCH 19/72] primitive collections --- .../baeldung/array/PrimitiveCollections.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java index b991dcb598..85f4dd2498 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -2,8 +2,6 @@ package com.baeldung.array; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; -import gnu.trove.list.TIntList; -import gnu.trove.list.array.TIntArrayList; import java.util.Arrays; import java.util.List; @@ -14,25 +12,21 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; - //guavaPrimitives(primitives); - - trovePrimitives(primitives); + guavaPrimitives(primitives); } - private static void trovePrimitives(int[] primitives) { - TIntList tList = new TIntArrayList(primitives); - tList.reverse(); - System.out.println(tList); - System.out.println(tList.size()); - } private static void guavaPrimitives(int[] primitives) { - ImmutableIntArray list = ImmutableIntArray.builder().addAll(primitives).build(); + ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build(); + System.out.println(immutableIntArray); - List integers = Ints.asList(primitives); + List list = Ints.asList(primitives); - int[] primitive = Ints.toArray(Arrays.asList(1, 2, 3, 4, 5)); - System.out.println(Arrays.toString(primitive)); + int[] primitiveArray = Ints.toArray(list); + + int[] concatenated = Ints.concat(primitiveArray, primitives); + + System.out.println(Arrays.toString(concatenated)); } } From 8c18214c558dc21ca0f956d50ad0587c19be1362 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 23 Jan 2019 09:44:05 +0400 Subject: [PATCH 20/72] more unit tests --- .../baeldung/string/MatchWordsUnitTest.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java index 0b25a265b3..1c2288068b 100644 --- a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java @@ -8,52 +8,59 @@ public class MatchWordsUnitTest { private final String[] words = {"hello", "Baeldung"}; private final String inputString = "hello there, Baeldung"; + private final String wholeInput = "helloBaeldung"; @Test public void givenText_whenCallingStringContains_shouldMatchWords() { - final boolean result = MatchWords.containsWords(inputString, words); - assertThat(result).isEqualTo(true); } @Test public void givenText_whenCallingJava8_shouldMatchWords() { - final boolean result = MatchWords.containsWordsJava8(inputString, words); - assertThat(result).isEqualTo(true); } + @Test + public void givenText_whenCallingJava8_shouldNotMatchWords() { + final boolean result = MatchWords.containsWordsJava8(wholeInput, words); + assertThat(result).isEqualTo(false); + } + @Test public void givenText_whenCallingPattern_shouldMatchWords() { - final boolean result = MatchWords.containsWordsPatternMatch(inputString, words); - assertThat(result).isEqualTo(true); } @Test public void givenText_whenCallingAhoCorasick_shouldMatchWords() { - final boolean result = MatchWords.containsWordsAhoCorasick(inputString, words); - assertThat(result).isEqualTo(true); } + @Test + public void givenText_whenCallingAhoCorasick_shouldNotMatchWords() { + final boolean result = MatchWords.containsWordsAhoCorasick(wholeInput, words); + assertThat(result).isEqualTo(false); + } + @Test public void givenText_whenCallingIndexOf_shouldMatchWords() { - final boolean result = MatchWords.containsWordsIndexOf(inputString, words); - assertThat(result).isEqualTo(true); } @Test public void givenText_whenCallingArrayList_shouldMatchWords() { - final boolean result = MatchWords.containsWordsArray(inputString, words); - assertThat(result).isEqualTo(true); } + + @Test + public void givenText_whenCallingArrayList_shouldNotMatchWords() { + final boolean result = MatchWords.containsWordsArray(wholeInput, words); + assertThat(result).isEqualTo(false); + } } From 4c540b764c9911a1e7f90cd01eea7087a9c170cd Mon Sep 17 00:00:00 2001 From: jose Date: Thu, 24 Jan 2019 23:04:56 -0300 Subject: [PATCH 21/72] Moving classes into core-java-lang --- .../baeldung/scope/BracketScopeExample.java | 14 -------------- .../com/baeldung/scope/ClassScopeExample.java | 14 -------------- .../com/baeldung/scope/LoopScopeExample.java | 18 ------------------ .../com/baeldung/scope/MethodScopeExample.java | 13 ------------- .../baeldung/scope/NestedScopesExample.java | 12 ------------ 5 files changed, 71 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java delete mode 100644 core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java delete mode 100644 core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java delete mode 100644 core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java delete mode 100644 core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java diff --git a/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java b/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java deleted file mode 100644 index 37ae211dcb..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/BracketScopeExample.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.variable.scope.examples; - -public class BracketScopeExample { - - public void mathOperationExample() { - Integer sum = 0; - { - Integer number = 2; - sum = sum + number; - } - // compiler error, number cannot be solved as a variable - // number++; - } -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java b/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java deleted file mode 100644 index 241c6b466e..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/ClassScopeExample.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.variable.scope.examples; - -public class ClassScopeExample { - - Integer amount = 0; - - public void exampleMethod() { - amount++; - } - - public void anotherExampleMethod() { - Integer anotherAmount = amount + 4; - } -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java deleted file mode 100644 index 7bf92a6d26..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/LoopScopeExample.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.variable.scope.examples; - -import java.util.Arrays; -import java.util.List; - -public class LoopScopeExample { - - List listOfNames = Arrays.asList("Joe", "Susan", "Pattrick"); - - public void iterationOfNames() { - String allNames = ""; - for (String name : listOfNames) { - allNames = allNames + " " + name; - } - // compiler error, name cannot be resolved to a variable - // String lastNameUsed = name; - } -} diff --git a/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java b/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java deleted file mode 100644 index e62c6a2a1c..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/MethodScopeExample.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.variable.scope.examples; - -public class MethodScopeExample { - - public void methodA() { - Integer area = 2; - } - - public void methodB() { - // compiler error, area cannot be resolved to a variable - // area = area + 2; - } -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java b/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java deleted file mode 100644 index fcd23e5ae0..0000000000 --- a/core-java/src/main/java/com/baeldung/scope/NestedScopesExample.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.variable.scope.examples; - -public class NestedScopesExample { - - String title = "Baeldung"; - - public void printTitle() { - System.out.println(title); - String title = "John Doe"; - System.out.println(title); - } -} \ No newline at end of file From ca5ff8ac8c70ea1f12148b363ce1a83824131c07 Mon Sep 17 00:00:00 2001 From: jose Date: Thu, 24 Jan 2019 23:06:51 -0300 Subject: [PATCH 22/72] Moving classes into core-java-lang --- .../baeldung/scope/BracketScopeExample.java | 14 ++++++++++++++ .../com/baeldung/scope/ClassScopeExample.java | 14 ++++++++++++++ .../com/baeldung/scope/LoopScopeExample.java | 18 ++++++++++++++++++ .../com/baeldung/scope/MethodScopeExample.java | 13 +++++++++++++ .../baeldung/scope/NestedScopesExample.java | 12 ++++++++++++ 5 files changed, 71 insertions(+) create mode 100644 core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java create mode 100644 core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java create mode 100644 core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java create mode 100644 core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java create mode 100644 core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java new file mode 100644 index 0000000000..37ae211dcb --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java @@ -0,0 +1,14 @@ +package org.baeldung.variable.scope.examples; + +public class BracketScopeExample { + + public void mathOperationExample() { + Integer sum = 0; + { + Integer number = 2; + sum = sum + number; + } + // compiler error, number cannot be solved as a variable + // number++; + } +} \ No newline at end of file diff --git a/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java new file mode 100644 index 0000000000..241c6b466e --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java @@ -0,0 +1,14 @@ +package org.baeldung.variable.scope.examples; + +public class ClassScopeExample { + + Integer amount = 0; + + public void exampleMethod() { + amount++; + } + + public void anotherExampleMethod() { + Integer anotherAmount = amount + 4; + } +} \ No newline at end of file diff --git a/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java new file mode 100644 index 0000000000..7bf92a6d26 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java @@ -0,0 +1,18 @@ +package org.baeldung.variable.scope.examples; + +import java.util.Arrays; +import java.util.List; + +public class LoopScopeExample { + + List listOfNames = Arrays.asList("Joe", "Susan", "Pattrick"); + + public void iterationOfNames() { + String allNames = ""; + for (String name : listOfNames) { + allNames = allNames + " " + name; + } + // compiler error, name cannot be resolved to a variable + // String lastNameUsed = name; + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java new file mode 100644 index 0000000000..e62c6a2a1c --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java @@ -0,0 +1,13 @@ +package org.baeldung.variable.scope.examples; + +public class MethodScopeExample { + + public void methodA() { + Integer area = 2; + } + + public void methodB() { + // compiler error, area cannot be resolved to a variable + // area = area + 2; + } +} \ No newline at end of file diff --git a/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java b/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java new file mode 100644 index 0000000000..fcd23e5ae0 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java @@ -0,0 +1,12 @@ +package org.baeldung.variable.scope.examples; + +public class NestedScopesExample { + + String title = "Baeldung"; + + public void printTitle() { + System.out.println(title); + String title = "John Doe"; + System.out.println(title); + } +} \ No newline at end of file From ae344b37ec7d7c0ed2cb0141e96c9811ad4eea71 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 25 Jan 2019 09:51:15 +0400 Subject: [PATCH 23/72] move the code into core-java-collections-lists module --- core-java-arrays/pom.xml | 16 ---------- core-java-collections-list/pom.xml | 29 +++++++++++++++++++ .../list/primitive}/PrimitiveCollections.java | 2 +- .../primitive}/PrimitivesListPerformance.java | 3 +- 4 files changed, 31 insertions(+), 19 deletions(-) rename {core-java-arrays/src/main/java/com/baeldung/array => core-java-collections-list/src/main/java/com/baeldung/list/primitive}/PrimitiveCollections.java (95%) rename {core-java-arrays/src/main/java/com/baeldung/array => core-java-collections-list/src/main/java/com/baeldung/list/primitive}/PrimitivesListPerformance.java (97%) diff --git a/core-java-arrays/pom.xml b/core-java-arrays/pom.xml index 6d4109804e..d2d0453e87 100644 --- a/core-java-arrays/pom.xml +++ b/core-java-arrays/pom.xml @@ -52,22 +52,6 @@ spring-web ${springframework.spring-web.version} - - - net.sf.trove4j - trove4j - 3.0.2 - - - it.unimi.dsi - fastutil - 8.1.0 - - - colt - colt - 1.2.0 - diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml index ee99e470d0..bc71882683 100644 --- a/core-java-collections-list/pom.xml +++ b/core-java-collections-list/pom.xml @@ -36,6 +36,33 @@ ${lombok.version} provided + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator-annprocess.version} + + + + net.sf.trove4j + trove4j + 3.0.2 + + + it.unimi.dsi + fastutil + 8.1.0 + + + colt + colt + 1.2.0 + @@ -44,5 +71,7 @@ 1.7.0 3.11.1 1.16.12 + 1.19 + 1.19 diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java similarity index 95% rename from core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java rename to core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 85f4dd2498..d6da32d899 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -1,4 +1,4 @@ -package com.baeldung.array; +package com.baeldung.list.primitive; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java similarity index 97% rename from core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java rename to core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java index 9db3a75574..f57c8d65a6 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.array; +package com.baeldung.list.primitive; import it.unimi.dsi.fastutil.ints.IntArrayList; import gnu.trove.list.array.TIntArrayList; @@ -9,7 +9,6 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.ArrayList; import java.util.List; -import java.util.Random; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) From 2f5ef3480b97cea30ec57dafb9370a114f9f8b18 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 25 Jan 2019 10:54:59 +0400 Subject: [PATCH 24/72] remove Ints examples --- .../com/baeldung/list/primitive/PrimitiveCollections.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index d6da32d899..5a8ddc0acd 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -20,13 +20,5 @@ public class PrimitiveCollections { ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build(); System.out.println(immutableIntArray); - - List list = Ints.asList(primitives); - - int[] primitiveArray = Ints.toArray(list); - - int[] concatenated = Ints.concat(primitiveArray, primitives); - - System.out.println(Arrays.toString(concatenated)); } } From c6e808348ddbcb70a90045db7b86affdf6ad9e38 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 26 Jan 2019 10:41:54 +0200 Subject: [PATCH 25/72] Update README.md --- spring-cloud/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index eb2e46c3d0..fede3cc12d 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -15,8 +15,6 @@ ### Relevant Articles: - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) -- [Using a Spring Cloud App Starter](http://www.baeldung.com/using-a-spring-cloud-app-starter) -- [Using a Spring Cloud App Starter](http://www.baeldung.com/spring-cloud-app-starter) - [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) - [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) From 2437a265006e4f7a485952d254058914bd2d8d0f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 26 Jan 2019 10:42:34 +0200 Subject: [PATCH 26/72] Create README.md --- spring-cloud/spring-cloud-stream-starters/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-cloud/spring-cloud-stream-starters/README.md diff --git a/spring-cloud/spring-cloud-stream-starters/README.md b/spring-cloud/spring-cloud-stream-starters/README.md new file mode 100644 index 0000000000..761d54abbd --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/README.md @@ -0,0 +1,3 @@ +#Revelant Articles: + +- [Using a Spring Cloud App Starter](http://www.baeldung.com/spring-cloud-app-starter) From 9a567f95b4be0737af8a9a0cd2b02e09d793bc54 Mon Sep 17 00:00:00 2001 From: PranayVJain Date: Sun, 27 Jan 2019 11:51:13 +0530 Subject: [PATCH 27/72] List files within directory Issue: BAEL-2447 --- .../java/com/baeldung/files/ListFiles.java | 64 +++++++++++++++++++ .../com/baeldung/file/ListFilesUnitTest.java | 46 +++++++++++++ .../listFilesUnitTestFolder/country.txt | 1 + .../listFilesUnitTestFolder/employee.json | 1 + .../listFilesUnitTestFolder/students.json | 1 + .../listFilesUnitTestFolder/test.xml | 1 + 6 files changed, 114 insertions(+) create mode 100644 core-java-io/src/main/java/com/baeldung/files/ListFiles.java create mode 100644 core-java-io/src/test/java/com/baeldung/file/ListFilesUnitTest.java create mode 100644 core-java-io/src/test/resources/listFilesUnitTestFolder/country.txt create mode 100644 core-java-io/src/test/resources/listFilesUnitTestFolder/employee.json create mode 100644 core-java-io/src/test/resources/listFilesUnitTestFolder/students.json create mode 100644 core-java-io/src/test/resources/listFilesUnitTestFolder/test.xml diff --git a/core-java-io/src/main/java/com/baeldung/files/ListFiles.java b/core-java-io/src/main/java/com/baeldung/files/ListFiles.java new file mode 100644 index 0000000000..c5de36270c --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/files/ListFiles.java @@ -0,0 +1,64 @@ +package com.baeldung.files; + +import java.io.File; +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ListFiles { + public static final int DEPTH = 1; + + public Set listFilesUsingJavaIO(String dir) { + return Stream.of(new File(dir).listFiles()) + .filter(file -> !file.isDirectory()) + .map(File::getName) + .collect(Collectors.toSet()); + } + + public Set listFilesUsingFileWalk(String dir, int depth) throws IOException { + try (Stream stream = Files.walk(Paths.get(dir), depth)) { + return stream.filter(file -> !Files.isDirectory(file)) + .map(Path::getFileName) + .map(Path::toString) + .collect(Collectors.toSet()); + } + } + + public Set listFilesUsingFileWalkAndVisitor(String dir) throws IOException { + Set fileList = new HashSet<>(); + Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (!Files.isDirectory(file)) { + fileList.add(file.getFileName() + .toString()); + } + return FileVisitResult.CONTINUE; + } + }); + return fileList; + } + + public Set listFilesUsingDirectoryStream(String dir) throws IOException { + Set fileList = new HashSet<>(); + try (DirectoryStream stream = Files.newDirectoryStream(Paths.get(dir))) { + for (Path path : stream) { + if (!Files.isDirectory(path)) { + fileList.add(path.getFileName() + .toString()); + } + } + } + return fileList; + } + +} diff --git a/core-java-io/src/test/java/com/baeldung/file/ListFilesUnitTest.java b/core-java-io/src/test/java/com/baeldung/file/ListFilesUnitTest.java new file mode 100644 index 0000000000..65710121cc --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/file/ListFilesUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.file; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +import com.baeldung.files.ListFiles; + +public class ListFilesUnitTest { + + private ListFiles listFiles = new ListFiles(); + private String DIRECTORY = "src/test/resources/listFilesUnitTestFolder"; + private static final int DEPTH = 1; + private Set EXPECTED_FILE_LIST = new HashSet() { + { + add("test.xml"); + add("employee.json"); + add("students.json"); + add("country.txt"); + } + }; + + @Test + public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException { + assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY)); + } + + @Test + public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException { + assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH)); + } + + @Test + public void givenDir_whenWalkingTreeWithVisitor_thenListAllFiles() throws IOException { + assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalkAndVisitor(DIRECTORY)); + } + + @Test + public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException { + assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingDirectoryStream(DIRECTORY)); + } +} diff --git a/core-java-io/src/test/resources/listFilesUnitTestFolder/country.txt b/core-java-io/src/test/resources/listFilesUnitTestFolder/country.txt new file mode 100644 index 0000000000..45bfe896dc --- /dev/null +++ b/core-java-io/src/test/resources/listFilesUnitTestFolder/country.txt @@ -0,0 +1 @@ +This is a sample txt file for unit test ListFilesUnitTest \ No newline at end of file diff --git a/core-java-io/src/test/resources/listFilesUnitTestFolder/employee.json b/core-java-io/src/test/resources/listFilesUnitTestFolder/employee.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/core-java-io/src/test/resources/listFilesUnitTestFolder/employee.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/core-java-io/src/test/resources/listFilesUnitTestFolder/students.json b/core-java-io/src/test/resources/listFilesUnitTestFolder/students.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/core-java-io/src/test/resources/listFilesUnitTestFolder/students.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/core-java-io/src/test/resources/listFilesUnitTestFolder/test.xml b/core-java-io/src/test/resources/listFilesUnitTestFolder/test.xml new file mode 100644 index 0000000000..19b16cc72c --- /dev/null +++ b/core-java-io/src/test/resources/listFilesUnitTestFolder/test.xml @@ -0,0 +1 @@ + \ No newline at end of file From 2a308c51cb3c68635a1510190528fdbd168a51c1 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 27 Jan 2019 10:34:13 +0400 Subject: [PATCH 28/72] suggested refactor --- .../main/java/com/baeldung/string/MatchWords.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings/src/main/java/com/baeldung/string/MatchWords.java index 4baaa49227..0cad52c320 100644 --- a/java-strings/src/main/java/com/baeldung/string/MatchWords.java +++ b/java-strings/src/main/java/com/baeldung/string/MatchWords.java @@ -15,8 +15,7 @@ public class MatchWords { public static boolean containsWordsIndexOf(String inputString, String[] words) { boolean found = true; for (String word : words) { - int index = inputString.indexOf(word); - if (index == -1) { + if (inputString.indexOf(word) == -1) { found = false; break; } @@ -64,21 +63,19 @@ public class MatchWords { } Pattern pattern = Pattern.compile(regexp.toString()); - if (pattern.matcher(inputString).find()) { - return true; - } - return false; + + return pattern.matcher(inputString).find(); } public static boolean containsWordsJava8(String inputString, String[] words) { - List inputStringList = Arrays.asList(inputString.split(" ")); + List inputStringList = Arrays.asList(inputString.split(" ")); List wordsList = Arrays.asList(words); return wordsList.stream().allMatch(inputStringList::contains); } public static boolean containsWordsArray(String inputString, String[] words) { - List inputStringList = Arrays.asList(inputString.split(" ")); + List inputStringList = Arrays.asList(inputString.split(" ")); List wordsList = Arrays.asList(words); return inputStringList.containsAll(wordsList); From 4bd87241ce8cc99f98446b3703cb8ddfba9c2dca Mon Sep 17 00:00:00 2001 From: rodolforfq <31481067+rodolforfq@users.noreply.github.com> Date: Sun, 27 Jan 2019 02:38:38 -0400 Subject: [PATCH 29/72] BAEL-2524 (#6206) * BAEL-2524 Uploading article examples. * Fixing build error Used List.of, which is not available on java 8 (running java 11 on my PC) --- .../java8/lambda/methodreference/Bicycle.java | 29 ++++++++ .../methodreference/BicycleComparator.java | 13 ++++ .../MethodReferenceExamples.java | 70 +++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java create mode 100644 core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java create mode 100644 core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java new file mode 100644 index 0000000000..760a24d7c2 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java @@ -0,0 +1,29 @@ +package com.baeldung.java8.lambda.methodreference; + +public class Bicycle { + + private String brand; + private Integer frameSize; + + public Bicycle(String brand, Integer frameSize) { + this.brand = brand; + this.frameSize = frameSize; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + public Integer getFrameSize() { + return frameSize; + } + + public void setFrameSize(Integer frameSize) { + this.frameSize = frameSize; + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java new file mode 100644 index 0000000000..153a7d105a --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java @@ -0,0 +1,13 @@ +package com.baeldung.java8.lambda.methodreference; + +import java.util.Comparator; + +public class BicycleComparator implements Comparator { + + @Override + public int compare(Bicycle a, Bicycle b) { + return a.getFrameSize() + .compareTo(b.getFrameSize()); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java new file mode 100644 index 0000000000..3b9a5ec6ff --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java @@ -0,0 +1,70 @@ +package com.baeldung.java8.lambda.methodreference; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.BiFunction; + +import org.junit.Test; + +public class MethodReferenceExamples { + + private static void doNothingAtAll(Object... o) { + } + + ; + + @Test + public void referenceToStaticMethod() { + List messages = Arrays.asList("Hello", "Baeldung", "readers!"); + messages.forEach((word) -> { + System.out.println(word); + }); + messages.forEach(System.out::println); + } + + @Test + public void referenceToInstanceMethodOfParticularObject() { + BicycleComparator bikeFrameSizeComparator = new BicycleComparator(); + createBicyclesList().stream() + .sorted((a, b) -> bikeFrameSizeComparator.compare(a, b)); + createBicyclesList().stream() + .sorted(bikeFrameSizeComparator::compare); + } + + @Test + public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() { + List numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18); + numbers.stream() + .sorted((a, b) -> Integer.compare(a, b)); + numbers.stream() + .sorted(Integer::compare); + } + + @Test + public void referenceToConstructor() { + BiFunction bikeCreator = (brand, frameSize) -> new Bicycle(brand, frameSize); + BiFunction bikeCreatorMethodReference = Bicycle::new; + List bikes = new ArrayList<>(); + bikes.add(bikeCreator.apply("Giant", 50)); + bikes.add(bikeCreator.apply("Scott", 20)); + bikes.add(bikeCreatorMethodReference.apply("Trek", 35)); + bikes.add(bikeCreatorMethodReference.apply("GT", 40)); + } + + @Test + public void limitationsAndAdditionalExamples() { + createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize())); + createBicyclesList().forEach((o) -> this.doNothingAtAll(o)); + } + + private List createBicyclesList() { + List bikes = new ArrayList<>(); + bikes.add(new Bicycle("Giant", 50)); + bikes.add(new Bicycle("Scott", 20)); + bikes.add(new Bicycle("Trek", 35)); + bikes.add(new Bicycle("GT", 40)); + return bikes; + } + +} From 8ccec9a413ee3e36eb73d0d1e2294596b2b3681f Mon Sep 17 00:00:00 2001 From: pcoates33 Date: Sun, 27 Jan 2019 06:55:25 +0000 Subject: [PATCH 30/72] BAEL-2510 Add nested properties section (#6212) Add nested properties section to ConfigurationProperties article. --- .../baeldung/properties/ConfigProperties.java | 62 +++++-------------- .../org/baeldung/properties/Credentials.java | 37 +++++++++++ .../src/main/resources/configprops.properties | 2 +- .../ConfigPropertiesIntegrationTest.java | 31 +++++++--- .../resources/configprops-test.properties | 2 +- 5 files changed, 75 insertions(+), 59 deletions(-) create mode 100644 spring-boot/src/main/java/org/baeldung/properties/Credentials.java diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java index 2d3e56100c..3698d8ef30 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java @@ -8,7 +8,6 @@ import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; -import org.hibernate.validator.constraints.Length; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @@ -20,41 +19,8 @@ import org.springframework.validation.annotation.Validated; @Validated public class ConfigProperties { - @Validated - public static class Credentials { - - @Length(max = 4, min = 1) - private String authMethod; - private String username; - private String password; - - public String getAuthMethod() { - return authMethod; - } - - public void setAuthMethod(String authMethod) { - this.authMethod = authMethod; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - } - @NotBlank - private String host; + private String hostName; @Min(1025) @Max(65536) @@ -63,16 +29,16 @@ public class ConfigProperties { @Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$") private String from; - private Credentials credentials; private List defaultRecipients; private Map additionalHeaders; + private Credentials credentials; - public String getHost() { - return host; + public String getHostName() { + return hostName; } - public void setHost(String host) { - this.host = host; + public void setHostName(String hostName) { + this.hostName = hostName; } public int getPort() { @@ -91,14 +57,6 @@ public class ConfigProperties { this.from = from; } - public Credentials getCredentials() { - return credentials; - } - - public void setCredentials(Credentials credentials) { - this.credentials = credentials; - } - public List getDefaultRecipients() { return defaultRecipients; } @@ -114,4 +72,12 @@ public class ConfigProperties { public void setAdditionalHeaders(Map additionalHeaders) { this.additionalHeaders = additionalHeaders; } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } } diff --git a/spring-boot/src/main/java/org/baeldung/properties/Credentials.java b/spring-boot/src/main/java/org/baeldung/properties/Credentials.java new file mode 100644 index 0000000000..2d8ac76e62 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/Credentials.java @@ -0,0 +1,37 @@ +package org.baeldung.properties; + +import org.hibernate.validator.constraints.Length; +import org.springframework.validation.annotation.Validated; + +@Validated +public class Credentials { + + @Length(max = 4, min = 1) + private String authMethod; + private String username; + private String password; + + public String getAuthMethod() { + return authMethod; + } + + public void setAuthMethod(String authMethod) { + this.authMethod = authMethod; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/spring-boot/src/main/resources/configprops.properties b/spring-boot/src/main/resources/configprops.properties index e5d9ae621d..2dad11f9cc 100644 --- a/spring-boot/src/main/resources/configprops.properties +++ b/spring-boot/src/main/resources/configprops.properties @@ -1,5 +1,5 @@ #Simple properties -mail.host=mailer@mail.com +mail.hostname=host@mail.com mail.port=9000 mail.from=mailer@mail.com diff --git a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java index 3f3b558db9..4ba6bf29d8 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -1,5 +1,8 @@ package org.baeldung.properties; +import java.util.List; +import java.util.Map; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,26 +21,36 @@ public class ConfigPropertiesIntegrationTest { @Test public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception { - Assert.assertTrue("From address is read as null!", properties.getFrom() != null); + Assert.assertEquals("Incorrectly bound hostName property", "host@mail.com", properties.getHostName()); + Assert.assertEquals("Incorrectly bound port property", 9000, properties.getPort()); + Assert.assertEquals("Incorrectly bound from property", "mailer@mail.com", properties.getFrom()); } @Test public void whenListPropertyQueriedthenReturnsProperty() throws Exception { - Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2); - Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2); + List defaultRecipients = properties.getDefaultRecipients(); + Assert.assertTrue("Couldn't bind list property!", defaultRecipients.size() == 2); + Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", defaultRecipients.size() == 2); + Assert.assertEquals("Incorrectly bound list[0] property", "admin@mail.com", defaultRecipients.get(0)); + Assert.assertEquals("Incorrectly bound list[1] property", "owner@mail.com", defaultRecipients.get(1)); } @Test public void whenMapPropertyQueriedthenReturnsProperty() throws Exception { - Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null); - Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3); + Map additionalHeaders = properties.getAdditionalHeaders(); + Assert.assertTrue("Couldn't bind map property!", additionalHeaders != null); + Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", additionalHeaders.size() == 3); + Assert.assertEquals("Incorrectly bound map[redelivery] property", "true", additionalHeaders.get("redelivery")); + Assert.assertEquals("Incorrectly bound map[secure] property", "true", additionalHeaders.get("secure")); + Assert.assertEquals("Incorrectly bound map[p3] property", "value", additionalHeaders.get("p3")); } @Test public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception { - Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1")); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john")); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password")); + Credentials credentials = properties.getCredentials(); + Assert.assertTrue("Couldn't bind map property!", credentials != null); + Assert.assertEquals("Incorrectly bound object property, authMethod", "SHA1", credentials.getAuthMethod()); + Assert.assertEquals("Incorrectly bound object property, username", "john", credentials.getUsername()); + Assert.assertEquals("Incorrectly bound object property, password", "password", credentials.getPassword()); } } diff --git a/spring-boot/src/test/resources/configprops-test.properties b/spring-boot/src/test/resources/configprops-test.properties index b27cf2107a..697771ae6e 100644 --- a/spring-boot/src/test/resources/configprops-test.properties +++ b/spring-boot/src/test/resources/configprops-test.properties @@ -1,5 +1,5 @@ #Simple properties -mail.host=mailer@mail.com +mail.hostname=host@mail.com mail.port=9000 mail.from=mailer@mail.com From 2e733c38675d49f250861cae91166d5c4b18495b Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 27 Jan 2019 14:25:36 +0200 Subject: [PATCH 31/72] minor formatting cleanup --- .../java/com/baeldung/config/DbConfig.java | 16 +++--- .../java/com/baeldung/config/MvcConfig.java | 8 +-- .../java/com/baeldung/config/RestConfig.java | 5 +- .../config/ValidatorEventRegister.java | 8 +-- .../baeldung/events/AuthorEventHandler.java | 49 +++++++++--------- .../com/baeldung/events/BookEventHandler.java | 23 +++++---- .../RestResponseEntityExceptionHandler.java | 7 +-- .../java/com/baeldung/models/Address.java | 2 +- .../main/java/com/baeldung/models/Author.java | 2 +- .../main/java/com/baeldung/models/Book.java | 7 ++- .../java/com/baeldung/models/Library.java | 2 +- .../java/com/baeldung/models/Subject.java | 2 +- .../com/baeldung/projections/CustomBook.java | 10 ++-- .../baeldung/repositories/BookRepository.java | 3 +- .../repositories/SubjectRepository.java | 4 +- .../events/AuthorEventHandlerUnitTest.java | 28 +++++------ .../events/BookEventHandlerUnitTest.java | 28 +++++------ .../SpringDataProjectionLiveTest.java | 50 +++++++++---------- 18 files changed, 122 insertions(+), 132 deletions(-) diff --git a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java index 05fa27bbff..3ca728ec94 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java @@ -20,7 +20,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; // @PropertySource("persistence-h2.properties") // @PropertySource("persistence-hsqldb.properties") // @PropertySource("persistence-derby.properties") -//@PropertySource("persistence-sqlite.properties") +// @PropertySource("persistence-sqlite.properties") public class DbConfig { @Autowired @@ -65,21 +65,23 @@ public class DbConfig { @Configuration @Profile("h2") @PropertySource("classpath:persistence-h2.properties") -class H2Config {} +class H2Config { +} @Configuration @Profile("hsqldb") @PropertySource("classpath:persistence-hsqldb.properties") -class HsqldbConfig {} - +class HsqldbConfig { +} @Configuration @Profile("derby") @PropertySource("classpath:persistence-derby.properties") -class DerbyConfig {} - +class DerbyConfig { +} @Configuration @Profile("sqlite") @PropertySource("classpath:persistence-sqlite.properties") -class SqliteConfig {} +class SqliteConfig { +} diff --git a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java index e5748f2f55..9d0d3a6687 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java @@ -11,11 +11,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig(){ + + public MvcConfig() { super(); } - + @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); @@ -27,7 +27,7 @@ public class MvcConfig implements WebMvcConfigurer { } @Bean - BookEventHandler bookEventHandler(){ + BookEventHandler bookEventHandler() { return new BookEventHandler(); } diff --git a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java index 39f90e867b..47cb95693b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java @@ -12,10 +12,9 @@ import org.springframework.http.HttpMethod; public class RestConfig implements RepositoryRestConfigurer { @Override - public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration){ + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration) { repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class); ExposureConfiguration config = repositoryRestConfiguration.getExposureConfiguration(); - config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> - httpMethods.disable(HttpMethod.PATCH)); + config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> httpMethods.disable(HttpMethod.PATCH)); } } diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java index 8f14d6c1c6..632ad9183a 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java @@ -24,13 +24,7 @@ public class ValidatorEventRegister implements InitializingBean { List events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); for (Map.Entry entry : validators.entrySet()) { - events - .stream() - .filter(p -> entry - .getKey() - .startsWith(p)) - .findFirst() - .ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); + events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); } } } diff --git a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java index 5a8ae05c08..485dc8e221 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java @@ -8,33 +8,34 @@ import java.util.logging.Logger; @RepositoryEventHandler public class AuthorEventHandler { - Logger logger = Logger.getLogger("Class AuthorEventHandler"); - public AuthorEventHandler(){ - super(); - } + Logger logger = Logger.getLogger("Class AuthorEventHandler"); - @HandleBeforeCreate - public void handleAuthorBeforeCreate(Author author){ - logger.info("Inside Author Before Create...."); - String name = author.getName(); - } + public AuthorEventHandler() { + super(); + } - @HandleAfterCreate - public void handleAuthorAfterCreate(Author author){ - logger.info("Inside Author After Create ...."); - String name = author.getName(); - } + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author) { + logger.info("Inside Author Before Create...."); + String name = author.getName(); + } - @HandleBeforeDelete - public void handleAuthorBeforeDelete(Author author){ - logger.info("Inside Author Before Delete ...."); - String name = author.getName(); - } + @HandleAfterCreate + public void handleAuthorAfterCreate(Author author) { + logger.info("Inside Author After Create ...."); + String name = author.getName(); + } - @HandleAfterDelete - public void handleAuthorAfterDelete(Author author){ - logger.info("Inside Author After Delete ...."); - String name = author.getName(); - } + @HandleBeforeDelete + public void handleAuthorBeforeDelete(Author author) { + logger.info("Inside Author Before Delete ...."); + String name = author.getName(); + } + + @HandleAfterDelete + public void handleAuthorAfterDelete(Author author) { + logger.info("Inside Author After Delete ...."); + String name = author.getName(); + } } diff --git a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java index 3953e6ce0d..36ae62b926 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java @@ -10,17 +10,18 @@ import org.springframework.data.rest.core.annotation.RepositoryEventHandler; @RepositoryEventHandler public class BookEventHandler { - Logger logger = Logger.getLogger("Class BookEventHandler"); - @HandleBeforeCreate - public void handleBookBeforeCreate(Book book){ + Logger logger = Logger.getLogger("Class BookEventHandler"); - logger.info("Inside Book Before Create ...."); - book.getAuthors(); - } + @HandleBeforeCreate + public void handleBookBeforeCreate(Book book) { - @HandleBeforeCreate - public void handleAuthorBeforeCreate(Author author){ - logger.info("Inside Author Before Create ...."); - author.getBooks(); - } + logger.info("Inside Book Before Create ...."); + book.getAuthors(); + } + + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author) { + logger.info("Inside Author Before Create ...."); + author.getBooks(); + } } diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java index aa24fccac7..a3ef91f6d6 100644 --- a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java @@ -19,12 +19,7 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; - String errors = nevEx - .getErrors() - .getAllErrors() - .stream() - .map(ObjectError::toString) - .collect(Collectors.joining("\n")); + String errors = nevEx.getErrors().getAllErrors().stream().map(ObjectError::toString).collect(Collectors.joining("\n")); return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); } diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Address.java b/spring-data-rest/src/main/java/com/baeldung/models/Address.java index 82e3783f3e..713af58ae6 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Address.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Address.java @@ -11,7 +11,7 @@ import javax.persistence.OneToOne; public class Address { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Author.java b/spring-data-rest/src/main/java/com/baeldung/models/Author.java index cdd04cbdcf..3f43af9c47 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Author.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Author.java @@ -16,7 +16,7 @@ import javax.persistence.ManyToMany; public class Author { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Book.java b/spring-data-rest/src/main/java/com/baeldung/models/Book.java index 002a64e738..07b0d08b84 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Book.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Book.java @@ -16,14 +16,14 @@ import javax.persistence.ManyToOne; public class Book { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String title; - + private String isbn; - + @ManyToOne @JoinColumn(name = "library_id") private Library library; @@ -63,7 +63,6 @@ public class Book { this.isbn = isbn; } - public Library getLibrary() { return library; } diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Library.java b/spring-data-rest/src/main/java/com/baeldung/models/Library.java index c27512d0e4..091975f5d0 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Library.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Library.java @@ -17,7 +17,7 @@ import org.springframework.data.rest.core.annotation.RestResource; public class Library { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java b/spring-data-rest/src/main/java/com/baeldung/models/Subject.java index b3b9a5b0a0..4e5fa82148 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Subject.java @@ -10,7 +10,7 @@ import javax.persistence.Id; public class Subject { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) diff --git a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java b/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java index 1cd9c01383..3dc6938f5c 100644 --- a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java +++ b/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java @@ -8,15 +8,15 @@ import org.springframework.data.rest.core.config.Projection; import com.baeldung.models.Author; import com.baeldung.models.Book; -@Projection(name = "customBook", types = { Book.class }) +@Projection(name = "customBook", types = { Book.class }) public interface CustomBook { @Value("#{target.id}") - long getId(); - + long getId(); + String getTitle(); - + List getAuthors(); - + @Value("#{target.getAuthors().size()}") int getAuthorCount(); } diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java b/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java index 34019a9d91..eee44f35d4 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java @@ -7,4 +7,5 @@ import com.baeldung.models.Book; import com.baeldung.projections.CustomBook; @RepositoryRestResource(excerptProjection = CustomBook.class) -public interface BookRepository extends CrudRepository {} +public interface BookRepository extends CrudRepository { +} diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java b/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java index a91ae2d505..76e34b0799 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java @@ -8,8 +8,8 @@ import org.springframework.data.rest.core.annotation.RestResource; import com.baeldung.models.Subject; public interface SubjectRepository extends PagingAndSortingRepository { - + @RestResource(path = "nameContains") public Page findByNameContaining(@Param("name") String name, Pageable p); - + } \ No newline at end of file diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java index 6db536c40c..c01d5882a0 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java @@ -9,21 +9,21 @@ import static org.mockito.Mockito.mock; public class AuthorEventHandlerUnitTest { - @Test - public void whenCreateAuthorThenSuccess() { - Author author = mock(Author.class); - AuthorEventHandler authorEventHandler = new AuthorEventHandler(); - authorEventHandler.handleAuthorBeforeCreate(author); - Mockito.verify(author,Mockito.times(1)).getName(); + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author, Mockito.times(1)).getName(); - } + } - @Test - public void whenDeleteAuthorThenSuccess() { - Author author = mock(Author.class); - AuthorEventHandler authorEventHandler = new AuthorEventHandler(); - authorEventHandler.handleAuthorAfterDelete(author); - Mockito.verify(author,Mockito.times(1)).getName(); + @Test + public void whenDeleteAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorAfterDelete(author); + Mockito.verify(author, Mockito.times(1)).getName(); - } + } } diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java index 28f0b91e1c..d6b8b3b25e 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java @@ -8,21 +8,21 @@ import org.mockito.Mockito; import static org.mockito.Mockito.mock; public class BookEventHandlerUnitTest { - @Test - public void whenCreateBookThenSuccess() { - Book book = mock(Book.class); - BookEventHandler bookEventHandler = new BookEventHandler(); - bookEventHandler.handleBookBeforeCreate(book); - Mockito.verify(book,Mockito.times(1)).getAuthors(); + @Test + public void whenCreateBookThenSuccess() { + Book book = mock(Book.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleBookBeforeCreate(book); + Mockito.verify(book, Mockito.times(1)).getAuthors(); - } + } - @Test - public void whenCreateAuthorThenSuccess() { - Author author = mock(Author.class); - BookEventHandler bookEventHandler = new BookEventHandler(); - bookEventHandler.handleAuthorBeforeCreate(author); - Mockito.verify(author,Mockito.times(1)).getBooks(); + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author, Mockito.times(1)).getBooks(); - } + } } diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java index 702c1521da..ad219ccd53 100644 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java @@ -29,16 +29,15 @@ public class SpringDataProjectionLiveTest { private static final String BOOK_ENDPOINT = "http://localhost:8080/books"; private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors"; - @Autowired private BookRepository bookRepo; @Autowired private AuthorRepository authorRepo; - + @Before - public void setup(){ - if(bookRepo.findById(1L) == null){ + public void setup() { + if (bookRepo.findById(1L) == null) { Book book = new Book("Animal Farm"); book.setIsbn("978-1943138425"); book = bookRepo.save(book); @@ -48,45 +47,44 @@ public class SpringDataProjectionLiveTest { author = authorRepo.save(author); } } - + @Test - public void whenGetBook_thenOK(){ - final Response response = RestAssured.get(BOOK_ENDPOINT+"/1"); - + public void whenGetBook_thenOK() { + final Response response = RestAssured.get(BOOK_ENDPOINT + "/1"); + assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("isbn")); assertFalse(response.asString().contains("authorCount")); -// System.out.println(response.asString()); + // System.out.println(response.asString()); } - - + @Test - public void whenGetBookProjection_thenOK(){ - final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook"); - + public void whenGetBookProjection_thenOK() { + final Response response = RestAssured.get(BOOK_ENDPOINT + "/1?projection=customBook"); + assertEquals(200, response.getStatusCode()); assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); -// System.out.println(response.asString()); + assertTrue(response.asString().contains("authorCount")); + // System.out.println(response.asString()); } - + @Test - public void whenGetAllBooks_thenOK(){ + public void whenGetAllBooks_thenOK() { final Response response = RestAssured.get(BOOK_ENDPOINT); - + assertEquals(200, response.getStatusCode()); assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); - // System.out.println(response.asString()); + assertTrue(response.asString().contains("authorCount")); + // System.out.println(response.asString()); } - + @Test - public void whenGetAuthorBooks_thenOK(){ - final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books"); - + public void whenGetAuthorBooks_thenOK() { + final Response response = RestAssured.get(AUTHOR_ENDPOINT + "/1/books"); + assertEquals(200, response.getStatusCode()); assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); + assertTrue(response.asString().contains("authorCount")); System.out.println(response.asString()); } } From 2e8d2a7c1e6d827263b3c380e93a49fbb63a59b5 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:08:16 +0200 Subject: [PATCH 32/72] Update README.md --- lombok/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lombok/README.md b/lombok/README.md index bd6282fd18..e3d08d4e26 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -5,3 +5,5 @@ - [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance) - [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value) - [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-custom-setter) +- [Setting up Lombok with Eclipse and Intellij](https://www.baeldung.com/lombok-ide) + From aed3e8f829d418a90afea6d659123afed0dd9e4c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:09:00 +0200 Subject: [PATCH 33/72] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 5aee69d9a9..d6cb619ed3 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -46,3 +46,4 @@ - [Graphs in Java](https://www.baeldung.com/java-graphs) - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) +- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) From 79f1babc26b4d96686e1815d4437d0c5f3f0c65f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:09:46 +0200 Subject: [PATCH 34/72] Update README.md --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 2eea5e60b4..5fe119cca4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -4,3 +4,4 @@ - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) - [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) +- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) From 639e0046d7ef36502edffff27be8a88b7d2d1ad4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:10:33 +0200 Subject: [PATCH 35/72] Update README.md --- core-java-io/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-io/README.md b/core-java-io/README.md index 2ad980ca6a..fcb3302a48 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -36,4 +36,5 @@ - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) - [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) - [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) -- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) \ No newline at end of file +- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) +- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) From 242dc1dbcee7394319af5eafb91b209fe39421fc Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:11:21 +0200 Subject: [PATCH 36/72] Update README.md --- persistence-modules/hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 03bdd9b759..a4e95a9062 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -29,3 +29,4 @@ - [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) From 8a3d3f934402b3409b3392edfccff8b4f1ad8a5e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:12:01 +0200 Subject: [PATCH 37/72] Update README.md --- java-streams/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-streams/README.md b/java-streams/README.md index 33ca2619a8..f2afd570f6 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -15,3 +15,4 @@ - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) - [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) +- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) From fd70f654b54e3ac59a9477809aed14c833ec15fa Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 27 Jan 2019 17:45:34 +0400 Subject: [PATCH 38/72] primitive list collections --- .../list/primitive/PrimitiveCollections.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 5a8ddc0acd..50f372e9c9 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -2,6 +2,8 @@ package com.baeldung.list.primitive; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; +import gnu.trove.list.array.TIntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.Arrays; import java.util.List; @@ -13,6 +15,18 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; guavaPrimitives(primitives); + + TIntArrayList tList = new TIntArrayList(primitives); + + cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives); + + IntArrayList fastUtilList = new IntArrayList(primitives); + + System.out.println(tList); + + System.out.println(coltList); + + System.out.println(fastUtilList); } From 4845bd82a17f61db82e48e68937fb1887c4eb533 Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Sun, 27 Jan 2019 14:18:13 +0000 Subject: [PATCH 39/72] added solid code (#6226) --- patterns/principles/solid/pom.xml | 23 ++++++++++++++++ .../main/java/com/baeldung/d/Keyboard.java | 4 +++ .../src/main/java/com/baeldung/d/Monitor.java | 6 +++++ .../java/com/baeldung/d/Windows98Machine.java | 15 +++++++++++ .../com/baeldung/d/Windows98MachineDI.java | 12 +++++++++ .../main/java/com/baeldung/i/BearCarer.java | 12 +++++++++ .../main/java/com/baeldung/i/BearCleaner.java | 5 ++++ .../main/java/com/baeldung/i/BearFeeder.java | 5 ++++ .../main/java/com/baeldung/i/BearKeeper.java | 9 +++++++ .../main/java/com/baeldung/i/BearPetter.java | 5 ++++ .../main/java/com/baeldung/i/CrazyPerson.java | 8 ++++++ .../src/main/java/com/baeldung/l/Car.java | 8 ++++++ .../main/java/com/baeldung/l/ElectricCar.java | 12 +++++++++ .../src/main/java/com/baeldung/l/Engine.java | 13 +++++++++ .../main/java/com/baeldung/l/MotorCar.java | 18 +++++++++++++ .../src/main/java/com/baeldung/o/Guitar.java | 10 +++++++ .../baeldung/o/SuperCoolGuitarWithFlames.java | 9 +++++++ .../src/main/java/com/baeldung/s/BadBook.java | 27 +++++++++++++++++++ .../main/java/com/baeldung/s/BookPrinter.java | 13 +++++++++ .../main/java/com/baeldung/s/GoodBook.java | 20 ++++++++++++++ 20 files changed, 234 insertions(+) create mode 100644 patterns/principles/solid/pom.xml create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/l/Car.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java create mode 100644 patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java diff --git a/patterns/principles/solid/pom.xml b/patterns/principles/solid/pom.xml new file mode 100644 index 0000000000..825c7730a5 --- /dev/null +++ b/patterns/principles/solid/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + com.baeldung + solid/artifactId> + 1.0-SNAPSHOT + + + + + + junit + junit + 4.12 + test + + + + + diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java b/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java new file mode 100644 index 0000000000..acb50cedb4 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java @@ -0,0 +1,4 @@ +package com.baeldung.d; + +public class Keyboard { +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java b/patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java new file mode 100644 index 0000000000..c0ab7a53b2 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java @@ -0,0 +1,6 @@ +package com.baeldung.d; + +public class Monitor { + + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java b/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java new file mode 100644 index 0000000000..a9f130aedb --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java @@ -0,0 +1,15 @@ +package com.baeldung.d; + +public class Windows98Machine { + + private final Keyboard keyboard; + private final Monitor monitor; + + public Windows98Machine() { + + monitor = new Monitor(); + keyboard = new Keyboard(); + + } + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java b/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java new file mode 100644 index 0000000000..2a6fd74a41 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java @@ -0,0 +1,12 @@ +package com.baeldung.d; + +public class Windows98MachineDI { + + private final Keyboard keyboard; + private final Monitor monitor; + + public Windows98MachineDI(Keyboard keyboard, Monitor monitor) { + this.keyboard = keyboard; + this.monitor = monitor; + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java b/patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java new file mode 100644 index 0000000000..3d69211674 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java @@ -0,0 +1,12 @@ +package com.baeldung.i; + +public class BearCarer implements BearCleaner, BearFeeder { + + public void washTheBear() { + //I think we missed a spot.. + } + + public void feedTheBear() { + //Tuna tuesdays.. + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java b/patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java new file mode 100644 index 0000000000..e2b71b2ce8 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java @@ -0,0 +1,5 @@ +package com.baeldung.i; + +public interface BearCleaner { + void washTheBear(); +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java b/patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java new file mode 100644 index 0000000000..5d0ba7cd29 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java @@ -0,0 +1,5 @@ +package com.baeldung.i; + +public interface BearFeeder { + void feedTheBear(); +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java b/patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java new file mode 100644 index 0000000000..f09774a5ff --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java @@ -0,0 +1,9 @@ +package com.baeldung.i; + +public interface BearKeeper { + + void washTheBear(); + void feedTheBear(); + void petTheBear(); + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java b/patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java new file mode 100644 index 0000000000..a913cf3d8a --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java @@ -0,0 +1,5 @@ +package com.baeldung.i; + +public interface BearPetter { + void petTheBear(); +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java b/patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java new file mode 100644 index 0000000000..aae0d4c11b --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java @@ -0,0 +1,8 @@ +package com.baeldung.i; + +public class CrazyPerson implements BearPetter { + + public void petTheBear() { + //Good luck with that! + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/Car.java b/patterns/principles/solid/src/main/java/com/baeldung/l/Car.java new file mode 100644 index 0000000000..b3481f894a --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/l/Car.java @@ -0,0 +1,8 @@ +package com.baeldung.l; + +public interface Car { + + void turnOnEngine(); + void accelerate(); + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java b/patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java new file mode 100644 index 0000000000..fd919c5659 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java @@ -0,0 +1,12 @@ +package com.baeldung.l; + +public class ElectricCar implements Car { + + public void turnOnEngine() { + throw new AssertionError("I don't have an engine!"); + } + + public void accelerate() { + //this acceleration is crazy! + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java b/patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java new file mode 100644 index 0000000000..a8e38b8877 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java @@ -0,0 +1,13 @@ +package com.baeldung.l; + +public class Engine { + + public void on(){ + //vroom. + } + + public void powerOn(int amount){ + //do something + } + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java b/patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java new file mode 100644 index 0000000000..638f315475 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java @@ -0,0 +1,18 @@ +package com.baeldung.l; + +public class MotorCar implements Car { + + private Engine engine; + + //Constructors, getters + setters + + public void turnOnEngine() { + //turn on the engine! + engine.on(); + } + + public void accelerate() { + //move forward! + engine.powerOn(1000); + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java b/patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java new file mode 100644 index 0000000000..baab006b5b --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java @@ -0,0 +1,10 @@ +package com.baeldung.o; + +public class Guitar { + + private String make; + private String model; + private int volume; + + //Constructors, getters & setters +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java b/patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java new file mode 100644 index 0000000000..b69e3be74a --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java @@ -0,0 +1,9 @@ +package com.baeldung.o; + +public class SuperCoolGuitarWithFlames extends Guitar { + + private String flameColour; + + //constructor, getters + setters + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java b/patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java new file mode 100644 index 0000000000..03c8fcd488 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java @@ -0,0 +1,27 @@ +package com.baeldung.s; + +public class BadBook { + + private String name; + private String author; + private String text; + + //constructor, getters and setters + + + //methods that directly relate to the book properties + public String replaceWordInText(String word){ + return text.replaceAll(word, text); + } + + public boolean isWordInText(String word){ + return text.contains(word); + } + + //methods for outputting text to console - should this really be here? + void printTextToConsole(){ + //our code for formatting and printing the text + } + + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java b/patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java new file mode 100644 index 0000000000..0c8ef62e01 --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java @@ -0,0 +1,13 @@ +package com.baeldung.s; + +public class BookPrinter { + + //methods for outputting text + void printTextToConsole(String text){ + //our code for formatting and printing the text + } + + void printTextToAnotherMedium(String text){ + //code for writing to any other location.. + } +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java b/patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java new file mode 100644 index 0000000000..b0993aca2b --- /dev/null +++ b/patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java @@ -0,0 +1,20 @@ +package com.baeldung.s; + +public class GoodBook { + + private String name; + private String author; + private String text; + + //constructor, getters and setters + + //methods that directly relate to the book properties + public String replaceWordInText(String word){ + return text.replaceAll(word, text); + } + + public boolean isWordInText(String word){ + return text.contains(word); + } + +} From e67915213a38cf82c0213f617d3c68ec812603b4 Mon Sep 17 00:00:00 2001 From: anuraggoyal1 Date: Sun, 27 Jan 2019 20:42:18 +0530 Subject: [PATCH 40/72] [BAEL-2471] Guide to Apache Commons MultiValuedMap (#6155) * [BAEL-2471] Guide to Apache Commons MultiValuedMap * Update MultiValuedMapUnitTest.java * added empty lines --- .../java/map/MultiValuedMapUnitTest.java | 204 ++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java new file mode 100644 index 0000000000..67e4a5b0a0 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java @@ -0,0 +1,204 @@ +package com.baeldung.java.map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.collections4.MultiMapUtils; +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; +import org.junit.Test; + +public class MultiValuedMapUnitTest { + + @Test + public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("key", "value1"); + map.put("key", "value2"); + map.put("key", "value2"); + + assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + } + + @Test + public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.putAll("key", Arrays.asList("value1", "value2", "value2")); + + assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + } + + @Test + public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + + assertThat((Collection) map.get("key")).containsExactly("value"); + } + + @Test + public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value1"); + map.put("key", "value2"); + + Collection> entries = (Collection>) map.entries(); + + for(Map.Entry entry : entries) { + assertThat(entry.getKey()).contains("key"); + assertTrue(entry.getValue().equals("value1") || entry.getValue().equals("value2") ); + } + } + + @Test + public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertThat(((Collection) map.keys())).contains("key", "key1", "key2"); + } + + @Test + public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertThat((Collection) map.keySet()).contains("key", "key1", "key2"); + } + + @Test + public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + } + + @Test + public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.remove("key"); + + assertThat(((Collection) map.values())).contains("value1", "value2"); + } + + @Test + public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.removeMapping("key", "value"); + + assertThat(((Collection) map.values())).contains("value1", "value2"); + } + + @Test + public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.clear(); + + assertTrue(map.isEmpty()); + } + + @Test + public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertTrue(map.containsKey("key")); + } + + @Test + public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertTrue(map.containsValue("value")); + } + + @Test + public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertFalse(map.isEmpty()); + } + + @Test + public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + assertEquals(3, map.size()); + } + + @Test + public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("key", "value1"); + map.put("key", "value2"); + map.put("key", "value2"); + + assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + } + + @Test + public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { + MultiValuedMap map = new HashSetValuedHashMap<>(); + + map.put("key1", "value1"); + map.put("key1", "value1"); + + assertThat((Collection) map.get("key1")).containsExactly("value1"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key", "value1"); + map.put("key", "value2"); + MultiValuedMap immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); + + immutableMap.put("key", "value3"); + } + + +} From f3faf9234e1d365c8bc9ac4a11316795b4b67b2b Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Mon, 28 Jan 2019 00:27:43 -0300 Subject: [PATCH 41/72] Initial Commit (#6202) --- .../validation/application/Application.java | 27 ++++++++ .../controllers/UserController.java | 52 ++++++++++++++ .../validation/application/entities/User.java | 50 ++++++++++++++ .../repositories/UserRepository.java | 8 +++ .../tests/UserControllerIntegrationTest.java | 69 +++++++++++++++++++ 5 files changed, 206 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/validation/application/Application.java create mode 100644 spring-boot/src/main/java/com/baeldung/validation/application/controllers/UserController.java create mode 100644 spring-boot/src/main/java/com/baeldung/validation/application/entities/User.java create mode 100644 spring-boot/src/main/java/com/baeldung/validation/application/repositories/UserRepository.java create mode 100644 spring-boot/src/test/java/com/baeldung/validation/tests/UserControllerIntegrationTest.java diff --git a/spring-boot/src/main/java/com/baeldung/validation/application/Application.java b/spring-boot/src/main/java/com/baeldung/validation/application/Application.java new file mode 100644 index 0000000000..af8f768193 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/validation/application/Application.java @@ -0,0 +1,27 @@ +package com.baeldung.validation.application; + +import com.baeldung.validation.application.entities.User; +import com.baeldung.validation.application.repositories.UserRepository; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner run(UserRepository userRepository) throws Exception { + return (String[] args) -> { + User user1 = new User("Bob", "bob@domain.com"); + User user2 = new User("Jenny", "jenny@domain.com"); + userRepository.save(user1); + userRepository.save(user2); + userRepository.findAll().forEach(System.out::println); + }; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/validation/application/controllers/UserController.java b/spring-boot/src/main/java/com/baeldung/validation/application/controllers/UserController.java new file mode 100644 index 0000000000..a4aeefb70b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/validation/application/controllers/UserController.java @@ -0,0 +1,52 @@ +package com.baeldung.validation.application.controllers; + +import com.baeldung.validation.application.entities.User; +import com.baeldung.validation.application.repositories.UserRepository; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + private final UserRepository userRepository; + + @Autowired + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping("/users") + public List getUsers() { + return (List) userRepository.findAll(); + } + + @PostMapping("/users") + ResponseEntity addUser(@Valid @RequestBody User user) { + return ResponseEntity.ok("User is valid"); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + public Map handleValidationExceptions(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return errors; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/validation/application/entities/User.java b/spring-boot/src/main/java/com/baeldung/validation/application/entities/User.java new file mode 100644 index 0000000000..529368f132 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/validation/application/entities/User.java @@ -0,0 +1,50 @@ +package com.baeldung.validation.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotBlank; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @NotBlank(message = "Name is mandatory") + private String name; + + @NotBlank(message = "Email is mandatory") + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/validation/application/repositories/UserRepository.java b/spring-boot/src/main/java/com/baeldung/validation/application/repositories/UserRepository.java new file mode 100644 index 0000000000..b579addcaa --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/validation/application/repositories/UserRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.validation.application.repositories; + +import com.baeldung.validation.application.entities.User; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends CrudRepository {} diff --git a/spring-boot/src/test/java/com/baeldung/validation/tests/UserControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/validation/tests/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..265c4ec22c --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/validation/tests/UserControllerIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.validation.tests; + +import com.baeldung.validation.application.controllers.UserController; +import com.baeldung.validation.application.repositories.UserRepository; +import java.nio.charset.Charset; +import static org.assertj.core.api.Assertions.assertThat; +import org.hamcrest.core.Is; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@RunWith(SpringRunner.class) +@WebMvcTest +@AutoConfigureMockMvc +public class UserControllerIntegrationTest { + + @MockBean + private UserRepository userRepository; + + @Autowired + UserController userController; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenUserControllerInjected_thenNotNull() throws Exception { + assertThat(userController).isNotNull(); + } + + @Test + public void whenGetRequestToUsers_thenCorrectResponse() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/users") + .contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8)); + + } + + @Test + public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception { + MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8")); + String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}"; + mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8)); + } + + @Test + public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception { + String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}"; + mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory"))) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8)); + } +} From 13f9b875b8385bf875469d50f8dc7d5fa0aa7a2e Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Mon, 28 Jan 2019 13:17:30 +0530 Subject: [PATCH 42/72] Changes in test file --- .../test/BitwiseOperatorUnitTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java index d8af4b0833..74b8eb6bd2 100644 --- a/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java @@ -10,7 +10,7 @@ public class BitwiseOperatorUnitTest { int value1 = 6; int value2 = 5; int result = value1 & value2; - assertEquals(result, 4); + assertEquals(4, result); } @Test @@ -18,7 +18,7 @@ public class BitwiseOperatorUnitTest { int value1 = 6; int value2 = 5; int result = value1 | value2; - assertEquals(result, 7); + assertEquals(7, result); } @Test @@ -26,7 +26,7 @@ public class BitwiseOperatorUnitTest { int value1 = 6; int value2 = 5; int result = value1 ^ value2; - assertEquals(result, 3); + assertEquals(3 result); } @Test @@ -40,42 +40,42 @@ public class BitwiseOperatorUnitTest { public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() { int value = 12; int rightShift = value >> 2; - assertEquals(rightShift, 3); + assertEquals(3, rightShift); } @Test public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() { int value = -12; int rightShift = value >> 2; - assertEquals(rightShift, -3); + assertEquals(-3, rightShift); } @Test public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() { int value = 12; int leftShift = value << 2; - assertEquals(leftShift, 48); + assertEquals(48, leftShift); } @Test public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() { int value = -12; int leftShift = value << 2; - assertEquals(leftShift, -48); + assertEquals(-48, leftShift); } @Test public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() { int value = 12; int unsignedRightShift = value >>> 2; - assertEquals(unsignedRightShift, 3); + assertEquals(3, unsignedRightShift); } @Test public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() { int value = -12; int unsignedRightShift = value >>> 2; - assertEquals(unsignedRightShift, 1073741821); + assertEquals(1073741821, unsignedRightShift); } } From e5c860192a84df1aee9e06bff059a5fd9cd22b91 Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Mon, 28 Jan 2019 13:28:22 +0530 Subject: [PATCH 43/72] Removed error line from the file --- .../baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java index 74b8eb6bd2..f74e181e36 100644 --- a/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bitwiseoperator/test/BitwiseOperatorUnitTest.java @@ -26,7 +26,7 @@ public class BitwiseOperatorUnitTest { int value1 = 6; int value2 = 5; int result = value1 ^ value2; - assertEquals(3 result); + assertEquals(3, result); } @Test From 44d5be301ce9e69b69f4ef632250f6b8f07cd8c0 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 28 Jan 2019 15:15:05 +0400 Subject: [PATCH 44/72] remove performance test --- .../primitive/PrimitivesListPerformance.java | 76 ------------------- 1 file changed, 76 deletions(-) delete mode 100644 core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java deleted file mode 100644 index f57c8d65a6..0000000000 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.list.primitive; - -import it.unimi.dsi.fastutil.ints.IntArrayList; -import gnu.trove.list.array.TIntArrayList; -import org.openjdk.jmh.annotations.*; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.NANOSECONDS) -@Warmup(iterations = 10) -public class PrimitivesListPerformance { - - @State(Scope.Thread) - public static class Initialize { - - List arrayList = new ArrayList<>(); - TIntArrayList tList = new TIntArrayList(); - cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); - IntArrayList fastUtilList = new IntArrayList(); - - int getValue = 10; - - final int iterations = 100000; - - @Setup(Level.Trial) - public void setUp() { - - for (int i = 0; i < iterations; i++) { - arrayList.add(i); - tList.add(i); - coltList.add(i); - fastUtilList.add(i); - } - - arrayList.add(getValue); - tList.add(getValue); - coltList.add(getValue); - fastUtilList.add(getValue); - } - } - - @Benchmark - public boolean containsArrayList(PrimitivesListPerformance.Initialize state) { - return state.arrayList.contains(state.getValue); - } - - @Benchmark - public boolean containsTIntList(PrimitivesListPerformance.Initialize state) { - return state.tList.contains(state.getValue); - } - - @Benchmark - public boolean containsColtIntList(PrimitivesListPerformance.Initialize state) { - return state.coltList.contains(state.getValue); - } - - @Benchmark - public boolean containsFastUtilIntList(PrimitivesListPerformance.Initialize state) { - return state.fastUtilList.contains(state.getValue); - } - - public static void main(String[] args) throws Exception { - Options options = new OptionsBuilder() - .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) - .forks(1).shouldFailOnError(true) - .shouldDoGC(true) - .jvmArgs("-server").build(); - new Runner(options).run(); - } -} From d944b67c29a56d83ea31603238aa599de7cb212e Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 28 Jan 2019 15:23:01 +0400 Subject: [PATCH 45/72] remove JMH dependency --- core-java-collections-list/pom.xml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml index bc71882683..a7e711088a 100644 --- a/core-java-collections-list/pom.xml +++ b/core-java-collections-list/pom.xml @@ -37,17 +37,6 @@ provided - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator-annprocess.version} - - net.sf.trove4j trove4j @@ -71,7 +60,5 @@ 1.7.0 3.11.1 1.16.12 - 1.19 - 1.19 From bb6c78f07b5b4e35101a59ea3203c1229cc44188 Mon Sep 17 00:00:00 2001 From: cror Date: Mon, 28 Jan 2019 18:20:21 +0100 Subject: [PATCH 46/72] BAEL-2702 fix: typo => failing SpringContextIntegrationTest --- .../src/main/resources/RedirectionWebSecurityConfig.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml index 231b5ab57e..0bb73d68ee 100644 --- a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml @@ -14,7 +14,7 @@ - + @@ -26,4 +26,3 @@ - From 7b9e72e6c97fdcfa3428294c8b98df51e3f972f2 Mon Sep 17 00:00:00 2001 From: cror Date: Mon, 28 Jan 2019 18:58:59 +0100 Subject: [PATCH 47/72] BAEL-2702 fix: added SecuredResourceController to the test context --- .../src/main/resources/RedirectionWebSecurityConfig.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml index 0bb73d68ee..cdee8dab43 100644 --- a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml @@ -15,6 +15,7 @@ + From d5e875a3f04794af04544bff6f8cb18b8c7ea2e8 Mon Sep 17 00:00:00 2001 From: cror Date: Mon, 28 Jan 2019 19:11:36 +0100 Subject: [PATCH 48/72] BAEL-2702 fix: added a NoOpPasswordEncoder to the test context --- .../src/main/resources/RedirectionWebSecurityConfig.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml index cdee8dab43..659347f610 100644 --- a/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml @@ -16,6 +16,7 @@ + From 8f5f12519fc99f8f17848627c333f2f566fad25f Mon Sep 17 00:00:00 2001 From: eric-martin Date: Mon, 28 Jan 2019 20:37:45 -0600 Subject: [PATCH 49/72] BAEL-2328: Using isTrue() and isFalse() for assertions --- .../baeldung/string/MatchWordsUnitTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java index 1c2288068b..385aadaa5d 100644 --- a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java @@ -13,54 +13,54 @@ public class MatchWordsUnitTest { @Test public void givenText_whenCallingStringContains_shouldMatchWords() { final boolean result = MatchWords.containsWords(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingJava8_shouldMatchWords() { final boolean result = MatchWords.containsWordsJava8(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingJava8_shouldNotMatchWords() { final boolean result = MatchWords.containsWordsJava8(wholeInput, words); - assertThat(result).isEqualTo(false); + assertThat(result).isFalse(); } @Test public void givenText_whenCallingPattern_shouldMatchWords() { final boolean result = MatchWords.containsWordsPatternMatch(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingAhoCorasick_shouldMatchWords() { final boolean result = MatchWords.containsWordsAhoCorasick(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingAhoCorasick_shouldNotMatchWords() { final boolean result = MatchWords.containsWordsAhoCorasick(wholeInput, words); - assertThat(result).isEqualTo(false); + assertThat(result).isFalse(); } @Test public void givenText_whenCallingIndexOf_shouldMatchWords() { final boolean result = MatchWords.containsWordsIndexOf(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingArrayList_shouldMatchWords() { final boolean result = MatchWords.containsWordsArray(inputString, words); - assertThat(result).isEqualTo(true); + assertThat(result).isTrue(); } @Test public void givenText_whenCallingArrayList_shouldNotMatchWords() { final boolean result = MatchWords.containsWordsArray(wholeInput, words); - assertThat(result).isEqualTo(false); + assertThat(result).isFalse(); } } From 0b988db96d1fa03768402b81360722d0606114b8 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 17:04:33 -0200 Subject: [PATCH 50/72] Moved Building REST API article related code from spring-rest-full to spring-boot-rest module --- spring-boot-rest/pom.xml | 2 - .../com/baeldung/persistence/IOperations.java | 13 +++++ .../service/common/AbstractService.java | 34 ++++++++++++- .../persistence/service/impl/FooService.java | 11 +++++ .../web/controller/FooController.java | 48 +++++++++++++++---- .../event/SingleResourceRetrievedEvent.java | 22 +++++++++ ...ourceRetrievedDiscoverabilityListener.java | 34 +++++++++++++ spring-rest-full/.attach_pid28499 | 0 .../org/baeldung/persistence/IOperations.java | 6 +-- .../service/common/AbstractService.java | 10 ---- .../persistence/service/impl/FooService.java | 12 ----- .../web/controller/FooController.java | 14 ------ 12 files changed, 153 insertions(+), 53 deletions(-) create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java delete mode 100644 spring-rest-full/.attach_pid28499 diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index cf4ac0371b..3c8c4d7486 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -51,7 +51,6 @@ net.sourceforge.htmlunit htmlunit - ${htmlunit.version} test @@ -67,7 +66,6 @@ com.baeldung.SpringBootRestApplication - 2.32 27.0.1-jre diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java index d8996ca50d..1cc732ab08 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java @@ -1,16 +1,29 @@ package com.baeldung.persistence; import java.io.Serializable; +import java.util.List; import org.springframework.data.domain.Page; public interface IOperations { + // read - one + + T findOne(final long id); + // read - all + List findAll(); + Page findPaginated(int page, int size); // write T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); } diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java index 871f768895..5900c443b8 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -1,6 +1,7 @@ package com.baeldung.persistence.service.common; import java.io.Serializable; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -8,23 +9,54 @@ import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.IOperations; +import com.google.common.collect.Lists; @Transactional public abstract class AbstractService implements IOperations { + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id) + .get(); + } + // read - all + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + @Override public Page findPaginated(final int page, final int size) { return getDao().findAll(PageRequest.of(page, size)); } // write - + @Override public T create(final T entity) { return getDao().save(entity); } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } protected abstract PagingAndSortingRepository getDao(); diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java index 9d705f51d3..299e5ec214 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java @@ -1,5 +1,7 @@ package com.baeldung.persistence.service.impl; +import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -11,6 +13,7 @@ import com.baeldung.persistence.dao.IFooDao; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.persistence.service.common.AbstractService; +import com.google.common.collect.Lists; @Service @Transactional @@ -36,5 +39,13 @@ public class FooService extends AbstractService implements IFooService { public Page findPaginated(Pageable pageable) { return dao.findAll(pageable); } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index b35295cf99..59e33263db 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -9,14 +9,16 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.baeldung.persistence.model.Foo; @@ -24,9 +26,11 @@ import com.baeldung.persistence.service.IFooService; import com.baeldung.web.exception.MyResourceNotFoundException; import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; import com.baeldung.web.hateoas.event.ResourceCreatedEvent; +import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; +import com.baeldung.web.util.RestPreconditions; import com.google.common.base.Preconditions; -@Controller +@RestController @RequestMapping(value = "/auth/foos") public class FooController { @@ -42,10 +46,24 @@ public class FooController { // API + // read - one + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } + // read - all - @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) - @ResponseBody + @GetMapping + public List findAll() { + return service.findAll(); + } + + @GetMapping(params = { "page", "size" }) public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { final Page resultPage = service.findPaginated(page, size); @@ -59,7 +77,6 @@ public class FooController { } @GetMapping("/pageable") - @ResponseBody public List findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { final Page resultPage = service.findPaginated(pageable); @@ -74,9 +91,8 @@ public class FooController { // write - @RequestMapping(method = RequestMethod.POST) + @PostMapping @ResponseStatus(HttpStatus.CREATED) - @ResponseBody public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); final Foo foo = service.create(resource); @@ -86,4 +102,18 @@ public class FooController { return foo; } + + @PutMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + Preconditions.checkNotNull(resource); + RestPreconditions.checkFound(service.findOne(resource.getId())); + service.update(resource); + } + + @DeleteMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + service.deleteById(id); + } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java new file mode 100644 index 0000000000..70face083c --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java @@ -0,0 +1,22 @@ +package com.baeldung.web.hateoas.event; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.ApplicationEvent; + +public class SingleResourceRetrievedEvent extends ApplicationEvent { + private final HttpServletResponse response; + + public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) { + super(source); + + this.response = response; + } + + // API + + public HttpServletResponse getResponse() { + return response; + } + +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java new file mode 100644 index 0000000000..d527c308b9 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java @@ -0,0 +1,34 @@ +package com.baeldung.web.hateoas.listener; + +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; +import com.baeldung.web.util.LinkUtil; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.google.common.base.Preconditions; +import com.google.common.net.HttpHeaders; + +@Component +class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener { + + @Override + public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) { + Preconditions.checkNotNull(resourceRetrievedEvent); + + final HttpServletResponse response = resourceRetrievedEvent.getResponse(); + addLinkHeaderOnSingleResourceRetrieval(response); + } + + void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) { + final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString(); + final int positionOfLastSlash = requestURL.lastIndexOf("/"); + final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash); + + final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection"); + response.addHeader(HttpHeaders.LINK, linkHeaderValue); + } + +} \ No newline at end of file diff --git a/spring-rest-full/.attach_pid28499 b/spring-rest-full/.attach_pid28499 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java index 8c5593c3e8..0b617bf7ab 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java @@ -16,11 +16,7 @@ public interface IOperations { // write T create(final T entity); - + T update(final T entity); - void delete(final T entity); - - void deleteById(final long entityId); - } diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java index 59ccea8b12..059516eeba 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java @@ -40,16 +40,6 @@ public abstract class AbstractService implements IOperat return getDao().save(entity); } - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().delete(entityId); - } - protected abstract PagingAndSortingRepository getDao(); } diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java index d46f1bfe90..32fe1bd7e0 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service.impl; -import java.util.List; - import org.baeldung.persistence.dao.IFooDao; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; @@ -11,8 +9,6 @@ import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import com.google.common.collect.Lists; - @Service @Transactional public class FooService extends AbstractService implements IFooService { @@ -38,12 +34,4 @@ public class FooService extends AbstractService implements IFooService { return dao.retrieveByName(name); } - // overridden to be secured - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - } diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 443d0908ee..2e4dbcacc9 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -80,20 +80,6 @@ public class FooController { return foo; } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { - Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); - service.update(resource); - } - - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - public void delete(@PathVariable("id") final Long id) { - service.deleteById(id); - } - @RequestMapping(method = RequestMethod.HEAD) @ResponseStatus(HttpStatus.OK) public void head(final HttpServletResponse resp) { From e51d996ec1fab6f0239cd436e0739fd8f5d22bba Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 17:05:09 -0200 Subject: [PATCH 51/72] Added spring boot related tests for building Rest API article --- .../web/FooControllerAppIntegrationTest.java | 36 +++++++++++ .../FooControllerWebLayerIntegrationTest.java | 60 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java create mode 100644 spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java new file mode 100644 index 0000000000..bd5b5eb58e --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.web; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +/** + * + * We'll start the whole context, but not the server. We'll mock the REST calls instead. + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class FooControllerAppIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenFindPaginatedRequest_thenEmptyResponse() throws Exception { + this.mockMvc.perform(get("/auth/foos").param("page", "0") + .param("size", "2")) + .andExpect(status().isOk()) + .andExpect(content().json("[]")); + } + +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java new file mode 100644 index 0000000000..7e41cf6393 --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.web; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.Collections; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.web.controller.FooController; +import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; + +/** + * + * We'll start only the web layer. + * + */ +@RunWith(SpringRunner.class) +@WebMvcTest(FooController.class) +public class FooControllerWebLayerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private IFooService service; + + @MockBean + private ApplicationEventPublisher publisher; + + @Test() + public void givenPresentFoo_whenFindPaginatedRequest_thenPageWithFooRetrieved() throws Exception { + Page page = new PageImpl<>(Collections.singletonList(new Foo("fooName"))); + when(service.findPaginated(0, 2)).thenReturn(page); + doNothing().when(publisher) + .publishEvent(any(PaginatedResultsRetrievedEvent.class)); + + this.mockMvc.perform(get("/auth/foos").param("page", "0") + .param("size", "2")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$",Matchers.hasSize(1))); + } + +} From 281432707993500042df7f02f1fa3b2310d9d401 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 19:17:01 -0200 Subject: [PATCH 52/72] Moved article from Readme files --- spring-boot-rest/README.md | 3 ++- spring-rest-full/README.md | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 2c89a64a00..ffc48126d3 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -2,4 +2,5 @@ Module for the articles that are part of the Spring REST E-book: 1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) 2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) -3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) \ No newline at end of file +3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) +4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) \ No newline at end of file diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 2ef3a09e37..5140c4b270 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -16,7 +16,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) -- [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) From f1ea814185be1e0bf555bb49c737da27eed86b3f Mon Sep 17 00:00:00 2001 From: rodolforfq <31481067+rodolforfq@users.noreply.github.com> Date: Wed, 30 Jan 2019 11:40:24 -0400 Subject: [PATCH 53/72] New examples (#6242) Adding new examples. Improvement in existing method. --- .../baeldung/java8/lambda/methodreference/Bicycle.java | 5 +++++ .../methodreference/MethodReferenceExamples.java | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java index 760a24d7c2..26f9f8bc46 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java @@ -5,6 +5,11 @@ public class Bicycle { private String brand; private Integer frameSize; + public Bicycle(String brand) { + this.brand = brand; + this.frameSize = 0; + } + public Bicycle(String brand, Integer frameSize) { this.brand = brand; this.frameSize = frameSize; diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java index 3b9a5ec6ff..ede0ef9f70 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java @@ -52,10 +52,18 @@ public class MethodReferenceExamples { bikes.add(bikeCreatorMethodReference.apply("GT", 40)); } + @Test + public void referenceToConstructorSimpleExample() { + List bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT"); + bikeBrands.stream() + .map(Bicycle::new) + .toArray(Bicycle[]::new); + } + @Test public void limitationsAndAdditionalExamples() { createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize())); - createBicyclesList().forEach((o) -> this.doNothingAtAll(o)); + createBicyclesList().forEach((o) -> MethodReferenceExamples.doNothingAtAll(o)); } private List createBicyclesList() { From 4d1c8634facc2e9fb305c794c27e379bf7bb4aeb Mon Sep 17 00:00:00 2001 From: psevestre Date: Thu, 31 Jan 2019 00:16:26 -0200 Subject: [PATCH 54/72] Code for BAEL-1381 (#6214) * BAEL-1381 * [BAEL-1381] * [BAEL-1381] New module name * [BAEL-1381] software-security module --- pom.xml | 3 +- .../sql-injection-samples/.gitignore | 25 +++ .../sql-injection-samples/pom.xml | 61 +++++++ .../examples/security/sql/AccountDAO.java | 169 ++++++++++++++++++ .../examples/security/sql/AccountDTO.java | 16 ++ .../sql/SqlInjectionSamplesApplication.java | 14 ++ .../src/main/resources/application.properties | 0 .../resources/db/changelog/create-tables.xml | 19 ++ .../main/resources/db/master-changelog.xml | 8 + ...qlInjectionSamplesApplicationUnitTest.java | 60 +++++++ .../src/test/resources/application-test.yml | 6 + .../src/test/resources/data.sql | 4 + .../src/test/resources/schema.sql | 6 + 13 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 software-security/sql-injection-samples/.gitignore create mode 100644 software-security/sql-injection-samples/pom.xml create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java create mode 100644 software-security/sql-injection-samples/src/main/resources/application.properties create mode 100644 software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml create mode 100644 software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml create mode 100644 software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java create mode 100644 software-security/sql-injection-samples/src/test/resources/application-test.yml create mode 100644 software-security/sql-injection-samples/src/test/resources/data.sql create mode 100644 software-security/sql-injection-samples/src/test/resources/schema.sql diff --git a/pom.xml b/pom.xml index 01cb86d103..787a03c2fb 100644 --- a/pom.xml +++ b/pom.xml @@ -567,7 +567,8 @@ rule-engines/rulebook rsocket rxjava - rxjava-2 + rxjava-2 + software-security/sql-injection-samples diff --git a/software-security/sql-injection-samples/.gitignore b/software-security/sql-injection-samples/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/software-security/sql-injection-samples/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml new file mode 100644 index 0000000000..d5e64db6b3 --- /dev/null +++ b/software-security/sql-injection-samples/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + com.baeldung + sql-injection-samples + 0.0.1-SNAPSHOT + sql-injection-samples + Sample SQL Injection tests + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + org.apache.derby + derby + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java new file mode 100644 index 0000000000..447dcc456d --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java @@ -0,0 +1,169 @@ +/** + * + */ +package com.baeldung.examples.security.sql; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import javax.sql.DataSource; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class AccountDAO { + + private final DataSource dataSource; + + public AccountDAO(DataSource dataSource) { + this.dataSource = dataSource; + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List unsafeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'"; + + try (Connection c = dataSource.getConnection(); + ResultSet rs = c.createStatement() + .executeQuery(sql)) { + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customer_id")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?"; + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + private static final Set VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance") + .collect(Collectors.toCollection(HashSet::new)); + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId, String orderBy) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? "; + + if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) { + sql = sql + " order by " + orderBy; + } + else { + throw new IllegalArgumentException("Nice try!"); + } + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Invalid placeholder usage example + * + * @param tableName + * @return + */ + public List wrongCountRecordsByTableName(String tableName) { + + try (Connection c = dataSource.getConnection(); + PreparedStatement p = c.prepareStatement("select count(*) from ?")) { + + p.setString(1, tableName); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java new file mode 100644 index 0000000000..2e6fa04af4 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java @@ -0,0 +1,16 @@ +package com.baeldung.examples.security.sql; + +import java.math.BigDecimal; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class AccountDTO { + + private String customerId; + private String accNumber; + private String branchId; + private BigDecimal balance; +} diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java new file mode 100644 index 0000000000..c1083ae3de --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.examples.security.sql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SqlInjectionSamplesApplication { + + public static void main(String[] args) { + SpringApplication.run(SqlInjectionSamplesApplication.class, args); + } + +} + diff --git a/software-security/sql-injection-samples/src/main/resources/application.properties b/software-security/sql-injection-samples/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml new file mode 100644 index 0000000000..a405c02049 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml new file mode 100644 index 0000000000..047ca2b314 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java new file mode 100644 index 0000000000..1f37ba04b6 --- /dev/null +++ b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.examples.security.sql; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.examples.security.sql.AccountDAO; +import com.baeldung.examples.security.sql.AccountDTO; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles({ "test" }) +public class SqlInjectionSamplesApplicationUnitTest { + + @Autowired + private AccountDAO target; + + @Test + public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(1); + } + + @Test + public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(3); + } + + @Test + public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() { + + List accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isEmpty(); + } + + @Test(expected = IllegalArgumentException.class) + public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() { + target.safeFindAccountsByCustomerId("C1", "INVALID"); + } + + @Test(expected = RuntimeException.class) + public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() { + target.wrongCountRecordsByTableName("Accounts"); + } +} diff --git a/software-security/sql-injection-samples/src/test/resources/application-test.yml b/software-security/sql-injection-samples/src/test/resources/application-test.yml new file mode 100644 index 0000000000..d07ee10aee --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/application-test.yml @@ -0,0 +1,6 @@ +# +# Test profile configuration +# +spring: + datasource: + initialization-mode: always diff --git a/software-security/sql-injection-samples/src/test/resources/data.sql b/software-security/sql-injection-samples/src/test/resources/data.sql new file mode 100644 index 0000000000..586618a07f --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/data.sql @@ -0,0 +1,4 @@ +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C1','0001',1,1000.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C2','0002',1,500.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C3','0003',1,501.00); + diff --git a/software-security/sql-injection-samples/src/test/resources/schema.sql b/software-security/sql-injection-samples/src/test/resources/schema.sql new file mode 100644 index 0000000000..bfb0ae8059 --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/schema.sql @@ -0,0 +1,6 @@ +create table Accounts ( + customer_id varchar(16) not null, + acc_number varchar(16) not null, + branch_id decimal(8,0), + balance decimal(16,4) +); From ca98fbb7062c13129ee3193b679a64ad9da63f84 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Thu, 31 Jan 2019 16:18:59 +0400 Subject: [PATCH 55/72] Added Stream Api --- .../list/primitive/PrimitiveCollections.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 50f372e9c9..01372763e9 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -7,15 +7,20 @@ import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.Arrays; import java.util.List; +import java.util.OptionalDouble; +import java.util.function.IntPredicate; +import java.util.stream.IntStream; public class PrimitiveCollections { public static void main(String[] args) { - int[] primitives = new int[] {5, 10, 0, 2}; + int[] primitives = new int[] {5, 10, 0, 2, -8}; guavaPrimitives(primitives); + intStream(primitives); + TIntArrayList tList = new TIntArrayList(primitives); cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives); @@ -29,6 +34,15 @@ public class PrimitiveCollections { System.out.println(fastUtilList); } + private static void intStream(int[] primitives) { + + IntStream stream = IntStream.of(5, 10, 0, 2, -8); + + IntStream newStream = IntStream.of(primitives); + + OptionalDouble average = stream.filter(i -> i > 0).average(); + } + private static void guavaPrimitives(int[] primitives) { From 56a832273e35c82da8d6de1b041ed518f11b53ce Mon Sep 17 00:00:00 2001 From: Dave Crane Date: Thu, 31 Jan 2019 12:48:35 +0000 Subject: [PATCH 56/72] Lombok SuperBuilder Issue: BAEL-2561 --- .../buildermethodname}/Child.java | 2 +- .../buildermethodname}/Parent.java | 2 +- .../buildermethodname/Student.java | 16 ++++ .../inheritance/superbuilder/Child.java | 11 +++ .../inheritance/superbuilder/Parent.java | 11 +++ .../inheritance/superbuilder/Student.java | 10 ++ .../lombok/builder/BuilderUnitTest.java | 16 ---- ...derInheritanceUsingMethodNameUnitTest.java | 40 ++++++++ ...rInheritanceUsingSuperBuilderUnitTest.java | 96 +++++++++++++++++++ 9 files changed, 186 insertions(+), 18 deletions(-) rename lombok/src/main/java/com/baeldung/lombok/builder/{ => inheritance/buildermethodname}/Child.java (86%) rename lombok/src/main/java/com/baeldung/lombok/builder/{ => inheritance/buildermethodname}/Parent.java (70%) create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java create mode 100644 lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java create mode 100644 lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java similarity index 86% rename from lombok/src/main/java/com/baeldung/lombok/builder/Child.java rename to lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java index 70f6d9c46e..4cfcc22fb2 100644 --- a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java @@ -1,4 +1,4 @@ -package com.baeldung.lombok.builder; +package com.baeldung.lombok.builder.inheritance.buildermethodname; import lombok.Builder; import lombok.Getter; diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java similarity index 70% rename from lombok/src/main/java/com/baeldung/lombok/builder/Parent.java rename to lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java index 0cf76d4b00..93e48ee44e 100644 --- a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java @@ -1,4 +1,4 @@ -package com.baeldung.lombok.builder; +package com.baeldung.lombok.builder.inheritance.buildermethodname; import lombok.Builder; import lombok.Getter; diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java new file mode 100644 index 0000000000..c8eea84b97 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.builder.inheritance.buildermethodname; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Student extends Child { + + private final String schoolName; + + @Builder(builderMethodName = "studentBuilder") + public Student(String parentName, int parentAge, String childName, int childAge, String schoolName) { + super(parentName, parentAge, childName, childAge); + this.schoolName = schoolName; + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java new file mode 100644 index 0000000000..92285ebdc3 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Child extends Parent { + private final String childName; + private final int childAge; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java new file mode 100644 index 0000000000..b8e0934520 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Parent { + private final String parentName; + private final int parentAge; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java new file mode 100644 index 0000000000..db43bacafa --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java @@ -0,0 +1,10 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Student extends Child { + private final String schoolName; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java index 56a380569d..546c38f140 100644 --- a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java +++ b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java @@ -40,20 +40,4 @@ public class BuilderUnitTest { assertThat(testImmutableClient.getName()).isEqualTo("foo"); assertThat(testImmutableClient.getId()).isEqualTo(1); } - - @Test - public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { - Child child = Child.childBuilder() - .parentName("Andrea") - .parentAge(38) - .childName("Emma") - .childAge(6) - .build(); - - assertThat(child.getChildName()).isEqualTo("Emma"); - assertThat(child.getChildAge()).isEqualTo(6); - assertThat(child.getParentName()).isEqualTo("Andrea"); - assertThat(child.getParentAge()).isEqualTo(38); - } - } diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java new file mode 100644 index 0000000000..cf50b2577b --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.lombok.builder.inheritance.buildermethodname; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class BuilderInheritanceUsingMethodNameUnitTest { + + @Test + public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { + Child child = Child.childBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + + @Test + public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() { + Student student = Student.studentBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("Baeldung High School") + .build(); + + assertThat(student.getChildName()).isEqualTo("Emma"); + assertThat(student.getChildAge()).isEqualTo(6); + assertThat(student.getParentName()).isEqualTo("Andrea"); + assertThat(student.getParentAge()).isEqualTo(38); + assertThat(student.getSchoolName()).isEqualTo("Baeldung High School"); + } +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java new file mode 100644 index 0000000000..72bfa6567b --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class BuilderInheritanceUsingSuperBuilderUnitTest { + + @Test + public void givenSuperBuilderOnParentAndOnChild_ChildInheritingParentIsBuilt() { + Child child = Child.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + + @Test + public void givenSuperBuilderOnParent_StandardBuilderIsBuilt() { + Parent parent = Parent.builder() + .parentName("Andrea") + .parentAge(38) + .build(); + + assertThat(parent.getParentName()).isEqualTo("Andrea"); + assertThat(parent.getParentAge()).isEqualTo(38); + } + + @Test + public void givenToBuilderIsSetToTrueOnParentAndChild_DeepCopyViaBuilderIsPossible() { + Child child1 = Child.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + Child child2 = child1.toBuilder() + .childName("Anna") + .build(); + + assertThat(child2.getChildName()).isEqualTo("Anna"); + assertThat(child2.getChildAge()).isEqualTo(6); + assertThat(child2.getParentName()).isEqualTo("Andrea"); + assertThat(child2.getParentAge()).isEqualTo(38); + + } + + @Test + public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() { + Student student = Student.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("Baeldung High School") + .build(); + + assertThat(student.getChildName()).isEqualTo("Emma"); + assertThat(student.getChildAge()).isEqualTo(6); + assertThat(student.getParentName()).isEqualTo("Andrea"); + assertThat(student.getParentAge()).isEqualTo(38); + assertThat(student.getSchoolName()).isEqualTo("Baeldung High School"); + } + + @Test + public void givenToBuilderIsSetToTrueOnParentChildAndStudent_DeepCopyViaBuilderIsPossible() { + Student student1 = Student.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("School 1") + .build(); + + Student student2 = student1.toBuilder() + .childName("Anna") + .schoolName("School 2") + .build(); + + assertThat(student2.getChildName()).isEqualTo("Anna"); + assertThat(student2.getChildAge()).isEqualTo(6); + assertThat(student2.getParentName()).isEqualTo("Andrea"); + assertThat(student2.getParentAge()).isEqualTo(38); + assertThat(student2.getSchoolName()).isEqualTo("School 2"); + + } + + +} From bd166ed82f02a49b7c1eadec210b0c1459745c33 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Thu, 31 Jan 2019 22:18:07 +0100 Subject: [PATCH 57/72] Fix the integration test in module spring-4 --- .../org/baeldung/SpringContextIntegrationTest.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9dfac2bd9e..d646e22511 100644 --- a/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,13 +2,16 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import com.baeldung.flips.ApplicationConfig; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ApplicationConfig.class) + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration public class SpringContextIntegrationTest { @Test From 1c556fe4fc9192eef90e0c60e084b202fd004a9e Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Thu, 31 Jan 2019 22:28:46 +0100 Subject: [PATCH 58/72] Fix the integration test in module springboot-autoconfiguration This test requires that MySQL engine is up. --- .../SpringContextIntegrationTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a0138bec8d --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.autoconfiguration.MySQLAutoconfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MySQLAutoconfiguration.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} \ No newline at end of file From 191039ffc60afc3b39ef09be79a54887a8e9d164 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Fri, 1 Feb 2019 07:19:07 +0100 Subject: [PATCH 59/72] Add code for issue BAEL-2574 (#6249) * Add code for issue BAEL-2574 This is a code for article "Access Spring MVC Model object in JS" Set up the project Add a test * Rename the test class --- spring-boot-mvc/pom.xml | 10 ++++++ .../java/com/baeldung/accessparamsjs/App.java | 13 ++++++++ .../baeldung/accessparamsjs/Controller.java | 32 +++++++++++++++++++ .../src/main/resources/application.properties | 4 ++- .../src/main/webapp/WEB-INF/jsp/index.jsp | 27 ++++++++++++++++ spring-boot-mvc/src/main/webapp/js/jquery.js | 2 ++ .../src/main/webapp/js/script-async-jquery.js | 6 ++++ .../src/main/webapp/js/script-async.js | 6 ++++ spring-boot-mvc/src/main/webapp/js/script.js | 4 +++ .../accessparamsjs/ControllerUnitTest.java | 28 ++++++++++++++++ 10 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java create mode 100644 spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java create mode 100644 spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-boot-mvc/src/main/webapp/js/jquery.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script-async-jquery.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script-async.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script.js create mode 100644 spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index b219e53431..bb3e6312ab 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -72,6 +72,16 @@ ${spring.fox.version} + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java new file mode 100644 index 0000000000..2ffbb354c3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java @@ -0,0 +1,13 @@ +package com.baeldung.accessparamsjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java new file mode 100644 index 0000000000..cc838eb6a5 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java @@ -0,0 +1,32 @@ +package com.baeldung.accessparamsjs; + +import java.util.Map; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +/** + * Sample rest controller for the tutorial article + * "Access Spring MVC Model object in JavaScript". + * + * @author Andrew Shcherbakov + * + */ +@RestController +public class Controller { + + /** + * Define two model objects (one integer and one string) and pass them to the view. + * + * @param model + * @return + */ + @RequestMapping("/index") + public ModelAndView index(Map model) { + model.put("number", 1234); + model.put("message", "Hello from Spring MVC"); + return new ModelAndView("/index"); + } + +} diff --git a/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-mvc/src/main/resources/application.properties index 709574239b..00362e2588 100644 --- a/spring-boot-mvc/src/main/resources/application.properties +++ b/spring-boot-mvc/src/main/resources/application.properties @@ -1 +1,3 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true +spring.mvc.view.prefix=/WEB-INF/jsp/ +spring.mvc.view.suffix=.jsp \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..d9f3966e82 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,27 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + +Access Spring MVC params + + + + + + +

Data from the external JS file (due to loading order)

+
+
+

Asynchronous loading from external JS file (plain JS)

+
+
+

Asynchronous loading from external JS file (jQuery)

+
+
+ + + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/js/jquery.js b/spring-boot-mvc/src/main/webapp/js/jquery.js new file mode 100644 index 0000000000..4d9b3a2587 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/js/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w("