diff --git a/README.md b/README.md
index 6dff78aa7a..1d916c8409 100644
--- a/README.md
+++ b/README.md
@@ -40,5 +40,3 @@ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloud
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
-- [Java Service Provider Interface](http://www.baeldung.com/java-spi)
-- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams)
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
index 8b47fa0fdf..5ca2d626f1 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
@@ -148,7 +148,7 @@ public class Board {
System.out.println("Game Draw");
break;
case IN_PROGRESS:
- System.out.println("Game In rogress");
+ System.out.println("Game In Progress");
break;
}
}
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java
new file mode 100644
index 0000000000..1e9188f726
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java
@@ -0,0 +1,139 @@
+package com.baeldung.algorithms.analysis;
+
+import org.junit.Test;
+
+public class AnalysisRunnerLiveTest {
+
+ int n = 10;
+ int total = 0;
+
+ @Test
+ public void whenConstantComplexity_thenConstantRuntime() {
+
+ System.out.println("**** n = " + n + " ****");
+ System.out.println();
+
+ // Constant Time
+ System.out.println("**** Constant time ****");
+
+ System.out.println("Hey - your input is: " + n);
+ System.out.println("Running time not dependent on input size!");
+ System.out.println();
+ }
+
+ @Test
+ public void whenLogarithmicComplexity_thenLogarithmicRuntime() {
+ // Logarithmic Time
+ System.out.println("**** Logarithmic Time ****");
+ for (int i = 1; i < n; i = i * 2) {
+ // System.out.println("Hey - I'm busy looking at: " + i);
+ total++;
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+ }
+
+ @Test
+ public void whenLinearComplexity_thenLinearRuntime() {
+ // Linear Time
+ System.out.println("**** Linear Time ****");
+ for (int i = 0; i < n; i++) {
+ // System.out.println("Hey - I'm busy looking at: " + i);
+ total++;
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+
+ }
+
+ @Test
+ public void whenNLogNComplexity_thenNLogNRuntime() {
+ // N Log N Time
+ System.out.println("**** nlogn Time ****");
+ total = 0;
+ for (
+
+ int i = 1; i <= n; i++) {
+ for (int j = 1; j < n; j = j * 2) {
+ // System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
+ total++;
+ }
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+ }
+
+ @Test
+ public void whenQuadraticComplexity_thenQuadraticRuntime() {
+ // Quadratic Time
+ System.out.println("**** Quadratic Time ****");
+ total = 0;
+ for (
+
+ int i = 1; i <= n; i++) {
+ for (int j = 1; j <= n; j++) {
+ // System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
+ total++;
+ }
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+ }
+
+ @Test
+ public void whenCubicComplexity_thenCubicRuntime() {
+ // Cubic Time
+ System.out.println("**** Cubic Time ****");
+ total = 0;
+ for (
+
+ int i = 1; i <= n; i++) {
+ for (int j = 1; j <= n; j++) {
+ for (int k = 1; k <= n; k++) {
+ // System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k);
+ total++;
+ }
+ }
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+ }
+
+ @Test
+ public void whenExponentialComplexity_thenExponentialRuntime() {
+ // Exponential Time
+ System.out.println("**** Exponential Time ****");
+ total = 0;
+ for (
+
+ int i = 1; i <= Math.pow(2, n); i++) {
+ // System.out.println("Hey - I'm busy looking at: " + i);
+ total++;
+ }
+ System.out.println("Total amount of times run: " + total);
+ System.out.println();
+ }
+
+ @Test
+ public void whenFactorialComplexity_thenFactorialRuntime() {
+ // Factorial Time
+ System.out.println("**** Factorial Time ****");
+ total = 0;
+ for (
+
+ int i = 1; i <=
+
+ factorial(n); i++) {
+ // System.out.println("Hey - I'm busy looking at: " + i);
+ total++;
+ }
+ System.out.println("Total amount of times run: " + total);
+ }
+
+ static int factorial(int n) {
+ if (n == 0 || n == 1)
+ return 1;
+ else
+ return n * factorial(n - 1);
+ }
+}
diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml
index ab7b38f6e0..9ccc7354af 100644
--- a/animal-sniffer-mvn-plugin/pom.xml
+++ b/animal-sniffer-mvn-plugin/pom.xml
@@ -5,7 +5,7 @@
animal-sniffer-mvn-plugin
jar
1.0-SNAPSHOT
- example-animal-sniffer-mvn-plugin
+ animal-sniffer-mvn-plugin
http://maven.apache.org
diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java
index 5319208e85..7253238e80 100644
--- a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java
+++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java
@@ -1,25 +1,30 @@
package com.baeldung.poi.powerpoint;
+import java.io.File;
+import java.util.List;
+
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
-
-import java.io.File;
-import java.util.List;
+import org.junit.rules.TemporaryFolder;
public class PowerPointIntegrationTest {
private PowerPointHelper pph;
private String fileLocation;
private static final String FILE_NAME = "presentation.pptx";
+
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setUp() throws Exception {
- File currDir = new File(".");
+ File currDir = tempFolder.newFolder();
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
diff --git a/camel-api/pom.xml b/camel-api/pom.xml
index 86f6713cd6..4e50828b96 100644
--- a/camel-api/pom.xml
+++ b/camel-api/pom.xml
@@ -5,7 +5,6 @@
com.example
spring-boot-camel
0.0.1-SNAPSHOT
- Spring-Boot - Camel API
com.baeldung
diff --git a/core-java-8/README.md b/core-java-8/README.md
index df6d50ad30..2eb8d49983 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -52,4 +52,4 @@
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
-
+- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java
new file mode 100644
index 0000000000..e79c90b684
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.java8;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import static org.junit.Assert.assertEquals;
+
+public class UnsignedArithmeticUnitTest {
+ @Test
+ public void whenDoublingALargeByteNumber_thenOverflow() {
+ byte b1 = 100;
+ byte b2 = (byte) (b1 << 1);
+
+ assertEquals(-56, b2);
+ }
+
+ @Test
+ public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() {
+ int positive = Integer.MAX_VALUE;
+ int negative = Integer.MIN_VALUE;
+
+ int signedComparison = Integer.compare(positive, negative);
+ assertEquals(1, signedComparison);
+
+ int unsignedComparison = Integer.compareUnsigned(positive, negative);
+ assertEquals(-1, unsignedComparison);
+
+ assertEquals(negative, positive + 1);
+ }
+
+ @Test
+ public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() {
+ int positive = Integer.MAX_VALUE;
+ int negative = Integer.MIN_VALUE;
+
+ assertEquals(-1, negative / positive);
+ assertEquals(1, Integer.divideUnsigned(negative, positive));
+
+ assertEquals(-1, negative % positive);
+ assertEquals(1, Integer.divideUnsigned(negative, positive));
+ }
+
+ @Test
+ public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() {
+ Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648"));
+ assertThat(thrown).isInstanceOf(NumberFormatException.class);
+
+ assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648"));
+ }
+
+ @Test
+ public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() {
+ String signedString = Integer.toString(Integer.MIN_VALUE);
+ assertEquals("-2147483648", signedString);
+
+ String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE);
+ assertEquals("2147483648", unsignedString);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java
new file mode 100644
index 0000000000..b9600a18cb
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.typeinference;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+
+public class TypeInferenceUnitTest {
+
+ @Test
+ public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() {
+ // Without type inference. code is verbose.
+ Map> mapOfMaps = new HashMap>();
+ List strList = Collections. emptyList();
+ List intList = Collections. emptyList();
+
+ assertTrue(mapOfMaps.isEmpty());
+ assertTrue(strList.isEmpty());
+ assertTrue(intList.isEmpty());
+ }
+
+ @Test
+ public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() {
+ // With type inference. code is concise.
+ List strListInferred = Collections.emptyList();
+ List intListInferred = Collections.emptyList();
+
+ assertTrue(strListInferred.isEmpty());
+ assertTrue(intListInferred.isEmpty());
+ }
+
+ @Test
+ public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() {
+ // Type Inference for constructor using diamond operator.
+ Map> mapOfMapsInferred = new HashMap<>();
+
+ assertTrue(mapOfMapsInferred.isEmpty());
+ assertEquals("public class java.util.HashMap", mapOfMapsInferred.getClass()
+ .toGenericString());
+ }
+
+ static List add(List list, T a, T b) {
+ list.add(a);
+ list.add(b);
+ return list;
+ }
+
+ @Test
+ public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() {
+ // Generalized target-type inference
+ List strListGeneralized = add(new ArrayList<>(), "abc", "def");
+ List intListGeneralized = add(new ArrayList<>(), 1, 2);
+ List numListGeneralized = add(new ArrayList<>(), 1, 2.0);
+
+ assertEquals("public class java.util.ArrayList", strListGeneralized.getClass()
+ .toGenericString());
+ assertFalse(intListGeneralized.isEmpty());
+ assertEquals(2, numListGeneralized.size());
+ }
+
+ @Test
+ public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() {
+ // Type Inference and Lambda Expressions.
+ List intList = Arrays.asList(5, 3, 4, 2, 1);
+ Collections.sort(intList, (a, b) -> {
+ assertEquals("java.lang.Integer", a.getClass().getName());
+ return a.compareTo(b);
+ });
+ assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray()));
+
+ List strList = Arrays.asList("Red", "Blue", "Green");
+ Collections.sort(strList, (a, b) -> {
+ assertEquals("java.lang.String", a.getClass().getName());
+ return a.compareTo(b);
+ });
+ assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray()));
+ }
+
+}
diff --git a/core-java-9/README.md b/core-java-9/README.md
index 4223e57d4b..a76dcefc69 100644
--- a/core-java-9/README.md
+++ b/core-java-9/README.md
@@ -25,3 +25,4 @@
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
+- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
index 0945a21b1b..a96232d66c 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
@@ -1,6 +1,7 @@
package org.baeldung.java.io;
import org.junit.Test;
+import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -105,6 +106,7 @@ public class JavaReadFromFileUnitTest {
}
@Test
+ @Ignore // TODO
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
final String expected_value = "青空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
diff --git a/core-java/README.md b/core-java/README.md
index 9bc7d9f7ee..fa2d7e4cf0 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -141,6 +141,7 @@
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
+- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
@@ -149,5 +150,13 @@
- [NaN in Java](http://www.baeldung.com/java-not-a-number)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
-
-
+- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
+- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
+- [Singletons in Java](http://www.baeldung.com/java-singleton)
+- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
+- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
+- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
+- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
+- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
+- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
+- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
diff --git a/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java b/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java
deleted file mode 100644
index 12c73f2489..0000000000
--- a/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.baeldung.linkedlist;
-
-/**
- * Implementation of a singly linked list.
- */
-public class LinkedList {
- private Node head;
- private Node tail;
-
- public Node head() {
- return head;
- }
-
- public void add(String data) {
- Node newNode = new Node(data);
-
- if (head == null) {
- head = newNode;
- tail = newNode;
- } else {
- tail.next = newNode;
- tail = newNode;
- }
- }
-
- public static class Node {
- private Node next;
- private String data;
-
- public Node(String data) {
- this.data = data;
- }
-
- public String data() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
-
- public boolean hasNext() {
- return next != null;
- }
-
- public Node next() {
- return next;
- }
-
- public void setNext(Node next) {
- this.next = next;
- }
-
- public String toString() {
- return this.data;
- }
- }
-}
diff --git a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java
index 27684c93d2..4cfa0d411b 100644
--- a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java
+++ b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java
@@ -1,12 +1,23 @@
package com.baeldung.linkedlist;
-import com.baeldung.linkedlist.LinkedList.Node;
+import java.util.LinkedList;
+import java.util.Optional;
+
+import com.baeldung.linkedlist.Node;
public class MiddleElementLookup {
- public static String findMiddleElement(Node head) {
+ public static Optional findMiddleElementLinkedList(LinkedList linkedList) {
+ if (linkedList == null || linkedList.isEmpty()) {
+ return Optional.empty();
+ }
+
+ return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2));
+ }
+
+ public static Optional findMiddleElementFromHead(Node head) {
if (head == null) {
- return null;
+ return Optional.empty();
}
// calculate the size of the list
@@ -23,17 +34,17 @@ public class MiddleElementLookup {
current = current.next();
}
- return current.data();
+ return Optional.ofNullable(current.data());
}
- public static String findMiddleElement1PassRecursively(Node head) {
+ public static Optional findMiddleElementFromHead1PassRecursively(Node head) {
if (head == null) {
- return null;
+ return Optional.empty();
}
MiddleAuxRecursion middleAux = new MiddleAuxRecursion();
findMiddleRecursively(head, middleAux);
- return middleAux.middle.data();
+ return Optional.ofNullable(middleAux.middle.data());
}
private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
@@ -53,9 +64,9 @@ public class MiddleElementLookup {
middleAux.length--;
}
- public static String findMiddleElement1PassIteratively(Node head) {
+ public static Optional findMiddleElementFromHead1PassIteratively(Node head) {
if (head == null) {
- return null;
+ return Optional.empty();
}
Node slowPointer = head;
@@ -68,7 +79,7 @@ public class MiddleElementLookup {
slowPointer = slowPointer.next();
}
- return slowPointer.data();
+ return Optional.ofNullable(slowPointer.data());
}
private static class MiddleAuxRecursion {
diff --git a/core-java/src/main/java/com/baeldung/linkedlist/Node.java b/core-java/src/main/java/com/baeldung/linkedlist/Node.java
new file mode 100644
index 0000000000..daceaffdcd
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/linkedlist/Node.java
@@ -0,0 +1,34 @@
+package com.baeldung.linkedlist;
+
+public class Node {
+ private Node next;
+ private String data;
+
+ public Node(String data) {
+ this.data = data;
+ }
+
+ public String data() {
+ return data;
+ }
+
+ public void setData(String data) {
+ this.data = data;
+ }
+
+ public boolean hasNext() {
+ return next != null;
+ }
+
+ public Node next() {
+ return next;
+ }
+
+ public void setNext(Node next) {
+ this.next = next;
+ }
+
+ public String toString() {
+ return this.data;
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java
index f432436190..a4dd7e25c3 100644
--- a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java
@@ -46,7 +46,7 @@ public class JaggedArrayUnitTest {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
obj.printElements(jaggedArr);
- assertEquals("[1, 2]\n[3, 4, 5]\n[6, 7, 8, 9]\n", outContent.toString());
+ assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out);
}
diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java
new file mode 100644
index 0000000000..9e6d3d6131
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java
@@ -0,0 +1,153 @@
+package com.baeldung.arrays;
+
+import static org.junit.Assert.*;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+public class ArraysUnitTest {
+ private String[] intro;
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Before
+ public void setup() {
+ intro = new String[] { "once", "upon", "a", "time" };
+ }
+
+ @Test
+ public void whenCopyOfRange_thenAbridgedArray() {
+ String[] abridgement = Arrays.copyOfRange(intro, 0, 3);
+
+ assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement);
+ assertFalse(Arrays.equals(intro, abridgement));
+ }
+
+ @Test
+ public void whenCopyOf_thenNullElement() {
+ String[] revised = Arrays.copyOf(intro, 3);
+ String[] expanded = Arrays.copyOf(intro, 5);
+
+ assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
+ assertNull(expanded[4]);
+ }
+
+ @Test
+ public void whenFill_thenAllMatch() {
+ String[] stutter = new String[3];
+ Arrays.fill(stutter, "once");
+
+ assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el)));
+ }
+
+ @Test
+ public void whenEqualsContent_thenMatch() {
+ assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
+ assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro));
+ }
+
+ @Test
+ public void whenNestedArrays_thenDeepEqualsPass() {
+ String[] end = { "the", "end" };
+ Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+ Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+
+ assertTrue(Arrays.deepEquals(story, copy));
+ assertFalse(Arrays.equals(story, copy));
+ }
+
+ @Test
+ public void whenSort_thenArraySorted() {
+ String[] sorted = Arrays.copyOf(intro, 4);
+ Arrays.sort(sorted);
+
+ assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted);
+ }
+
+ @Test
+ public void whenBinarySearch_thenFindElements() {
+ String[] sorted = Arrays.copyOf(intro, 4);
+ Arrays.sort(sorted);
+ int exact = Arrays.binarySearch(sorted, "time");
+ int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);
+
+ assertEquals("time", sorted[exact]);
+ assertEquals(2, exact);
+ assertEquals(exact, caseInsensitive);
+ }
+
+ @Test
+ public void whenNullElement_thenArraysHashCodeNotEqual() {
+ int beforeChange = Arrays.hashCode(intro);
+ int before = intro.hashCode();
+ intro[3] = null;
+ int after = intro.hashCode();
+ int afterChange = Arrays.hashCode(intro);
+
+ assertNotEquals(beforeChange, afterChange);
+ assertEquals(before, after);
+ }
+
+ @Test
+ public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() {
+ Object[] looping = new Object[] { intro, intro };
+ int deepHashBefore = Arrays.deepHashCode(looping);
+ int hashBefore = Arrays.hashCode(looping);
+
+ intro[3] = null;
+
+ int hashAfter = Arrays.hashCode(looping);
+ int deepHashAfter = Arrays.deepHashCode(looping);
+
+ assertEquals(hashAfter, hashBefore);
+ assertNotEquals(deepHashAfter, deepHashBefore);
+ }
+
+ @Test
+ public void whenStreamBadIndex_thenException() {
+ assertEquals(Arrays.stream(intro).count(), 4);
+
+ exception.expect(ArrayIndexOutOfBoundsException.class);
+ Arrays.stream(intro, 2, 1).count();
+ }
+
+ @Test
+ public void whenSetAllToUpper_thenAppliedToAllElements() {
+ String[] longAgo = new String[4];
+ Arrays.setAll(longAgo, i -> intro[i].toUpperCase());
+
+ assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" });
+ }
+
+ @Test
+ public void whenToString_thenFormattedArrayString() {
+ assertEquals("[once, upon, a, time]", Arrays.toString(intro));
+ }
+
+ @Test
+ public void whenNestedArrayDeepString_thenFormattedArraysString() {
+ String[] end = { "the", "end" };
+ Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+
+ assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story));
+ }
+
+ @Test
+ public void whenAsList_thenImmutableArray() {
+ List rets = Arrays.asList(intro);
+
+ assertTrue(rets.contains("upon"));
+ assertTrue(rets.contains("time"));
+ assertEquals(rets.size(), 4);
+
+ exception.expect(UnsupportedOperationException.class);
+ rets.add("the");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java
index d456259612..2801bbfc9e 100644
--- a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java
@@ -1,52 +1,97 @@
package com.baeldung.linkedlist;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.util.LinkedList;
import org.junit.Test;
public class MiddleElementLookupUnitTest {
@Test
- public void whenFindingMiddle_thenMiddleFound() {
- String middle = MiddleElementLookup.findMiddleElement(createList(5).head());
- assertEquals("3", middle);
-
- middle = MiddleElementLookup.findMiddleElement(createList(4).head());
- assertEquals("2", middle);
+ public void whenFindingMiddleLinkedList_thenMiddleFound() {
+ assertEquals("3", MiddleElementLookup
+ .findMiddleElementLinkedList(createLinkedList(5))
+ .get());
+ assertEquals("2", MiddleElementLookup
+ .findMiddleElementLinkedList(createLinkedList(4))
+ .get());
}
@Test
- public void whenFindingMiddle1PassRecursively_thenMiddleFound() {
- String middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(5).head());
- assertEquals("3", middle);
-
- middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(4).head());
- assertEquals("2", middle);
+ public void whenFindingMiddleFromHead_thenMiddleFound() {
+ assertEquals("3", MiddleElementLookup
+ .findMiddleElementFromHead(createNodesList(5))
+ .get());
+ assertEquals("2", MiddleElementLookup
+ .findMiddleElementFromHead(createNodesList(4))
+ .get());
}
@Test
- public void whenFindingMiddle1PassIteratively_thenMiddleFound() {
- String middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(5).head());
- assertEquals("3", middle);
-
- middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(4).head());
- assertEquals("2", middle);
+ public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
+ assertEquals("3", MiddleElementLookup
+ .findMiddleElementFromHead1PassRecursively(createNodesList(5))
+ .get());
+ assertEquals("2", MiddleElementLookup
+ .findMiddleElementFromHead1PassRecursively(createNodesList(4))
+ .get());
}
@Test
- public void whenListEmptyOrNull_thenMiddleNull() {
- String middle = MiddleElementLookup.findMiddleElement(null);
- assertEquals(null, middle);
-
- middle = MiddleElementLookup.findMiddleElement1PassIteratively(null);
- assertEquals(null, middle);
-
- middle = MiddleElementLookup.findMiddleElement1PassRecursively(null);
- assertEquals(null, middle);
+ public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
+ assertEquals("3", MiddleElementLookup
+ .findMiddleElementFromHead1PassIteratively(createNodesList(5))
+ .get());
+ assertEquals("2", MiddleElementLookup
+ .findMiddleElementFromHead1PassIteratively(createNodesList(4))
+ .get());
}
- private static LinkedList createList(int n) {
- LinkedList list = new LinkedList();
+ @Test
+ public void whenListEmptyOrNull_thenMiddleNotFound() {
+ // null list
+ assertFalse(MiddleElementLookup
+ .findMiddleElementLinkedList(null)
+ .isPresent());
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead(null)
+ .isPresent());
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead1PassIteratively(null)
+ .isPresent());
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead1PassRecursively(null)
+ .isPresent());
+
+ // empty LinkedList
+ assertFalse(MiddleElementLookup
+ .findMiddleElementLinkedList(new LinkedList<>())
+ .isPresent());
+
+ // LinkedList with nulls
+ LinkedList nullsList = new LinkedList<>();
+ nullsList.add(null);
+ nullsList.add(null);
+ assertFalse(MiddleElementLookup
+ .findMiddleElementLinkedList(nullsList)
+ .isPresent());
+
+ // nodes with null values
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead(new Node(null))
+ .isPresent());
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead1PassIteratively(new Node(null))
+ .isPresent());
+ assertFalse(MiddleElementLookup
+ .findMiddleElementFromHead1PassRecursively(new Node(null))
+ .isPresent());
+ }
+
+ private static LinkedList createLinkedList(int n) {
+ LinkedList list = new LinkedList<>();
for (int i = 1; i <= n; i++) {
list.add(String.valueOf(i));
@@ -55,4 +100,17 @@ public class MiddleElementLookupUnitTest {
return list;
}
+ private static Node createNodesList(int n) {
+ Node head = new Node("1");
+ Node current = head;
+
+ for (int i = 2; i <= n; i++) {
+ Node newNode = new Node(String.valueOf(i));
+ current.setNext(newNode);
+ current = newNode;
+ }
+
+ return head;
+ }
+
}
diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
index fe2747bcee..04d2886a82 100644
--- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
+++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
@@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest {
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
- .set("pattern", "00000.00 �")
+ .set("pattern", "00000.00 US Dollar")
.build());
String customFormatted = customFormat.format(oneDollar);
diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
index 7f165cec86..9abe8a927c 100644
--- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
@@ -104,7 +104,7 @@ public class NashornUnitTest {
public void loadExamples() throws ScriptException {
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
- Assert.assertEquals(6.0, loadResult);
+ Assert.assertEquals(6, ((Double) loadResult).intValue());
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt
index ae0c707289..69cfce5601 100644
--- a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt
+++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt
@@ -2,32 +2,22 @@ package com.baeldung.enums
enum class CardType(val color: String) : ICardLimit {
SILVER("gray") {
- override fun getCreditLimit(): Int {
- return 100000
- }
-
- override fun calculateCashbackPercent(): Float {
- return 0.25f
- }
+ override fun getCreditLimit() = 100000
+ override fun calculateCashbackPercent() = 0.25f
},
GOLD("yellow") {
- override fun getCreditLimit(): Int {
- return 200000
- }
-
- override fun calculateCashbackPercent(): Float {
- return 0.5f
- }
+ override fun getCreditLimit() = 200000
+ override fun calculateCashbackPercent(): Float = 0.5f
},
PLATINUM("black") {
- override fun getCreditLimit(): Int {
- return 300000
- }
-
- override fun calculateCashbackPercent(): Float {
- return 0.75f
- }
+ override fun getCreditLimit() = 300000
+ override fun calculateCashbackPercent() = 0.75f
};
+ companion object {
+ fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color }
+ fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
+ }
+
abstract fun calculateCashbackPercent(): Float
}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardTypeHelper.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardTypeHelper.kt
deleted file mode 100644
index 29982192bb..0000000000
--- a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardTypeHelper.kt
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.baeldung.enums
-
-class CardTypeHelper {
- fun getCardTypeByColor(color: String): CardType? {
- for (cardType in CardType.values()) {
- if (cardType.color.equals(color)) {
- return cardType;
- }
- }
- return null
- }
-
- fun getCardTypeByName(name: String): CardType {
- return CardType.valueOf(name.toUpperCase())
- }
-}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeHelperUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeHelperUnitTest.kt
deleted file mode 100644
index 8fcd281784..0000000000
--- a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeHelperUnitTest.kt
+++ /dev/null
@@ -1,43 +0,0 @@
-package com.baeldung.enums
-
-import org.junit.jupiter.api.Assertions
-import org.junit.jupiter.api.Test
-
-internal class CardTypeHelperUnitTest {
-
- @Test
- fun whenGetCardTypeByColor_thenSilverCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.SILVER, cardTypeHelper.getCardTypeByColor("gray"))
- }
-
- @Test
- fun whenGetCardTypeByColor_thenGoldCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.GOLD, cardTypeHelper.getCardTypeByColor("yellow"))
- }
-
- @Test
- fun whenGetCardTypeByColor_thenPlatinumCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.PLATINUM, cardTypeHelper.getCardTypeByColor("black"))
- }
-
- @Test
- fun whenGetCardTypeByName_thenSilverCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.SILVER, cardTypeHelper.getCardTypeByName("silver"))
- }
-
- @Test
- fun whenGetCardTypeByName_thenGoldCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.GOLD, cardTypeHelper.getCardTypeByName("gold"))
- }
-
- @Test
- fun whenGetCardTypeByName_thenPlatinumCardType() {
- val cardTypeHelper = CardTypeHelper()
- Assertions.assertEquals(CardType.PLATINUM, cardTypeHelper.getCardTypeByName("platinum"))
- }
-}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt
index 0e74e1cf56..525faebd55 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt
+++ b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt
@@ -1,5 +1,6 @@
package com.baeldung.enums
+import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
@@ -49,4 +50,35 @@ internal class CardTypeUnitTest {
fun givenPlatinumCardType_whenCheckColor_thenReturnColor() {
assertEquals("black", CardType.PLATINUM.color)
}
+
+ @Test
+ fun whenGetCardTypeByColor_thenSilverCardType() {
+ Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray"))
+ }
+
+ @Test
+ fun whenGetCardTypeByColor_thenGoldCardType() {
+ Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow"))
+ }
+
+ @Test
+ fun whenGetCardTypeByColor_thenPlatinumCardType() {
+ Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenSilverCardType() {
+ Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenGoldCardType() {
+ Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenPlatinumCardType() {
+ Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum"))
+ }
+
}
diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
index e708922988..3100f0c70b 100644
--- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
+++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
@@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.couchbase.client.java.Bucket;
@@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService {
private Cluster cluster;
private Map buckets = new ConcurrentHashMap<>();
+
+ @Autowired
+ public ClusterServiceImpl(Cluster cluster) {
+ this.cluster = cluster;
+ }
@PostConstruct
private void init() {
diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
index 459585d995..75a196ff5d 100644
--- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
+++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
@@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService {
@Autowired
public TutorialBucketService(ClusterService clusterService) {
super(clusterService);
+ openBucket();
}
@Override
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java
new file mode 100644
index 0000000000..9e650752d2
--- /dev/null
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java
@@ -0,0 +1,24 @@
+package com.baeldung.couchbase.async.person;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+import com.couchbase.client.java.Cluster;
+import com.couchbase.client.java.CouchbaseCluster;
+import com.couchbase.client.java.env.CouchbaseEnvironment;
+import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
+
+@Configuration
+@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"})
+public class PersonCrudServiceIntegrationTestConfig {
+
+ @Bean
+ public Cluster cluster() {
+ CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
+ .connectTimeout(60000)
+ .build();
+ return CouchbaseCluster.create(env, "127.0.0.1");
+ }
+
+}
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
similarity index 90%
rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
index 565aaed5da..267071ab35 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
@@ -1,27 +1,31 @@
package com.baeldung.couchbase.async.person;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-import javax.annotation.PostConstruct;
-
import org.apache.commons.lang3.RandomStringUtils;
+import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.couchbase.async.AsyncIntegrationTest;
-import com.baeldung.couchbase.async.person.Person;
-import com.baeldung.couchbase.async.person.PersonCrudService;
-import com.baeldung.couchbase.async.person.PersonDocumentConverter;
import com.baeldung.couchbase.async.service.BucketService;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.document.JsonDocument;
-public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class})
+public class PersonCrudServiceLiveTest extends AsyncIntegrationTest {
@Autowired
private PersonCrudService personService;
@@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
private Bucket bucket;
- @PostConstruct
- private void init() {
+ @Before
+ public void init() {
bucket = bucketService.getBucket();
}
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
similarity index 94%
rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
index d0db5d37a3..5f478ae788 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
@@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public class ClusterServiceIntegrationTest extends AsyncIntegrationTest {
+public class ClusterServiceLiveTest extends AsyncIntegrationTest {
@Autowired
private ClusterService couchbaseService;
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
similarity index 98%
rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
index 00d462e32a..d260795ed3 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
@@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.view.ViewResult;
import com.couchbase.client.java.view.ViewRow;
-public class StudentGradeServiceIntegrationTest {
- private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class);
+public class StudentGradeServiceLiveTest {
+ private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class);
static StudentGradeService studentGradeService;
static Set gradeIds = new HashSet<>();
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
similarity index 97%
rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
index 8112d7d222..602bb5b8a5 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
@@ -1,5 +1,23 @@
package com.baeldung.couchbase.n1ql;
+import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
+import static com.couchbase.client.java.query.Select.select;
+import static com.couchbase.client.java.query.dsl.Expression.i;
+import static com.couchbase.client.java.query.dsl.Expression.s;
+import static com.couchbase.client.java.query.dsl.Expression.x;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.document.JsonDocument;
@@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.query.Statement;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
import rx.Observable;
-import java.util.List;
-import java.util.UUID;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-
-import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
-import static com.couchbase.client.java.query.Select.select;
-import static com.couchbase.client.java.query.dsl.Expression.*;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
-public class N1QLIntegrationTest {
+public class N1QLLiveTest {
@Autowired
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
similarity index 97%
rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
index ec15be1acc..493b326d49 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
@@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.couchbase.spring.IntegrationTest;
-public class PersonCrudServiceIntegrationTest extends IntegrationTest {
+public class PersonCrudServiceLiveTest extends IntegrationTest {
private static final String CLARK_KENT = "Clark Kent";
private static final String SMALLVILLE = "Smallville";
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
similarity index 94%
rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
index ead247dfbc..7a89a208f7 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
@@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public class ClusterServiceIntegrationTest extends IntegrationTest {
+public class ClusterServiceLiveTest extends IntegrationTest {
@Autowired
private ClusterService couchbaseService;
diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml
index 83dd0aef30..88116f8003 100755
--- a/ejb/ejb-client/pom.xml
+++ b/ejb/ejb-client/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
ejb-client
- EJB3 Client Maven
EJB3 Client Maven
diff --git a/ethereumj/README.md b/ethereumj/README.md
index 5a0be0bd16..320ae8c9f8 100644
--- a/ethereumj/README.md
+++ b/ethereumj/README.md
@@ -3,3 +3,4 @@
### Relevant Articles:
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity)
+- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j)
diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml
index 611b7b09eb..6917505f1b 100644
--- a/ethereumj/pom.xml
+++ b/ethereumj/pom.xml
@@ -10,10 +10,10 @@
ethereumj
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/flips/pom.xml b/flips/pom.xml
index be9f584114..34cbab7035 100644
--- a/flips/pom.xml
+++ b/flips/pom.xml
@@ -8,10 +8,10 @@
flips
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/flyway/pom.xml b/flyway/pom.xml
index 3637f1de28..018f9b7f86 100644
--- a/flyway/pom.xml
+++ b/flyway/pom.xml
@@ -8,10 +8,10 @@
Flyway Callbacks Demo
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/grpc/pom.xml b/grpc/pom.xml
index ad563f16fd..fb8312e8df 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -5,8 +5,6 @@
grpc-demo
0.0.1-SNAPSHOT
jar
- grpc-demo
- http://maven.apache.org
com.baeldung
diff --git a/gson/README.md b/gson/README.md
index 60c80477b1..bedfbd206c 100644
--- a/gson/README.md
+++ b/gson/README.md
@@ -6,3 +6,4 @@
### Relevant Articles:
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
+- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization)
diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
index 254272e1c0..e3c07ab38a 100644
--- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
+++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
@@ -1,3 +1,2 @@
Manifest-Version: 1.0
Class-Path:
-
diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile
new file mode 100644
index 0000000000..211e8927a3
--- /dev/null
+++ b/guest/spring-boot-app/docker/Dockerfile
@@ -0,0 +1,16 @@
+# Alpine Linux with OpenJDK JRE
+FROM openjdk:8-jre-alpine
+RUN apk add --no-cache bash
+
+# copy fat WAR
+COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war
+
+# copy fat WAR
+COPY logback.xml /logback.xml
+
+COPY run.sh /run.sh
+
+# runs application
+#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"]
+
+ENTRYPOINT ["/run.sh"]
diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml
new file mode 100644
index 0000000000..7e03ddc827
--- /dev/null
+++ b/guest/spring-boot-app/docker/logback.xml
@@ -0,0 +1,15 @@
+
+
+
+
+ /var/log/Application/application.log
+ true
+
+ %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n
+
+
+
+
+
+
+
diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh
new file mode 100755
index 0000000000..aeecc29371
--- /dev/null
+++ b/guest/spring-boot-app/docker/run.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war
+
diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml
index ba57bbd5c5..c02eef7ef3 100644
--- a/guest/spring-boot-app/pom.xml
+++ b/guest/spring-boot-app/pom.xml
@@ -51,6 +51,22 @@
WebContent
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ com.stackify.Application
+ ${project.basedir}/docker
+
+
+
+
+
@@ -58,4 +74,4 @@
8.0.43
-
\ No newline at end of file
+
diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml
index 169b216ff9..da4d27b14d 100644
--- a/guest/spring-mvc/pom.xml
+++ b/guest/spring-mvc/pom.xml
@@ -27,28 +27,6 @@
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
UTF-8
UTF-8
diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml
index 16e946d108..793df750de 100644
--- a/guest/spring-security/pom.xml
+++ b/guest/spring-security/pom.xml
@@ -45,28 +45,6 @@
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
UTF-8
UTF-8
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
index e8fdabebbc..23d7d2e201 100644
--- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -1,5 +1,7 @@
package com.baeldung.hibernate;
+import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
+import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
import com.baeldung.hibernate.pessimisticlocking.Individual;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
@@ -70,6 +72,8 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
+ metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
+ metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
new file mode 100644
index 0000000000..f7b8e6bf6d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.jpabootstrap.application;
+
+import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
+import com.baeldung.hibernate.jpabootstrap.entities.User;
+import javax.persistence.EntityManager;
+
+public class Application {
+
+ public static void main(String[] args) {
+ EntityManager entityManager = getJpaEntityManager();
+ User user = entityManager.find(User.class, 1);
+ System.out.println(user);
+ entityManager.getTransaction().begin();
+ user.setName("John");
+ user.setEmail("john@domain.com");
+ entityManager.merge(user);
+ entityManager.getTransaction().commit();
+ entityManager.getTransaction().begin();
+ entityManager.persist(new User("Monica", "monica@domain.com"));
+ entityManager.getTransaction().commit();
+
+ // additional CRUD operations
+
+ }
+
+ private static class EntityManagerHolder {
+ private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
+ new Class[]{User.class}).getEntityManager();
+ }
+
+ public static EntityManager getJpaEntityManager() {
+ return EntityManagerHolder.ENTITY_MANAGER;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
new file mode 100644
index 0000000000..3852b44b64
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
@@ -0,0 +1,131 @@
+package com.baeldung.hibernate.jpabootstrap.config;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+import javax.sql.DataSource;
+import javax.persistence.SharedCacheMode;
+import javax.persistence.ValidationMode;
+import javax.persistence.spi.ClassTransformer;
+import javax.persistence.spi.PersistenceUnitInfo;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import org.hibernate.jpa.HibernatePersistenceProvider;
+
+public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
+
+ public static final String JPA_VERSION = "2.1";
+ private final String persistenceUnitName;
+ private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
+ private final List managedClassNames;
+ private final List mappingFileNames = new ArrayList<>();
+ private final Properties properties;
+ private DataSource jtaDataSource;
+ private DataSource nonjtaDataSource;
+ private final List transformers = new ArrayList<>();
+
+ public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) {
+ this.persistenceUnitName = persistenceUnitName;
+ this.managedClassNames = managedClassNames;
+ this.properties = properties;
+ }
+
+ @Override
+ public String getPersistenceUnitName() {
+ return persistenceUnitName;
+ }
+
+ @Override
+ public String getPersistenceProviderClassName() {
+ return HibernatePersistenceProvider.class.getName();
+ }
+
+ @Override
+ public PersistenceUnitTransactionType getTransactionType() {
+ return transactionType;
+ }
+
+ public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
+ this.jtaDataSource = jtaDataSource;
+ this.nonjtaDataSource = null;
+ transactionType = PersistenceUnitTransactionType.JTA;
+ return this;
+ }
+
+ @Override
+ public DataSource getJtaDataSource() {
+ return jtaDataSource;
+ }
+
+ public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
+ this.nonjtaDataSource = nonJtaDataSource;
+ this.jtaDataSource = null;
+ transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
+ return this;
+ }
+
+ @Override
+ public DataSource getNonJtaDataSource() {
+ return nonjtaDataSource;
+ }
+
+ @Override
+ public List getMappingFileNames() {
+ return mappingFileNames;
+ }
+
+ @Override
+ public List getJarFileUrls() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public URL getPersistenceUnitRootUrl() {
+ return null;
+ }
+
+ @Override
+ public List getManagedClassNames() {
+ return managedClassNames;
+ }
+
+ @Override
+ public boolean excludeUnlistedClasses() {
+ return false;
+ }
+
+ @Override
+ public SharedCacheMode getSharedCacheMode() {
+ return SharedCacheMode.UNSPECIFIED;
+ }
+
+ @Override
+ public ValidationMode getValidationMode() {
+ return ValidationMode.AUTO;
+ }
+
+ public Properties getProperties() {
+ return properties;
+ }
+
+ @Override
+ public String getPersistenceXMLSchemaVersion() {
+ return JPA_VERSION;
+ }
+
+ @Override
+ public ClassLoader getClassLoader() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+
+ @Override
+ public void addTransformer(ClassTransformer transformer) {
+ transformers.add(transformer);
+ }
+
+ @Override
+ public ClassLoader getNewTempClassLoader() {
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
new file mode 100644
index 0000000000..bc1932af6f
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
@@ -0,0 +1,69 @@
+package com.baeldung.hibernate.jpabootstrap.config;
+
+import com.mysql.cj.jdbc.MysqlDataSource;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.spi.PersistenceUnitInfo;
+import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
+import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
+
+public class JpaEntityManagerFactory {
+
+ private final String DB_URL = "jdbc:mysql://databaseurl";
+ private final String DB_USER_NAME = "username";
+ private final String DB_PASSWORD = "password";
+ private final Class[] entityClasses;
+
+ public JpaEntityManagerFactory(Class[] entityClasses) {
+ this.entityClasses = entityClasses;
+ }
+
+ public EntityManager getEntityManager() {
+ return getEntityManagerFactory().createEntityManager();
+ }
+
+ protected EntityManagerFactory getEntityManagerFactory() {
+ PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
+ Map configuration = new HashMap<>();
+ return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
+ .build();
+ }
+
+ protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
+ return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
+ }
+
+ protected List getEntityClassNames() {
+ return Arrays.asList(getEntities())
+ .stream()
+ .map(Class::getName)
+ .collect(Collectors.toList());
+ }
+
+ protected Properties getProperties() {
+ Properties properties = new Properties();
+ properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
+ properties.put("hibernate.id.new_generator_mappings", false);
+ properties.put("hibernate.connection.datasource", getMysqlDataSource());
+ return properties;
+ }
+
+ protected Class[] getEntities() {
+ return entityClasses;
+ }
+
+ protected DataSource getMysqlDataSource() {
+ MysqlDataSource mysqlDataSource = new MysqlDataSource();
+ mysqlDataSource.setURL(DB_URL);
+ mysqlDataSource.setUser(DB_USER_NAME);
+ mysqlDataSource.setPassword(DB_PASSWORD);
+ return mysqlDataSource;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
new file mode 100644
index 0000000000..86ca1dfa19
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
@@ -0,0 +1,45 @@
+package com.baeldung.hibernate.jpabootstrap.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "users")
+public class User {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+ private String name;
+ private String email;
+
+ public User(){}
+
+ public User(String name, String email) {
+ this.name = name;
+ this.email = email;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
new file mode 100644
index 0000000000..1af3e3e21b
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
@@ -0,0 +1,48 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import javax.persistence.*;
+
+@Entity
+public class OptimisticLockingCourse {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ @ManyToOne
+ @JoinTable(name = "optimistic_student_course")
+ private OptimisticLockingStudent student;
+
+ public OptimisticLockingCourse(Long id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public OptimisticLockingCourse() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public OptimisticLockingStudent getStudent() {
+ return student;
+ }
+
+ public void setStudent(OptimisticLockingStudent student) {
+ this.student = student;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
new file mode 100644
index 0000000000..b79212ae8d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
@@ -0,0 +1,70 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+public class OptimisticLockingStudent {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ private String lastName;
+ @Version
+ private Integer version;
+
+ @OneToMany(mappedBy = "student")
+ private List courses;
+
+ public OptimisticLockingStudent(Long id, String name, String lastName, List courses) {
+ this.id = id;
+ this.name = name;
+ this.lastName = lastName;
+ this.courses = courses;
+ }
+
+ public OptimisticLockingStudent() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public List getCourses() {
+ return courses;
+ }
+
+ public void setCourses(List courses) {
+ this.courses = courses;
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
new file mode 100644
index 0000000000..68b51764e4
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
@@ -0,0 +1,134 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import com.baeldung.hibernate.HibernateUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+import javax.persistence.LockModeType;
+import javax.persistence.OptimisticLockException;
+import java.io.IOException;
+import java.util.Arrays;
+
+public class OptimisticLockingIntegrationTest {
+
+ @Before
+ public void setUp() throws IOException {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH");
+ OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course));
+ course.setStudent(student);
+ entityManager.persist(course);
+ entityManager.persist(student);
+ entityManager.getTransaction()
+ .commit();
+ entityManager.close();
+ }
+
+ @After
+ public void clean() throws IOException {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L);
+ OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L);
+ entityManager.remove(course);
+ entityManager.remove(student);
+ entityManager.getTransaction()
+ .commit();
+ entityManager.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+ em.refresh(student, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+ em.lock(student, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
+ String propertyFileName = "hibernate-pessimistic-locking.properties";
+ EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
+ .openSession();
+ entityManager.getTransaction()
+ .begin();
+
+ return entityManager;
+ }
+}
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 8e4a9b28b7..b17ca2bfd9 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -6,10 +6,10 @@
hystrix
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml
index 461182e504..85078bd696 100644
--- a/java-websocket/pom.xml
+++ b/java-websocket/pom.xml
@@ -5,8 +5,6 @@
java-websocket
war
0.0.1-SNAPSHOT
- java-websocket Maven Webapp
- http://maven.apache.org
com.baeldung
diff --git a/javax-servlets/README.md b/javax-servlets/README.md
index ef8ec168cf..55ca1116aa 100644
--- a/javax-servlets/README.md
+++ b/javax-servlets/README.md
@@ -3,3 +3,5 @@
- [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp)
- [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session)
- [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet)
+- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file)
+- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response)
diff --git a/javax-servlets/src/main/java/com/baeldung/model/Employee.java b/javax-servlets/src/main/java/com/baeldung/model/Employee.java
index 9a85a69fff..698a598962 100644
--- a/javax-servlets/src/main/java/com/baeldung/model/Employee.java
+++ b/javax-servlets/src/main/java/com/baeldung/model/Employee.java
@@ -5,9 +5,9 @@ public class Employee {
private int id;
private String name;
private String department;
- private Double salary;
+ private long salary;
- public Employee(int id, String name, String department, Double salary) {
+ public Employee(int id, String name, String department, long salary) {
super();
this.id = id;
this.name = name;
@@ -61,11 +61,11 @@ public class Employee {
this.department = department;
}
- public Double getSalary() {
+ public long getSalary() {
return salary;
}
- public void setSalary(Double salary) {
+ public void setSalary(long salary) {
this.salary = salary;
}
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java
index ea82ca5055..dbc1a010f7 100644
--- a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java
@@ -14,18 +14,15 @@ import com.google.gson.Gson;
@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
public class EmployeeServlet extends HttpServlet {
+
+ private Gson gson = new Gson();
@Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
- int id = Integer.parseInt(request.getParameter("id"));
- String name = request.getParameter("name");
- String department = request.getParameter("department");
- Double salary = Double.parseDouble(request.getParameter("salary"));
-
- Employee employee = new Employee(id, name, department, salary);
- String employeeJsonString = new Gson().toJson(employee);
+ Employee employee = new Employee(1, "Karan", "IT", 5000);
+ String employeeJsonString = this.gson.toJson(employee);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java
index c96ad0a858..4fe4908075 100644
--- a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java
+++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java
@@ -36,21 +36,15 @@ public class EmployeeServletIntegrationTest {
int id = 1;
String name = "Karan Khanna";
String department = "IT";
- Double salary = 5000.0;
+ long salary = 5000;
employee = new Employee(id, name, department, salary);
- //when
- when(httpServletRequest.getParameter("id")).thenReturn(String.valueOf(id));
- when(httpServletRequest.getParameter("name")).thenReturn(name);
- when(httpServletRequest.getParameter("department")).thenReturn(department);
- when(httpServletRequest.getParameter("salary")).thenReturn(String.valueOf(salary));
-
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
when(httpServletResponse.getWriter()).thenReturn(pw);
EmployeeServlet employeeServlet = new EmployeeServlet();
- employeeServlet.doPost(httpServletRequest, httpServletResponse);
+ employeeServlet.doGet(httpServletRequest, httpServletResponse);
String employeeJsonString = sw.getBuffer().toString().trim();
Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class);
diff --git a/jaxb/pom.xml b/jaxb/pom.xml
index 26d7c8d362..f8e5ec0977 100644
--- a/jaxb/pom.xml
+++ b/jaxb/pom.xml
@@ -39,6 +39,11 @@
commons-lang3
${commons-lang3.version}
+
+ javax.activation
+ activation
+ 1.1
+
diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties
new file mode 100644
index 0000000000..5bc2bfe4b9
--- /dev/null
+++ b/jaxb/src/main/resources/log4jstructuraldp.properties
@@ -0,0 +1,9 @@
+
+# Root logger
+log4j.rootLogger=INFO, file, stdout
+
+# Write to console
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
index b2dde85c0f..77b7f1a0b3 100644
--- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
+++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
@@ -44,7 +44,7 @@ public class JaxbIntegrationTest {
File bookFile = new File(this.getClass().getResource("/book.xml").getFile());
String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8");
String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8");
- Assert.assertEquals(sampleBookXML, marshallerBookXML);
+ Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", ""));
}
@Test
diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml
new file mode 100644
index 0000000000..605d531b16
--- /dev/null
+++ b/jaxb/src/test/resources/book.xml
@@ -0,0 +1,5 @@
+
+
+ Book1
+ 2016-12-16T17:28:49.718Z
+
diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
similarity index 98%
rename from jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
index caeba95e45..0d6fd295e6 100644
--- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
@@ -22,7 +22,7 @@ import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@RunWith(Arquillian.class)
-public class ConvListValIntegrationTest {
+public class ConvListValLiveTest {
@ArquillianResource
private URL deploymentUrl;
diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
similarity index 98%
rename from jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
index 0e4c91ad67..41dde6549d 100644
--- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
-public class AutomaticTimerBeanIntegrationTest {
+public class AutomaticTimerBeanLiveTest {
//the @AutomaticTimerBean has a method called every 10 seconds
//testing the difference ==> 100000
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
similarity index 96%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
index 13cd1729db..350c094f38 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticAtFixedRateTimerBeanIntegrationTest {
+public class ProgrammaticAtFixedRateTimerBeanLiveTest {
final static long TIMEOUT = 1000;
final static long TOLERANCE = 500l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
similarity index 97%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
index b90cb6d909..ad079c131b 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
@@ -19,7 +19,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticTimerBeanIntegrationTest {
+public class ProgrammaticTimerBeanLiveTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
similarity index 96%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
index e2e660f79b..974f0a285f 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest {
+public class ProgrammaticWithFixedDelayTimerBeanLiveTest {
final static long TIMEOUT = 15000l;
final static long TOLERANCE = 1000l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
similarity index 97%
rename from jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
index 580edade77..a4ed9ceb68 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
@@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
-public class ScheduleTimerBeanIntegrationTest {
+public class ScheduleTimerBeanLiveTest {
private final static long TIMEOUT = 5000l;
private final static long TOLERANCE = 1000l;
diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml
index 77e214234e..e5593bdbb9 100644
--- a/jhipster/jhipster-microservice/car-app/pom.xml
+++ b/jhipster/jhipster-microservice/car-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.car.app
diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml
index beada8f064..3c21e0042f 100644
--- a/jhipster/jhipster-microservice/dealer-app/pom.xml
+++ b/jhipster/jhipster-microservice/dealer-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.dealer.app
diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml
index d90addf51b..42808e26ce 100644
--- a/jhipster/jhipster-microservice/gateway-app/pom.xml
+++ b/jhipster/jhipster-microservice/gateway-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.gateway
diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml
index fc8e8353b4..c8c9578fd6 100644
--- a/jhipster/jhipster-monolithic/pom.xml
+++ b/jhipster/jhipster-monolithic/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../parent-boot-5
+ ../../parent-boot-1
com.baeldung
diff --git a/jjwt/pom.xml b/jjwt/pom.xml
index 51d4dcf1c0..2aa52b8818 100644
--- a/jjwt/pom.xml
+++ b/jjwt/pom.xml
@@ -10,10 +10,10 @@
Exercising the JJWT
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/jmeter/pom.xml b/jmeter/pom.xml
index bb5769ef57..5f9509f0be 100644
--- a/jmeter/pom.xml
+++ b/jmeter/pom.xml
@@ -9,10 +9,10 @@
Intro to Performance testing using JMeter
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
similarity index 98%
rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java
rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
index c0fb5485aa..8bc8c854da 100644
--- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java
+++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
@@ -15,7 +15,7 @@ import org.junit.Test;
import com.baeldung.jpa.model.Car;
-public class StoredProcedureIntegrationTest {
+public class StoredProcedureLiveTest {
private static EntityManagerFactory factory = null;
private static EntityManager entityManager = null;
diff --git a/kotlin-js/README.md b/kotlin-js/README.md
new file mode 100644
index 0000000000..445ad6da9a
--- /dev/null
+++ b/kotlin-js/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Kotlin and Javascript](http://www.baeldung.com/kotlin-javascript)
diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java
index 61c98d0126..fd1e9c29a9 100644
--- a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java
+++ b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java
@@ -15,12 +15,13 @@ import static org.junit.Assert.assertEquals;
public class EntryProcessorIntegrationTest {
private static final String CACHE_NAME = "MyCache";
+ private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider";
private Cache cache;
@Before
public void instantiateCache() {
- CachingProvider cachingProvider = Caching.getCachingProvider();
+ CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME);
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration config = new MutableConfiguration<>();
this.cache = cacheManager.createCache(CACHE_NAME, config);
@@ -29,7 +30,7 @@ public class EntryProcessorIntegrationTest {
@After
public void tearDown() {
- Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
+ Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME);
}
@Test
diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java
index fcbfbe6111..512a75ec61 100644
--- a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java
+++ b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java
@@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals;
public class EventListenerIntegrationTest {
private static final String CACHE_NAME = "MyCache";
+ private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider";
private Cache cache;
private SimpleCacheEntryListener listener;
@@ -24,7 +25,7 @@ public class EventListenerIntegrationTest {
@Before
public void setup() {
- CachingProvider cachingProvider = Caching.getCachingProvider();
+ CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME);
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration config = new MutableConfiguration();
this.cache = cacheManager.createCache("MyCache", config);
@@ -33,7 +34,7 @@ public class EventListenerIntegrationTest {
@After
public void tearDown() {
- Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
+ Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME);
}
@Test
diff --git a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java
index fac3d32bcb..33521469fa 100644
--- a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java
+++ b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java
@@ -14,7 +14,7 @@ public class JCacheIntegrationTest {
@Test
public void instantiateCache() {
- CachingProvider cachingProvider = Caching.getCachingProvider();
+ CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider");
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration config = new MutableConfiguration<>();
Cache cache = cacheManager.createCache("simpleCache", config);
diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml
index a1951f09b7..6e5d212fb8 100644
--- a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml
+++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml
@@ -2,6 +2,6 @@
-
+
\ No newline at end of file
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 4f90d63d93..663b9e68bb 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -709,6 +709,20 @@
xchart
${xchart-version}
+
+
+ commons-net
+ commons-net
+ ${commons-net.version}
+
+
+ org.mockftpserver
+ MockFtpServer
+ ${mockftpserver.version}
+ test
+
+
+
@@ -923,6 +937,8 @@
2.5.11
3.6.1
3.5.2
+ 3.6
+ 2.7.1
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java
index 5b4097b1e4..a8c15887be 100644
--- a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java
+++ b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java
@@ -47,27 +47,29 @@ public class Histogram {
private Map processRawData() {
- List datasetList = Arrays.asList(36, 25, 38, 46, 55, 68, 72, 55, 36, 38, 67, 45, 22, 48, 91, 46, 52, 61, 58, 55);
+ List datasetList = Arrays.asList(
+ 36, 25, 38, 46, 55, 68, 72,
+ 55, 36, 38, 67, 45, 22, 48,
+ 91, 46, 52, 61, 58, 55);
Frequency frequency = new Frequency();
datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString())));
- List processed = new ArrayList();
- datasetList.forEach(d -> {
- double observation = Double.parseDouble(d.toString());
+ datasetList.stream()
+ .map(d -> Double.parseDouble(d.toString()))
+ .distinct()
+ .forEach(observation -> {
+ long observationFrequency = frequency.getCount(observation);
+ int upperBoundary = (observation > classWidth)
+ ? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth)
+ : classWidth;
+ int lowerBoundary = (upperBoundary > classWidth)
+ ? Math.subtractExact(upperBoundary, classWidth)
+ : 0;
+ String bin = lowerBoundary + "-" + upperBoundary;
- if(processed.contains(observation))
- return;
+ updateDistributionMap(lowerBoundary, bin, observationFrequency);
- long observationFrequency = frequency.getCount(observation);
- int upperBoundary = (observation > classWidth) ? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth) : classWidth;
- int lowerBoundary = (upperBoundary > classWidth) ? Math.subtractExact(upperBoundary, classWidth) : 0;
- String bin = lowerBoundary + "-" + upperBoundary;
-
- updateDistributionMap(lowerBoundary, bin, observationFrequency);
-
- processed.add(observation);
-
- });
+ });
return distributionMap;
}
diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java
new file mode 100644
index 0000000000..209bed35f0
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java
@@ -0,0 +1,63 @@
+package com.baeldung.ftp;
+
+import org.apache.commons.net.PrintCommandListener;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.net.ftp.FTPReply;
+
+import java.io.*;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.stream.Collectors;
+
+class FtpClient {
+
+ private final String server;
+ private final int port;
+ private final String user;
+ private final String password;
+ private FTPClient ftp;
+
+ FtpClient(String server, int port, String user, String password) {
+ this.server = server;
+ this.port = port;
+ this.user = user;
+ this.password = password;
+ }
+
+ void open() throws IOException {
+ ftp = new FTPClient();
+
+ ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
+
+ ftp.connect(server, port);
+ int reply = ftp.getReplyCode();
+ if (!FTPReply.isPositiveCompletion(reply)) {
+ ftp.disconnect();
+ throw new IOException("Exception in connecting to FTP Server");
+ }
+
+ ftp.login(user, password);
+ }
+
+ void close() throws IOException {
+ ftp.disconnect();
+ }
+
+ Collection listFiles(String path) throws IOException {
+ FTPFile[] files = ftp.listFiles(path);
+
+ return Arrays.stream(files)
+ .map(FTPFile::getName)
+ .collect(Collectors.toList());
+ }
+
+ void putFileToPath(File file, String path) throws IOException {
+ ftp.storeFile(path, new FileInputStream(file));
+ }
+
+ void downloadFile(String source, String destination) throws IOException {
+ FileOutputStream out = new FileOutputStream(destination);
+ ftp.retrieveFile(source, out);
+ }
+}
diff --git a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java
index fd713606cf..685890c6d7 100644
--- a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java
+++ b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java
@@ -14,7 +14,7 @@ public class UserController {
public static Handler fetchById = ctx -> {
int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
UserDao dao = UserDao.instance();
- User user = dao.getUserById(id);
+ User user = dao.getUserById(id).get();
if (user == null) {
ctx.html("Not Found");
} else {
diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java
new file mode 100644
index 0000000000..43da69f96d
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.ftp;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockftpserver.fake.FakeFtpServer;
+import org.mockftpserver.fake.UserAccount;
+import org.mockftpserver.fake.filesystem.DirectoryEntry;
+import org.mockftpserver.fake.filesystem.FileEntry;
+import org.mockftpserver.fake.filesystem.FileSystem;
+import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.Collection;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class FtpClientIntegrationTest {
+
+ private FakeFtpServer fakeFtpServer;
+
+ private FtpClient ftpClient;
+
+ @Before
+ public void setup() throws IOException {
+ fakeFtpServer = new FakeFtpServer();
+ fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
+
+ FileSystem fileSystem = new UnixFakeFileSystem();
+ fileSystem.add(new DirectoryEntry("/data"));
+ fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
+ fakeFtpServer.setFileSystem(fileSystem);
+ fakeFtpServer.setServerControlPort(0);
+
+ fakeFtpServer.start();
+
+ ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password");
+ ftpClient.open();
+ }
+
+ @After
+ public void teardown() throws IOException {
+ ftpClient.close();
+ fakeFtpServer.stop();
+ }
+
+ @Test
+ public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException {
+ Collection files = ftpClient.listFiles("");
+
+ assertThat(files).contains("foobar.txt");
+ }
+
+ @Test
+ public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
+ ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt");
+
+ assertThat(new File("downloaded_buz.txt")).exists();
+ new File("downloaded_buz.txt").delete(); // cleanup
+ }
+
+ @Test
+ public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException {
+ File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI());
+
+ ftpClient.putFileToPath(file, "/buz.txt");
+
+ assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue();
+ }
+
+}
diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java
new file mode 100644
index 0000000000..ef6809b02d
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.ftp;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockftpserver.fake.FakeFtpServer;
+import org.mockftpserver.fake.UserAccount;
+import org.mockftpserver.fake.filesystem.DirectoryEntry;
+import org.mockftpserver.fake.filesystem.FileEntry;
+import org.mockftpserver.fake.filesystem.FileSystem;
+import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.file.Files;
+import java.util.Collection;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class JdkFtpClientIntegrationTest {
+
+ private FakeFtpServer fakeFtpServer;
+
+
+ @Before
+ public void setup() throws IOException {
+ fakeFtpServer = new FakeFtpServer();
+ fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
+
+ FileSystem fileSystem = new UnixFakeFileSystem();
+ fileSystem.add(new DirectoryEntry("/data"));
+ fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
+ fakeFtpServer.setFileSystem(fileSystem);
+ fakeFtpServer.setServerControlPort(0);
+
+ fakeFtpServer.start();
+ }
+
+ @After
+ public void teardown() throws IOException {
+ fakeFtpServer.stop();
+ }
+
+ @Test
+ public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
+ String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort());
+
+ URLConnection urlConnection = new URL(ftpUrl).openConnection();
+ InputStream inputStream = urlConnection.getInputStream();
+ Files.copy(inputStream, new File("downloaded_buz.txt").toPath());
+ inputStream.close();
+
+ assertThat(new File("downloaded_buz.txt")).exists();
+
+ new File("downloaded_buz.txt").delete(); // cleanup
+ }
+
+}
diff --git a/libraries/src/test/resources/ftp/baz.txt b/libraries/src/test/resources/ftp/baz.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java
index e4404a6528..53634002a0 100644
--- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java
+++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java
@@ -12,6 +12,7 @@ import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
+
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest {
diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml
index 2b7a238ee8..77d13cd5c6 100644
--- a/mesos-marathon/pom.xml
+++ b/mesos-marathon/pom.xml
@@ -7,10 +7,10 @@
0.0.1-SNAPSHOT
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
diff --git a/msf4j/README.md b/msf4j/README.md
new file mode 100644
index 0000000000..7c66b8dc5f
--- /dev/null
+++ b/msf4j/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/msf4j)
diff --git a/msf4j/pom.xml b/msf4j/pom.xml
new file mode 100644
index 0000000000..f691d746b7
--- /dev/null
+++ b/msf4j/pom.xml
@@ -0,0 +1,32 @@
+
+
+
+ org.wso2.msf4j
+ msf4j-service
+ 2.6.0
+
+ 4.0.0
+
+ com.baeldung.msf4j
+ msf4j
+ 0.0.1-SNAPSHOT
+ WSO2 MSF4J Microservice
+
+
+ com.baeldung.msf4j.msf4jintro.Application
+
+
+
+ org.wso2.msf4j
+ msf4j-spring
+ 2.6.1
+
+
+ org.wso2.msf4j
+ msf4j-mustache-template
+ 2.6.1
+
+
+
+
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java
new file mode 100644
index 0000000000..c4cf136536
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java
@@ -0,0 +1,11 @@
+package com.baeldung.msf4j.msf4japi;
+
+import org.wso2.msf4j.MicroservicesRunner;
+
+public class Application {
+ public static void main(String[] args) {
+ new MicroservicesRunner()
+ .deploy(new MenuService())
+ .start();
+ }
+}
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java
new file mode 100644
index 0000000000..d17a7a1034
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java
@@ -0,0 +1,20 @@
+package com.baeldung.msf4j.msf4japi;
+
+public class Meal {
+ private String name;
+ private Float price;
+
+ public Meal(String name, Float price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Float getPrice() {
+ return price;
+ }
+
+}
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java
new file mode 100644
index 0000000000..4f880a1393
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java
@@ -0,0 +1,78 @@
+package com.baeldung.msf4j.msf4japi;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+
+import com.google.gson.Gson;
+
+@Path("/menu")
+public class MenuService {
+
+ private List meals = new ArrayList();
+
+ public MenuService() {
+ meals.add(new Meal("Java beans",42.0f));
+ }
+
+ @GET
+ @Path("/")
+ @Produces({ "application/json" })
+ public Response index() {
+ return Response.ok()
+ .entity(meals)
+ .build();
+ }
+
+ @GET
+ @Path("/{id}")
+ @Produces({ "application/json" })
+ public Response meal(@PathParam("id") int id) {
+ return Response.ok()
+ .entity(meals.get(id))
+ .build();
+ }
+
+
+ @POST
+ @Path("/")
+ @Consumes("application/json")
+ @Produces({ "application/json" })
+ public Response create(Meal meal) {
+ meals.add(meal);
+ return Response.ok()
+ .entity(meal)
+ .build();
+ }
+
+ @PUT
+ @Path("/{id}")
+ @Consumes("application/json")
+ @Produces({ "application/json" })
+ public Response update(@PathParam("id") int id, Meal meal) {
+ meals.set(id, meal);
+ return Response.ok()
+ .entity(meal)
+ .build();
+ }
+
+ @DELETE
+ @Path("/{id}")
+ @Produces({ "application/json" })
+ public Response delete(@PathParam("id") int id) {
+ Meal meal = meals.get(id);
+ meals.remove(id);
+ return Response.ok()
+ .entity(meal)
+ .build();
+ }
+}
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java
new file mode 100644
index 0000000000..dc4a060056
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java
@@ -0,0 +1,11 @@
+package com.baeldung.msf4j.msf4jintro;
+
+import org.wso2.msf4j.MicroservicesRunner;
+
+public class Application {
+ public static void main(String[] args) {
+ new MicroservicesRunner()
+ .deploy(new SimpleService())
+ .start();
+ }
+}
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java
new file mode 100644
index 0000000000..bcb52859b5
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java
@@ -0,0 +1,21 @@
+package com.baeldung.msf4j.msf4jintro;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+
+@Path("/")
+public class SimpleService {
+
+ @GET
+ public String index() {
+ return "Default content";
+ }
+
+ @GET
+ @Path("/say/{name}")
+ public String say(@PathParam("name") String name) {
+ return "Hello " + name;
+ }
+
+}
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java
new file mode 100644
index 0000000000..2a5232a7e6
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java
@@ -0,0 +1,10 @@
+package com.baeldung.msf4j.msf4jspring;
+
+import org.wso2.msf4j.spring.MSF4JSpringApplication;
+
+public class Application {
+
+ public static void main(String[] args) {
+ MSF4JSpringApplication.run(Application.class, args);
+ }
+}
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java
new file mode 100644
index 0000000000..c3313fc3b1
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java
@@ -0,0 +1,15 @@
+package com.baeldung.msf4j.msf4jspring.configuration;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.wso2.msf4j.spring.transport.HTTPTransportConfig;
+
+@Configuration
+public class PortConfiguration {
+
+ @Bean
+ public HTTPTransportConfig http() {
+ return new HTTPTransportConfig(9090);
+ }
+
+}
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java
new file mode 100644
index 0000000000..99de0abc4c
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java
@@ -0,0 +1,20 @@
+package com.baeldung.msf4j.msf4jspring.domain;
+
+public class Meal {
+ private String name;
+ private Float price;
+
+ public Meal(String name, Float price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Float getPrice() {
+ return price;
+ }
+
+}
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java
new file mode 100644
index 0000000000..4d9e54348e
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java
@@ -0,0 +1,37 @@
+package com.baeldung.msf4j.msf4jspring.repositories;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.springframework.stereotype.Component;
+import com.baeldung.msf4j.msf4jspring.domain.Meal;
+
+@Component
+public class MealRepository {
+
+ private List meals = new ArrayList();
+
+ public MealRepository() {
+ meals.add(new Meal("Salad", 4.2f));
+ meals.add(new Meal("Litre of cola", 2.99f));
+ }
+
+ public void create(Meal meal) {
+ meals.add(meal);
+ }
+
+ public void remove(Meal meal) {
+ meals.remove(meal);
+ }
+
+ public Meal find(int id) {
+ return meals.get(id);
+ }
+
+ public List findAll() {
+ return meals;
+ }
+
+ public void update(int id, Meal meal) {
+ meals.set(id, meal);
+ }
+}
\ No newline at end of file
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java
new file mode 100644
index 0000000000..9c617257cb
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java
@@ -0,0 +1,47 @@
+package com.baeldung.msf4j.msf4jspring.resources;
+
+import java.util.Collections;
+import java.util.Map;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.wso2.msf4j.template.MustacheTemplateEngine;
+
+import com.baeldung.msf4j.msf4jspring.services.MealService;
+
+@Component
+@Path("/meal")
+public class MealResource {
+
+ @Autowired
+ private MealService mealService;
+
+ @GET
+ @Path("/")
+ public Response all() {
+ Map map = Collections.singletonMap("meals", mealService.findAll());
+ String html = MustacheTemplateEngine.instance()
+ .render("meals.mustache", map);
+ return Response.ok()
+ .type(MediaType.TEXT_HTML)
+ .entity(html)
+ .build();
+ }
+
+ @GET
+ @Path("/{id}")
+ @Produces({ "text/xml" })
+ public Response meal(@PathParam("id") int id) {
+ return Response.ok()
+ .entity(mealService.find(id))
+ .build();
+ }
+
+}
diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java
new file mode 100644
index 0000000000..fd6a519999
--- /dev/null
+++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java
@@ -0,0 +1,27 @@
+package com.baeldung.msf4j.msf4jspring.services;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.baeldung.msf4j.msf4jspring.domain.Meal;
+import com.baeldung.msf4j.msf4jspring.repositories.MealRepository;
+
+@Service
+public class MealService {
+ @Autowired
+ private MealRepository mealRepository;
+
+ public Meal find(int id) {
+ return mealRepository.find(id);
+ }
+
+ public List findAll() {
+ return mealRepository.findAll();
+ }
+
+ public void create(Meal meal) {
+ mealRepository.create(meal);
+ }
+}
diff --git a/msf4j/src/main/resources/application.properties b/msf4j/src/main/resources/application.properties
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/msf4j/src/main/resources/templates/meals.mustache b/msf4j/src/main/resources/templates/meals.mustache
new file mode 100644
index 0000000000..f4bdfaccf9
--- /dev/null
+++ b/msf4j/src/main/resources/templates/meals.mustache
@@ -0,0 +1,13 @@
+
+
+ Meals
+
+
+
+
Today's Meals
+ {{#meals}}
+
{{name}}: {{price}}$
+ {{/meals}}
+
+
+