diff --git a/annotations/readme.md b/annotations/readme.md
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/annotations/readme.md
@@ -0,0 +1 @@
+
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
new file mode 100644
index 0000000000..1f83ecf934
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -0,0 +1,54 @@
+
+
+
+ 4.0.0
+ cxf-jaxrs-implementation
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+ UTF-8
+ 3.1.7
+ 4.5.2
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+
+ com.baeldung.cxf.jaxrs.implementation.RestfulServer
+
+
+
+ maven-surefire-plugin
+ 2.19.1
+
+
+ **/ServiceTest
+
+
+
+
+
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxrs
+ ${cxf.version}
+
+
+ org.apache.cxf
+ cxf-rt-transports-http-jetty
+ ${cxf.version}
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java
new file mode 100644
index 0000000000..592df4b7c3
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java
@@ -0,0 +1,62 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Path("baeldung")
+@Produces("text/xml")
+public class Baeldung {
+ private Map courses = new HashMap<>();
+
+ {
+ Student student1 = new Student();
+ Student student2 = new Student();
+ student1.setId(1);
+ student1.setName("Student A");
+ student2.setId(2);
+ student2.setName("Student B");
+
+ List course1Students = new ArrayList<>();
+ course1Students.add(student1);
+ course1Students.add(student2);
+
+ Course course1 = new Course();
+ Course course2 = new Course();
+ course1.setId(1);
+ course1.setName("REST with Spring");
+ course1.setStudents(course1Students);
+ course2.setId(2);
+ course2.setName("Learn Spring Security");
+
+ courses.put(1, course1);
+ courses.put(2, course2);
+ }
+
+ @GET
+ @Path("courses/{courseOrder}")
+ public Course getCourse(@PathParam("courseOrder") int courseOrder) {
+ return courses.get(courseOrder);
+ }
+
+ @PUT
+ @Path("courses/{courseOrder}")
+ public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) {
+ Course existingCourse = courses.get(courseOrder);
+
+ if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) {
+ courses.put(courseOrder, course);
+ return Response.ok().build();
+ }
+
+ return Response.notModified().build();
+ }
+
+ @Path("courses/{courseOrder}/students")
+ public Course pathToStudent(@PathParam("courseOrder") int courseOrder) {
+ return courses.get(courseOrder);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
new file mode 100644
index 0000000000..32689a332f
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
@@ -0,0 +1,65 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Response;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.ArrayList;
+import java.util.List;
+
+@XmlRootElement(name = "Course")
+public class Course {
+ private int id;
+ private String name;
+ private List students;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getStudents() {
+ return students;
+ }
+
+ public void setStudents(List students) {
+ this.students = students;
+ }
+
+ @GET
+ @Path("{studentOrder}")
+ public Student getStudent(@PathParam("studentOrder")int studentOrder) {
+ return students.get(studentOrder);
+ }
+
+ @POST
+ public Response postStudent(Student student) {
+ if (students == null) {
+ students = new ArrayList<>();
+ }
+ students.add(student);
+ return Response.ok(student).build();
+ }
+
+ @DELETE
+ @Path("{studentOrder}")
+ public Response deleteStudent(@PathParam("studentOrder") int studentOrder) {
+ Student student = students.get(studentOrder);
+ if (student != null) {
+ students.remove(studentOrder);
+ return Response.ok().build();
+ } else {
+ return Response.notModified().build();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java
new file mode 100644
index 0000000000..bb35bab3f8
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java
@@ -0,0 +1,21 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
+
+public class RestfulServer {
+ public static void main(String args[]) throws Exception {
+ JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
+ factoryBean.setResourceClasses(Baeldung.class);
+ factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung()));
+ factoryBean.setAddress("http://localhost:8080/");
+ Server server = factoryBean.create();
+
+ System.out.println("Server ready...");
+ Thread.sleep(60 * 1000);
+ System.out.println("Server exiting");
+ server.destroy();
+ System.exit(0);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
new file mode 100644
index 0000000000..de782e4edb
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
@@ -0,0 +1,25 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "Student")
+public class Student {
+ private int id;
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml
new file mode 100644
index 0000000000..465c337745
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml
@@ -0,0 +1,4 @@
+
+ 3
+ Apache CXF Support for RESTful
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml
new file mode 100644
index 0000000000..7fb6189815
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml
@@ -0,0 +1,5 @@
+
+
+ 3
+ Student C
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java
new file mode 100644
index 0000000000..8c606436c8
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.InputStreamEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.xml.bind.JAXB;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+
+import static org.junit.Assert.assertEquals;
+
+public class ServiceTest {
+ private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
+ private static CloseableHttpClient client;
+
+ @BeforeClass
+ public static void createClient() {
+ client = HttpClients.createDefault();
+ }
+
+ @AfterClass
+ public static void closeClient() throws IOException {
+ client.close();
+ }
+
+ @Test
+ public void whenPutCourse_thenCorrect() throws IOException {
+ HttpPut httpPut = new HttpPut(BASE_URL + "3");
+ InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml");
+ httpPut.setEntity(new InputStreamEntity(resourceStream));
+ httpPut.setHeader("Content-Type", "text/xml");
+
+ HttpResponse response = client.execute(httpPut);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ Course course = getCourse(3);
+ assertEquals(3, course.getId());
+ assertEquals("Apache CXF Support for RESTful", course.getName());
+ }
+
+ @Test
+ public void whenPostStudent_thenCorrect() throws IOException {
+ HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
+ InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml");
+ httpPost.setEntity(new InputStreamEntity(resourceStream));
+ httpPost.setHeader("Content-Type", "text/xml");
+
+ HttpResponse response = client.execute(httpPost);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ Student student = getStudent(2, 0);
+ assertEquals(3, student.getId());
+ assertEquals("Student C", student.getName());
+ }
+
+ @Test
+ public void whenDeleteStudent_thenCorrect() throws IOException {
+ HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0");
+ HttpResponse response = client.execute(httpDelete);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ Course course = getCourse(1);
+ assertEquals(1, course.getStudents().size());
+ assertEquals(2, course.getStudents().get(0).getId());
+ assertEquals("Student B", course.getStudents().get(0).getName());
+ }
+
+ private Course getCourse(int courseOrder) throws IOException {
+ URL url = new URL(BASE_URL + courseOrder);
+ InputStream input = url.openStream();
+ return JAXB.unmarshal(new InputStreamReader(input), Course.class);
+ }
+
+ private Student getStudent(int courseOrder, int studentOrder) throws IOException {
+ URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
+ InputStream input = url.openStream();
+ return JAXB.unmarshal(new InputStreamReader(input), Student.class);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 022fc59f9b..af7949bb6c 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -8,6 +8,7 @@
cxf-introductioncxf-spring
+ cxf-jaxrs-implementation
diff --git a/assertj/pom.xml b/assertj/pom.xml
index 421afd40a5..df55ebba4b 100644
--- a/assertj/pom.xml
+++ b/assertj/pom.xml
@@ -1,7 +1,6 @@
-
+4.0.0com.baeldung
@@ -9,11 +8,18 @@
1.0.0-SNAPSHOT
+
com.google.guavaguava
- 19.0
+ ${guava.version}
+
+ org.assertj
+ assertj-guava
+ 3.0.0
+
+
junitjunit
@@ -26,11 +32,7 @@
3.5.1test
-
- org.assertj
- assertj-guava
- 3.0.0
-
+
@@ -46,4 +48,9 @@
+
+
+ 19.0
+
+
\ No newline at end of file
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 566eb4e43a..22e3bab595 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -15,7 +15,7 @@
commons-iocommons-io
- 2.4
+ 2.5
diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java
index 8143da5794..1918c801dc 100644
--- a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java
+++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java
@@ -1,17 +1,71 @@
package com.baeldung;
+import com.google.common.collect.Lists;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
+import java.util.*;
+import java.util.concurrent.ThreadLocalRandom;
public class RandomListElementTest {
@Test
- public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() {
- List givenList = Arrays.asList(1, 2, 3);
+ public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
+ List givenList = Lists.newArrayList(1, 2, 3);
Random rand = new Random();
+
givenList.get(rand.nextInt(givenList.size()));
}
+
+ @Test
+ public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
+ List givenList = Lists.newArrayList(1, 2, 3);
+
+ givenList.get((int)(Math.random() * givenList.size()));
+ }
+
+ @Test
+ public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
+ Random rand = new Random();
+ List givenList = Lists.newArrayList("one", "two", "three", "four");
+
+ int numberOfElements = 2;
+
+ for (int i = 0; i < numberOfElements; i++) {
+ int randomIndex = rand.nextInt(givenList.size());
+ givenList.get(randomIndex);
+ }
+ }
+
+ @Test
+ public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
+ Random rand = new Random();
+ List givenList = Lists.newArrayList("one", "two", "three", "four");
+
+ int numberOfElements = 2;
+
+ for (int i = 0; i < numberOfElements; i++) {
+ int randomIndex = rand.nextInt(givenList.size());
+ givenList.get(randomIndex);
+ givenList.remove(randomIndex);
+ }
+ }
+
+ @Test
+ public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
+ List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
+ Collections.shuffle(givenList);
+
+ int randomSeriesLength = 3;
+
+ givenList.subList(0, randomSeriesLength - 1);
+ }
+
+ @Test
+ public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() {
+ List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
+ int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size();
+
+ givenList.get(randomIndex);
+ }
+
}
diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java
new file mode 100644
index 0000000000..62d2663994
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java
@@ -0,0 +1,38 @@
+package com.baeldung.encoderdecoder;
+
+import org.hamcrest.CoreMatchers;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+
+public class EncoderDecoder {
+
+ @Test
+ public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException {
+ String plainURL = "http://www.baeldung.com" ;
+ String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString());
+
+ Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL));
+ }
+
+ @Test
+ public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException {
+ String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ;
+ String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString());
+
+ Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL));
+ }
+
+ @Test
+ public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException {
+ String encodedURL = "http%3A%2F%2Fwww.baeldung.com";
+
+ String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString());
+
+ Assert.assertFalse("http://www.baeldung.com".equals(decodedURL));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java
index b1476b6360..e21af9552a 100644
--- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java
+++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java
@@ -1,17 +1,24 @@
package com.baeldung.file;
+import org.apache.commons.io.FileUtils;
+import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
-
-import static org.hamcrest.CoreMatchers.containsString;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
public class FileOperationsTest {
@@ -20,34 +27,22 @@ public class FileOperationsTest {
String expectedData = "Hello World from fileTest.txt!!!";
ClassLoader classLoader = getClass().getClassLoader();
- InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
-
- Assert.assertThat(data, containsString(expectedData));
-}
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
@Test
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
-
+
Class clazz = FileOperationsTest.class;
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
- Assert.assertThat(data, containsString(expectedData));
- }
-
- @Test
- public void givenURLName_whenUsingURL_thenFileData() throws IOException {
- String expectedData = "Baeldung";
-
- URL urlObject = new URL("http://www.baeldung.com/");
- URLConnection urlConnection = urlObject.openConnection();
-
- InputStream inputStream = urlConnection.getInputStream();
- String data = readFromInputStream(inputStream);
-
- Assert.assertThat(data, containsString(expectedData));
+ Assert.assertEquals(expectedData, data.trim());
}
@Test
@@ -58,21 +53,69 @@ public class FileOperationsTest {
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
- Assert.assertThat(data, containsString(expectedData));
+ Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
+ @Test
+ public void givenURLName_whenUsingURL_thenFileData() throws IOException {
+ String expectedData = "Baeldung";
+
+ URL urlObject = new URL("http://www.baeldung.com/");
+
+ URLConnection urlConnection = urlObject.openConnection();
+
+ InputStream inputStream = urlConnection.getInputStream();
+ String data = readFromInputStream(inputStream);
+
+ Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
+ }
+
+ @Test
+ public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ String data = FileUtils.readFileToString(file);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
+
+ byte[] fileBytes = Files.readAllBytes(path);
+ String data = new String(fileBytes);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
+
+ StringBuilder data = new StringBuilder();
+ Stream lines = Files.lines(path);
+ lines.forEach(line -> data.append(line).append("\n"));
+ lines.close();
+
+ Assert.assertEquals(expectedData, data.toString().trim());
+ }
+
private String readFromInputStream(InputStream inputStream) throws IOException {
- InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder resultStringBuilder = new StringBuilder();
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- resultStringBuilder.append(line);
- resultStringBuilder.append("\n");
+ try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ resultStringBuilder.append(line).append("\n");
+ }
}
- bufferedReader.close();
- inputStreamReader.close();
- inputStream.close();
+
return resultStringBuilder.toString();
}
}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java
index 06d9394a5e..da9027060e 100644
--- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java
@@ -1,47 +1,41 @@
package com.baeldung.util;
-import static org.junit.Assert.assertEquals;
-
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalTime;
-import java.time.temporal.ChronoField;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-
import org.junit.Test;
+import java.time.*;
+import java.time.temporal.ChronoField;
+
+import static org.junit.Assert.assertEquals;
+
public class CurrentDateTimeTest {
+ private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
+
@Test
public void shouldReturnCurrentDate() {
- final LocalDate now = LocalDate.now();
- final Calendar calendar = GregorianCalendar.getInstance();
+ final LocalDate now = LocalDate.now(clock);
- assertEquals("10-10-2010".length(), now.toString().length());
- assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH));
- assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1);
- assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
+ assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
+ assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
+ assertEquals(2016, now.get(ChronoField.YEAR));
}
@Test
public void shouldReturnCurrentTime() {
- final LocalTime now = LocalTime.now();
- final Calendar calendar = GregorianCalendar.getInstance();
+ final LocalTime now = LocalTime.now(clock);
- assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY));
- assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR));
- assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE));
+ assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
+ assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
+ assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
}
@Test
public void shouldReturnCurrentTimestamp() {
- final Instant now = Instant.now();
- final Calendar calendar = GregorianCalendar.getInstance();
+ final Instant now = Instant.now(clock);
- assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
+ assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD
@@ -0,0 +1 @@
+
diff --git a/core-java/pom.xml b/core-java/pom.xml
index bce97d1148..a5e89d2a76 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -174,7 +174,7 @@
5.1.38
- 2.7.2
+ 2.7.81.7.13
diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java
new file mode 100644
index 0000000000..1c034051aa
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java
@@ -0,0 +1,46 @@
+package com.baeldung.java.nio.selector;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+
+public class EchoClient {
+ private static SocketChannel client;
+ private static ByteBuffer buffer;
+ private static EchoClient instance;
+
+ public static EchoClient start() {
+ if (instance == null)
+ instance = new EchoClient();
+
+ return instance;
+ }
+
+ private EchoClient() {
+ try {
+ client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
+ buffer = ByteBuffer.allocate(256);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String sendMessage(String msg) {
+ buffer = ByteBuffer.wrap(msg.getBytes());
+ String response = null;
+ try {
+ client.write(buffer);
+ buffer.clear();
+ client.read(buffer);
+ response = new String(buffer.array()).trim();
+ System.out.println("response=" + response);
+ buffer.clear();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return response;
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java
new file mode 100644
index 0000000000..aedcbb319b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java
@@ -0,0 +1,50 @@
+package com.baeldung.java.nio.selector;
+
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.Selector;
+import java.nio.channels.SelectionKey;
+import java.nio.ByteBuffer;
+import java.io.IOException;
+import java.util.Set;
+import java.util.Iterator;
+import java.net.InetSocketAddress;
+
+public class EchoServer {
+
+ public static void main(String[] args)
+
+ throws IOException {
+ Selector selector = Selector.open();
+ ServerSocketChannel serverSocket = ServerSocketChannel.open();
+ serverSocket.bind(new InetSocketAddress("localhost", 5454));
+ serverSocket.configureBlocking(false);
+ serverSocket.register(selector, SelectionKey.OP_ACCEPT);
+ ByteBuffer buffer = ByteBuffer.allocate(256);
+
+ while (true) {
+ selector.select();
+ Set selectedKeys = selector.selectedKeys();
+ Iterator iter = selectedKeys.iterator();
+ while (iter.hasNext()) {
+
+ SelectionKey key = iter.next();
+
+ if (key.isAcceptable()) {
+ SocketChannel client = serverSocket.accept();
+ client.configureBlocking(false);
+ client.register(selector, SelectionKey.OP_READ);
+ }
+
+ if (key.isReadable()) {
+ SocketChannel client = (SocketChannel) key.channel();
+ client.read(buffer);
+ buffer.flip();
+ client.write(buffer);
+ buffer.clear();
+ }
+ iter.remove();
+ }
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/regex/Result.java b/core-java/src/main/java/com/baeldung/java/regex/Result.java
deleted file mode 100644
index d47c94ad2e..0000000000
--- a/core-java/src/main/java/com/baeldung/java/regex/Result.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.baeldung.java.regex;
-
-public class Result {
- private boolean found = false;
- private int count = 0;
-
- public Result() {
-
- }
-
- public boolean isFound() {
- return found;
- }
-
- public void setFound(boolean found) {
- this.found = found;
- }
-
- public int getCount() {
- return count;
- }
-
- public void setCount(int count) {
- this.count = count;
- }
-
-}
diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java
new file mode 100644
index 0000000000..63da2fe2bf
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java
@@ -0,0 +1,18 @@
+package com.baeldung.java.nio.selector;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class EchoTest {
+
+ @Test
+ public void givenClient_whenServerEchosMessage_thenCorrect() {
+ EchoClient client = EchoClient.start();
+ String resp1 = client.sendMessage("hello");
+ String resp2 = client.sendMessage("world");
+ assertEquals("hello", resp1);
+ assertEquals("world", resp2);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java
index 257e486600..414401eb85 100644
--- a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java
+++ b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java
@@ -13,366 +13,368 @@ public class RegexTest {
@Test
public void givenText_whenSimpleRegexMatches_thenCorrect() {
- Result result = runTest("foo", "foo");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
-
+ Pattern pattern = Pattern.compile("foo");
+ Matcher matcher = pattern.matcher("foo");
+ assertTrue(matcher.find());
}
@Test
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
- Result result = runTest("foo", "foofoo");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ Pattern pattern = Pattern.compile("foo");
+ Matcher matcher = pattern.matcher("foofoo");
+ int matches = 0;
+ while (matcher.find())
+ matches++;
+ assertEquals(matches, 2);
}
@Test
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
- Result result = runTest(".", "foo");
- assertTrue(result.isFound());
+ int matches = runTest(".", "foo");
+ assertTrue(matches > 0);
}
@Test
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
- Result result = runTest("foo.", "foofoo");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("foo.", "foofoo");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenORSet_whenMatchesAny_thenCorrect() {
- Result result = runTest("[abc]", "b");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("[abc]", "b");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
- Result result = runTest("[abc]", "cab");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("[abc]", "cab");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
- Result result = runTest("[bcr]at", "bat cat rat");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("[bcr]at", "bat cat rat");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenNORSet_whenMatchesNon_thenCorrect() {
- Result result = runTest("[^abc]", "g");
- assertTrue(result.isFound());
+ int matches = runTest("[^abc]", "g");
+ assertTrue(matches > 0);
}
@Test
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
- Result result = runTest("[^bcr]at", "sat mat eat");
- assertTrue(result.isFound());
+ int matches = runTest("[^bcr]at", "sat mat eat");
+ assertTrue(matches > 0);
}
@Test
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
- Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
- Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 26);
+ int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 26);
}
@Test
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
- Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 28);
+ int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 28);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
- Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
- Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
- Result result = runTest("[1-3[7-9]]", "123456789");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 6);
+ int matches = runTest("[1-3[7-9]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 6);
}
@Test
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
- Result result = runTest("[1-6&&[3-9]]", "123456789");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 4);
+ int matches = runTest("[1-6&&[3-9]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 4);
}
@Test
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
- Result result = runTest("[0-9&&[^2468]]", "123456789");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 5);
+ int matches = runTest("[0-9&&[^2468]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 5);
}
@Test
public void givenDigits_whenMatches_thenCorrect() {
- Result result = runTest("\\d", "123");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("\\d", "123");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenNonDigits_whenMatches_thenCorrect() {
- Result result = runTest("\\D", "a6c");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("\\D", "a6c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenWhiteSpace_whenMatches_thenCorrect() {
- Result result = runTest("\\s", "a c");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("\\s", "a c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
- Result result = runTest("\\S", "a c");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("\\S", "a c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenWordCharacter_whenMatches_thenCorrect() {
- Result result = runTest("\\w", "hi!");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("\\w", "hi!");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenNonWordCharacter_whenMatches_thenCorrect() {
- Result result = runTest("\\W", "hi!");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("\\W", "hi!");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
- Result result = runTest("\\a?", "hi");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("\\a?", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
- Result result = runTest("\\a{0,1}", "hi");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("\\a{0,1}", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
- Result result = runTest("\\a*", "hi");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("\\a*", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
- Result result = runTest("\\a{0,}", "hi");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 3);
+ int matches = runTest("\\a{0,}", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
- Result result = runTest("\\a+", "hi");
- assertFalse(result.isFound());
+ int matches = runTest("\\a+", "hi");
+ assertFalse(matches > 0);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
- Result result = runTest("\\a{1,}", "hi");
- assertFalse(result.isFound());
+ int matches = runTest("\\a{1,}", "hi");
+ assertFalse(matches > 0);
}
@Test
public void givenBraceQuantifier_whenMatches_thenCorrect() {
- Result result = runTest("a{3}", "aaaaaa");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("a{3}", "aaaaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
- Result result = runTest("a{3}", "aa");
- assertFalse(result.isFound());
+ int matches = runTest("a{3}", "aa");
+ assertFalse(matches > 0);
}
@Test
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
- Result result = runTest("a{2,3}", "aaaa");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("a{2,3}", "aaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
- Result result = runTest("a{2,3}?", "aaaa");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("a{2,3}?", "aaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect() {
- Result result = runTest("(\\d\\d)", "12");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("(\\d\\d)", "12");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect2() {
- Result result = runTest("(\\d\\d)", "1212");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 2);
+ int matches = runTest("(\\d\\d)", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect3() {
- Result result = runTest("(\\d\\d)(\\d\\d)", "1212");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
- Result result = runTest("(\\d\\d)\\1", "1212");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("(\\d\\d)\\1", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
- Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212");
- assertTrue(result.isFound());
- assertEquals(result.getCount(), 1);
+ int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
}
@Test
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
- Result result = runTest("(\\d\\d)\\1", "1213");
- assertFalse(result.isFound());
+ int matches = runTest("(\\d\\d)\\1", "1213");
+ assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtBeginning_thenCorrect() {
- Result result = runTest("^dog", "dogs are friendly");
- assertTrue(result.isFound());
+ int matches = runTest("^dog", "dogs are friendly");
+ assertTrue(matches > 0);
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
- Result result = runTest("^dog", "are dogs are friendly?");
- assertFalse(result.isFound());
+ int matches = runTest("^dog", "are dogs are friendly?");
+ assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtEnd_thenCorrect() {
- Result result = runTest("dog$", "Man's best friend is a dog");
- assertTrue(result.isFound());
+ int matches = runTest("dog$", "Man's best friend is a dog");
+ assertTrue(matches > 0);
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
- Result result = runTest("dog$", "is a dog man's best friend?");
- assertFalse(result.isFound());
+ int matches = runTest("dog$", "is a dog man's best friend?");
+ assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
- Result result = runTest("\\bdog\\b", "a dog is friendly");
- assertTrue(result.isFound());
+ int matches = runTest("\\bdog\\b", "a dog is friendly");
+ assertTrue(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
- Result result = runTest("\\bdog\\b", "dog is man's best friend");
- assertTrue(result.isFound());
+ int matches = runTest("\\bdog\\b", "dog is man's best friend");
+ assertTrue(matches > 0);
}
@Test
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
- Result result = runTest("\\bdog\\b", "snoop dogg is a rapper");
- assertFalse(result.isFound());
+ int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
+ assertFalse(matches > 0);
}
@Test
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
- Result result = runTest("\\bdog\\B", "snoop dogg is a rapper");
- assertTrue(result.isFound());
+ int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
+ assertTrue(matches > 0);
}
@Test
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
- Result result = runTest("\u00E9", "\u0065\u0301");
- assertFalse(result.isFound());
+ int matches = runTest("\u00E9", "\u0065\u0301");
+ assertFalse(matches > 0);
}
@Test
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
- Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
- assertTrue(result.isFound());
+ int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
+ assertTrue(matches > 0);
}
@Test
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
- Result result = runTest("dog", "This is a Dog");
- assertFalse(result.isFound());
+ int matches = runTest("dog", "This is a Dog");
+ assertFalse(matches > 0);
}
@Test
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
- Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
- assertTrue(result.isFound());
+ int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
+ assertTrue(matches > 0);
}
@Test
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
- Result result = runTest("(?i)dog", "This is a Dog");
- assertTrue(result.isFound());
+ int matches = runTest("(?i)dog", "This is a Dog");
+ assertTrue(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
- Result result = runTest("dog$ #check for word dog at end of text", "This is a dog");
- assertFalse(result.isFound());
+ int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
+ assertFalse(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
- Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
- assertTrue(result.isFound());
+ int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
+ assertTrue(matches > 0);
}
@Test
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
- Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
- assertTrue(result.isFound());
+ int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
+ assertTrue(matches > 0);
}
@Test
@@ -401,38 +403,38 @@ public class RegexTest {
@Test
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
- Result result = runTest("(.*)", "text");
- assertTrue(result.isFound());
+ int matches = runTest("(.*)", "text");
+ assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
- Result result = runTest("(.*)", "text", Pattern.LITERAL);
- assertFalse(result.isFound());
+ int matches = runTest("(.*)", "text", Pattern.LITERAL);
+ assertFalse(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
- Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL);
- assertTrue(result.isFound());
+ int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
+ assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
- Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
- assertFalse(result.isFound());
+ int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
+ assertFalse(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
- Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
- assertTrue(result.isFound());
+ int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
+ assertTrue(matches > 0);
}
@Test
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
- Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
- assertTrue(result.isFound());
+ int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
+ assertTrue(matches > 0);
}
@Test
@@ -479,25 +481,22 @@ public class RegexTest {
}
- public synchronized static Result runTest(String regex, String text) {
+ public synchronized static int runTest(String regex, String text) {
pattern = Pattern.compile(regex);
matcher = pattern.matcher(text);
- Result result = new Result();
+ int matches = 0;
while (matcher.find())
- result.setCount(result.getCount() + 1);
- if (result.getCount() > 0)
- result.setFound(true);
- return result;
+ matches++;
+ return matches;
}
- public synchronized static Result runTest(String regex, String text, int flags) {
+ public synchronized static int runTest(String regex, String text, int flags) {
pattern = Pattern.compile(regex, flags);
matcher = pattern.matcher(text);
- Result result = new Result();
+ int matches = 0;
while (matcher.find())
- result.setCount(result.getCount() + 1);
- if (result.getCount() > 0)
- result.setFound(true);
- return result;
+ matches++;
+ return matches;
}
}
+
diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java
new file mode 100644
index 0000000000..23be2200d3
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java
@@ -0,0 +1,57 @@
+package org.baeldung.core.exceptions;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+
+import java.io.*;
+
+public class FileNotFoundExceptionTest {
+
+ private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class);
+
+ private String fileName = Double.toString(Math.random());
+
+ @Test(expected = BusinessException.class)
+ public void raiseBusinessSpecificException() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ throw new BusinessException("BusinessException: necessary file was not present.", ex);
+ }
+ }
+
+ @Test
+ public void createFile() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ try {
+ new File(fileName).createNewFile();
+ readFailingFile();
+ } catch (IOException ioe) {
+ throw new RuntimeException("BusinessException: even creation is not possible.", ioe);
+ }
+ }
+ }
+
+ @Test
+ public void logError() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ LOG.error("Optional file " + fileName + " was not found.", ex);
+ }
+ }
+
+ private void readFailingFile() throws IOException {
+ BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
+ rd.readLine();
+ // no need to close file
+ }
+
+ private class BusinessException extends RuntimeException {
+ BusinessException(String string, FileNotFoundException ex) {
+ super(string, ex);
+ }
+ }
+}
diff --git a/core-java/src/test/resources/test_md5.txt b/core-java/src/test/resources/test_md5.txt
new file mode 100644
index 0000000000..95d09f2b10
--- /dev/null
+++ b/core-java/src/test/resources/test_md5.txt
@@ -0,0 +1 @@
+hello world
\ No newline at end of file
diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar
deleted file mode 100644
index 5fd4d5023f..0000000000
Binary files a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar and /dev/null differ
diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties
deleted file mode 100644
index eb91947648..0000000000
--- a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties
+++ /dev/null
@@ -1 +0,0 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
\ No newline at end of file
diff --git a/couchbase-sdk-async/.springBeans b/couchbase-sdk-async/.springBeans
deleted file mode 100644
index ff32b84d3b..0000000000
--- a/couchbase-sdk-async/.springBeans
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
- 1
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar
deleted file mode 100644
index 5fd4d5023f..0000000000
Binary files a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar and /dev/null differ
diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties
deleted file mode 100644
index eb91947648..0000000000
--- a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties
+++ /dev/null
@@ -1 +0,0 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
\ No newline at end of file
diff --git a/couchbase-sdk-intro/mvnw b/couchbase-sdk-intro/mvnw
deleted file mode 100755
index a1ba1bf554..0000000000
--- a/couchbase-sdk-intro/mvnw
+++ /dev/null
@@ -1,233 +0,0 @@
-#!/bin/sh
-# ----------------------------------------------------------------------------
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-# ----------------------------------------------------------------------------
-
-# ----------------------------------------------------------------------------
-# Maven2 Start Up Batch script
-#
-# Required ENV vars:
-# ------------------
-# JAVA_HOME - location of a JDK home dir
-#
-# Optional ENV vars
-# -----------------
-# M2_HOME - location of maven2's installed home dir
-# MAVEN_OPTS - parameters passed to the Java VM when running Maven
-# e.g. to debug Maven itself, use
-# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-# ----------------------------------------------------------------------------
-
-if [ -z "$MAVEN_SKIP_RC" ] ; then
-
- if [ -f /etc/mavenrc ] ; then
- . /etc/mavenrc
- fi
-
- if [ -f "$HOME/.mavenrc" ] ; then
- . "$HOME/.mavenrc"
- fi
-
-fi
-
-# OS specific support. $var _must_ be set to either true or false.
-cygwin=false;
-darwin=false;
-mingw=false
-case "`uname`" in
- CYGWIN*) cygwin=true ;;
- MINGW*) mingw=true;;
- Darwin*) darwin=true
- #
- # Look for the Apple JDKs first to preserve the existing behaviour, and then look
- # for the new JDKs provided by Oracle.
- #
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
- #
- # Oracle JDKs
- #
- export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=`/usr/libexec/java_home`
- fi
- ;;
-esac
-
-if [ -z "$JAVA_HOME" ] ; then
- if [ -r /etc/gentoo-release ] ; then
- JAVA_HOME=`java-config --jre-home`
- fi
-fi
-
-if [ -z "$M2_HOME" ] ; then
- ## resolve links - $0 may be a link to maven's home
- PRG="$0"
-
- # need this for relative symlinks
- while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG="`dirname "$PRG"`/$link"
- fi
- done
-
- saveddir=`pwd`
-
- M2_HOME=`dirname "$PRG"`/..
-
- # make it fully qualified
- M2_HOME=`cd "$M2_HOME" && pwd`
-
- cd "$saveddir"
- # echo Using m2 at $M2_HOME
-fi
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched
-if $cygwin ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --unix "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
-fi
-
-# For Migwn, ensure paths are in UNIX format before anything is touched
-if $mingw ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME="`(cd "$M2_HOME"; pwd)`"
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
- # TODO classpath?
-fi
-
-if [ -z "$JAVA_HOME" ]; then
- javaExecutable="`which javac`"
- if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
- # readlink(1) is not available as standard on Solaris 10.
- readLink=`which readlink`
- if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
- if $darwin ; then
- javaHome="`dirname \"$javaExecutable\"`"
- javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
- else
- javaExecutable="`readlink -f \"$javaExecutable\"`"
- fi
- javaHome="`dirname \"$javaExecutable\"`"
- javaHome=`expr "$javaHome" : '\(.*\)/bin'`
- JAVA_HOME="$javaHome"
- export JAVA_HOME
- fi
- fi
-fi
-
-if [ -z "$JAVACMD" ] ; then
- if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- else
- JAVACMD="`which java`"
- fi
-fi
-
-if [ ! -x "$JAVACMD" ] ; then
- echo "Error: JAVA_HOME is not defined correctly." >&2
- echo " We cannot execute $JAVACMD" >&2
- exit 1
-fi
-
-if [ -z "$JAVA_HOME" ] ; then
- echo "Warning: JAVA_HOME environment variable is not set."
-fi
-
-CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --path --windows "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
-fi
-
-# traverses directory structure from process work directory to filesystem root
-# first directory with .mvn subdirectory is considered project base directory
-find_maven_basedir() {
- local basedir=$(pwd)
- local wdir=$(pwd)
- while [ "$wdir" != '/' ] ; do
- if [ -d "$wdir"/.mvn ] ; then
- basedir=$wdir
- break
- fi
- wdir=$(cd "$wdir/.."; pwd)
- done
- echo "${basedir}"
-}
-
-# concatenates all lines of a file
-concat_lines() {
- if [ -f "$1" ]; then
- echo "$(tr -s '\n' ' ' < "$1")"
- fi
-}
-
-export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
-MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
-
-# Provide a "standardized" way to retrieve the CLI args that will
-# work with both Windows and non-Windows executions.
-MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
-export MAVEN_CMD_LINE_ARGS
-
-WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-exec "$JAVACMD" \
- $MAVEN_OPTS \
- -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
- "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
- ${WRAPPER_LAUNCHER} "$@"
diff --git a/couchbase-sdk-intro/mvnw.cmd b/couchbase-sdk-intro/mvnw.cmd
deleted file mode 100644
index 2b934e89dd..0000000000
--- a/couchbase-sdk-intro/mvnw.cmd
+++ /dev/null
@@ -1,145 +0,0 @@
-@REM ----------------------------------------------------------------------------
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM ----------------------------------------------------------------------------
-
-@REM ----------------------------------------------------------------------------
-@REM Maven2 Start Up Batch script
-@REM
-@REM Required ENV vars:
-@REM JAVA_HOME - location of a JDK home dir
-@REM
-@REM Optional ENV vars
-@REM M2_HOME - location of maven2's installed home dir
-@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
-@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
-@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
-@REM e.g. to debug Maven itself, use
-@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-@REM ----------------------------------------------------------------------------
-
-@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
-@echo off
-@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
-@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
-
-@REM set %HOME% to equivalent of $HOME
-if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
-
-@REM Execute a user defined script before this one
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
-@REM check for pre script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
-if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
-:skipRcPre
-
-@setlocal
-
-set ERROR_CODE=0
-
-@REM To isolate internal variables from possible post scripts, we use another setlocal
-@setlocal
-
-@REM ==== START VALIDATION ====
-if not "%JAVA_HOME%" == "" goto OkJHome
-
-echo.
-echo Error: JAVA_HOME not found in your environment. >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-:OkJHome
-if exist "%JAVA_HOME%\bin\java.exe" goto init
-
-echo.
-echo Error: JAVA_HOME is set to an invalid directory. >&2
-echo JAVA_HOME = "%JAVA_HOME%" >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-@REM ==== END VALIDATION ====
-
-:init
-
-set MAVEN_CMD_LINE_ARGS=%*
-
-@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
-@REM Fallback to current working directory if not found.
-
-set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
-IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
-
-set EXEC_DIR=%CD%
-set WDIR=%EXEC_DIR%
-:findBaseDir
-IF EXIST "%WDIR%"\.mvn goto baseDirFound
-cd ..
-IF "%WDIR%"=="%CD%" goto baseDirNotFound
-set WDIR=%CD%
-goto findBaseDir
-
-:baseDirFound
-set MAVEN_PROJECTBASEDIR=%WDIR%
-cd "%EXEC_DIR%"
-goto endDetectBaseDir
-
-:baseDirNotFound
-set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
-cd "%EXEC_DIR%"
-
-:endDetectBaseDir
-
-IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
-
-@setlocal EnableExtensions EnableDelayedExpansion
-for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
-@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
-
-:endReadAdditionalConfig
-
-SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
-
-set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
-set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
-if ERRORLEVEL 1 goto error
-goto end
-
-:error
-set ERROR_CODE=1
-
-:end
-@endlocal & set ERROR_CODE=%ERROR_CODE%
-
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
-@REM check for post script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
-if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
-:skipRcPost
-
-@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
-if "%MAVEN_BATCH_PAUSE%" == "on" pause
-
-if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
-
-exit /B %ERROR_CODE%
\ No newline at end of file
diff --git a/couchbase-sdk-intro/pom.xml b/couchbase-sdk-intro/pom.xml
deleted file mode 100644
index 1c2ca5ee05..0000000000
--- a/couchbase-sdk-intro/pom.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
- 4.0.0
- com.baeldung
- couchbase-sdk-intro
- 0.1-SNAPSHOT
- jar
- couchbase-sdk-intro
- Intro to the Couchbase SDK
-
-
-
-
- com.couchbase.client
- java-client
- ${couchbase.client.version}
-
-
-
-
-
-
- maven-compiler-plugin
- 2.3.2
-
- 1.7
- 1.7
-
-
-
-
-
-
- 1.7
- UTF-8
- 2.2.6
-
-
-
diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar
deleted file mode 100644
index 5fd4d5023f..0000000000
Binary files a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar and /dev/null differ
diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties
deleted file mode 100644
index eb91947648..0000000000
--- a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties
+++ /dev/null
@@ -1 +0,0 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
\ No newline at end of file
diff --git a/couchbase-sdk-spring-service/mvnw b/couchbase-sdk-spring-service/mvnw
deleted file mode 100755
index a1ba1bf554..0000000000
--- a/couchbase-sdk-spring-service/mvnw
+++ /dev/null
@@ -1,233 +0,0 @@
-#!/bin/sh
-# ----------------------------------------------------------------------------
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-# ----------------------------------------------------------------------------
-
-# ----------------------------------------------------------------------------
-# Maven2 Start Up Batch script
-#
-# Required ENV vars:
-# ------------------
-# JAVA_HOME - location of a JDK home dir
-#
-# Optional ENV vars
-# -----------------
-# M2_HOME - location of maven2's installed home dir
-# MAVEN_OPTS - parameters passed to the Java VM when running Maven
-# e.g. to debug Maven itself, use
-# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-# ----------------------------------------------------------------------------
-
-if [ -z "$MAVEN_SKIP_RC" ] ; then
-
- if [ -f /etc/mavenrc ] ; then
- . /etc/mavenrc
- fi
-
- if [ -f "$HOME/.mavenrc" ] ; then
- . "$HOME/.mavenrc"
- fi
-
-fi
-
-# OS specific support. $var _must_ be set to either true or false.
-cygwin=false;
-darwin=false;
-mingw=false
-case "`uname`" in
- CYGWIN*) cygwin=true ;;
- MINGW*) mingw=true;;
- Darwin*) darwin=true
- #
- # Look for the Apple JDKs first to preserve the existing behaviour, and then look
- # for the new JDKs provided by Oracle.
- #
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
- #
- # Oracle JDKs
- #
- export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=`/usr/libexec/java_home`
- fi
- ;;
-esac
-
-if [ -z "$JAVA_HOME" ] ; then
- if [ -r /etc/gentoo-release ] ; then
- JAVA_HOME=`java-config --jre-home`
- fi
-fi
-
-if [ -z "$M2_HOME" ] ; then
- ## resolve links - $0 may be a link to maven's home
- PRG="$0"
-
- # need this for relative symlinks
- while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG="`dirname "$PRG"`/$link"
- fi
- done
-
- saveddir=`pwd`
-
- M2_HOME=`dirname "$PRG"`/..
-
- # make it fully qualified
- M2_HOME=`cd "$M2_HOME" && pwd`
-
- cd "$saveddir"
- # echo Using m2 at $M2_HOME
-fi
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched
-if $cygwin ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --unix "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
-fi
-
-# For Migwn, ensure paths are in UNIX format before anything is touched
-if $mingw ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME="`(cd "$M2_HOME"; pwd)`"
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
- # TODO classpath?
-fi
-
-if [ -z "$JAVA_HOME" ]; then
- javaExecutable="`which javac`"
- if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
- # readlink(1) is not available as standard on Solaris 10.
- readLink=`which readlink`
- if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
- if $darwin ; then
- javaHome="`dirname \"$javaExecutable\"`"
- javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
- else
- javaExecutable="`readlink -f \"$javaExecutable\"`"
- fi
- javaHome="`dirname \"$javaExecutable\"`"
- javaHome=`expr "$javaHome" : '\(.*\)/bin'`
- JAVA_HOME="$javaHome"
- export JAVA_HOME
- fi
- fi
-fi
-
-if [ -z "$JAVACMD" ] ; then
- if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- else
- JAVACMD="`which java`"
- fi
-fi
-
-if [ ! -x "$JAVACMD" ] ; then
- echo "Error: JAVA_HOME is not defined correctly." >&2
- echo " We cannot execute $JAVACMD" >&2
- exit 1
-fi
-
-if [ -z "$JAVA_HOME" ] ; then
- echo "Warning: JAVA_HOME environment variable is not set."
-fi
-
-CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --path --windows "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
-fi
-
-# traverses directory structure from process work directory to filesystem root
-# first directory with .mvn subdirectory is considered project base directory
-find_maven_basedir() {
- local basedir=$(pwd)
- local wdir=$(pwd)
- while [ "$wdir" != '/' ] ; do
- if [ -d "$wdir"/.mvn ] ; then
- basedir=$wdir
- break
- fi
- wdir=$(cd "$wdir/.."; pwd)
- done
- echo "${basedir}"
-}
-
-# concatenates all lines of a file
-concat_lines() {
- if [ -f "$1" ]; then
- echo "$(tr -s '\n' ' ' < "$1")"
- fi
-}
-
-export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
-MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
-
-# Provide a "standardized" way to retrieve the CLI args that will
-# work with both Windows and non-Windows executions.
-MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
-export MAVEN_CMD_LINE_ARGS
-
-WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-exec "$JAVACMD" \
- $MAVEN_OPTS \
- -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
- "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
- ${WRAPPER_LAUNCHER} "$@"
diff --git a/couchbase-sdk-spring-service/mvnw.cmd b/couchbase-sdk-spring-service/mvnw.cmd
deleted file mode 100644
index 2b934e89dd..0000000000
--- a/couchbase-sdk-spring-service/mvnw.cmd
+++ /dev/null
@@ -1,145 +0,0 @@
-@REM ----------------------------------------------------------------------------
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM ----------------------------------------------------------------------------
-
-@REM ----------------------------------------------------------------------------
-@REM Maven2 Start Up Batch script
-@REM
-@REM Required ENV vars:
-@REM JAVA_HOME - location of a JDK home dir
-@REM
-@REM Optional ENV vars
-@REM M2_HOME - location of maven2's installed home dir
-@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
-@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
-@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
-@REM e.g. to debug Maven itself, use
-@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-@REM ----------------------------------------------------------------------------
-
-@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
-@echo off
-@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
-@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
-
-@REM set %HOME% to equivalent of $HOME
-if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
-
-@REM Execute a user defined script before this one
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
-@REM check for pre script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
-if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
-:skipRcPre
-
-@setlocal
-
-set ERROR_CODE=0
-
-@REM To isolate internal variables from possible post scripts, we use another setlocal
-@setlocal
-
-@REM ==== START VALIDATION ====
-if not "%JAVA_HOME%" == "" goto OkJHome
-
-echo.
-echo Error: JAVA_HOME not found in your environment. >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-:OkJHome
-if exist "%JAVA_HOME%\bin\java.exe" goto init
-
-echo.
-echo Error: JAVA_HOME is set to an invalid directory. >&2
-echo JAVA_HOME = "%JAVA_HOME%" >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-@REM ==== END VALIDATION ====
-
-:init
-
-set MAVEN_CMD_LINE_ARGS=%*
-
-@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
-@REM Fallback to current working directory if not found.
-
-set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
-IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
-
-set EXEC_DIR=%CD%
-set WDIR=%EXEC_DIR%
-:findBaseDir
-IF EXIST "%WDIR%"\.mvn goto baseDirFound
-cd ..
-IF "%WDIR%"=="%CD%" goto baseDirNotFound
-set WDIR=%CD%
-goto findBaseDir
-
-:baseDirFound
-set MAVEN_PROJECTBASEDIR=%WDIR%
-cd "%EXEC_DIR%"
-goto endDetectBaseDir
-
-:baseDirNotFound
-set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
-cd "%EXEC_DIR%"
-
-:endDetectBaseDir
-
-IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
-
-@setlocal EnableExtensions EnableDelayedExpansion
-for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
-@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
-
-:endReadAdditionalConfig
-
-SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
-
-set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
-set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
-if ERRORLEVEL 1 goto error
-goto end
-
-:error
-set ERROR_CODE=1
-
-:end
-@endlocal & set ERROR_CODE=%ERROR_CODE%
-
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
-@REM check for post script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
-if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
-:skipRcPost
-
-@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
-if "%MAVEN_BATCH_PAUSE%" == "on" pause
-
-if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
-
-exit /B %ERROR_CODE%
\ No newline at end of file
diff --git a/couchbase-sdk-spring-service/pom.xml b/couchbase-sdk-spring-service/pom.xml
deleted file mode 100644
index d344f8c756..0000000000
--- a/couchbase-sdk-spring-service/pom.xml
+++ /dev/null
@@ -1,102 +0,0 @@
-
-
- 4.0.0
- com.baeldung
- couchbase-sdk-spring-service
- 0.1-SNAPSHOT
- jar
- couchbase-sdk-spring-service
- Intro to the Couchbase SDK
-
-
-
-
- com.couchbase.client
- java-client
- ${couchbase.client.version}
-
-
-
-
- org.springframework
- spring-context
- ${spring-framework.version}
-
-
- org.springframework
- spring-context-support
- ${spring-framework.version}
-
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
- compile
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
-
-
- org.springframework
- spring-test
- ${spring-framework.version}
- test
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
- test
-
-
-
-
-
-
- maven-compiler-plugin
- 2.3.2
-
- 1.7
- 1.7
-
-
-
-
-
-
- 1.7
- UTF-8
- 2.2.6
- 4.2.4.RELEASE
- 1.1.3
- 1.7.12
- 4.11
- 3.4
-
-
-
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java b/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java
deleted file mode 100644
index 8210c10b3a..0000000000
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.baeldung.couchbase.person;
-
-import org.springframework.stereotype.Service;
-
-import com.baeldung.couchbase.service.JsonDocumentConverter;
-import com.couchbase.client.java.document.JsonDocument;
-import com.couchbase.client.java.document.json.JsonObject;
-
-@Service
-public class FluentPersonDocumentConverter implements JsonDocumentConverter {
-
- @Override
- public JsonDocument toDocument(Person p) {
- JsonObject content = JsonObject.empty()
- .put("type", "Person")
- .put("name", p.getName())
- .put("homeTown", p.getHomeTown());
- return JsonDocument.create(p.getId(), content);
- }
-
- @Override
- public Person fromDocument(JsonDocument doc) {
- JsonObject content = doc.content();
- return Person.Builder.newInstance()
- .id(doc.id())
- .type("Person")
- .name(content.getString("name"))
- .homeTown(content.getString("homeTown"))
- .build();
- }
-}
diff --git a/couchbase-sdk-spring-service/src/main/resources/logback.xml b/couchbase-sdk-spring-service/src/main/resources/logback.xml
deleted file mode 100644
index efcc6fb4c7..0000000000
--- a/couchbase-sdk-spring-service/src/main/resources/logback.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
- web - %date [%thread] %-5level %logger{36} - %message%n
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java
deleted file mode 100644
index d593aac52d..0000000000
--- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.baeldung.couchbase;
-
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@ComponentScan(basePackages={"com.baeldung.couchbase"})
-public class IntegrationTestConfig {
-}
diff --git a/couchbase-sdk/README.md b/couchbase-sdk/README.md
new file mode 100644
index 0000000000..9cdcdea012
--- /dev/null
+++ b/couchbase-sdk/README.md
@@ -0,0 +1,50 @@
+## Couchbase SDK Tutorial Project
+
+### Relevant Articles:
+- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk)
+- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
+- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
+
+### Overview
+This Maven project contains the Java code for the Couchbase entities and Spring services
+as described in the tutorials, as well as a unit/integration test
+for each service implementation.
+
+### Working with the Code
+The project was developed and tested using Java 7 and 8 in the Eclipse-based
+Spring Source Toolkit (STS) and therefore should run fine in any
+recent version of Eclipse or another IDE of your choice
+that supports Java 7 or later.
+
+### Building the Project
+You can also build the project using Maven outside of any IDE:
+```
+mvn clean install
+```
+
+### Package Organization
+Java classes for the intro tutorial are in the
+org.baeldung.couchbase.intro package.
+
+Java classes for the Spring service tutorial are in the
+org.baeldung.couchbase.spring package hierarchy.
+
+Java classes for the Asynchronous Couchbase tutorial are in the
+org.baeldung.couchbase.async package hierarchy.
+
+
+### Running the tests
+The test classes for the Spring service tutorial are:
+- org.baeldung.couchbase.spring.service.ClusterServiceTest
+- org.baeldung.couchbase.spring.person.PersonCrudServiceTest
+
+The test classes for the Asynchronous Couchbase tutorial are in the
+org.baeldung.couchbase.async package hierarchy:
+- org.baeldung.couchbase.async.service.ClusterServiceTest
+- org.baeldung.couchbase.async.person.PersonCrudServiceTest
+
+The test classes may be run as JUnit tests from your IDE
+or using the Maven command line:
+```
+mvn test
+```
diff --git a/couchbase-sdk-async/mvnw b/couchbase-sdk/mvnw
similarity index 100%
rename from couchbase-sdk-async/mvnw
rename to couchbase-sdk/mvnw
diff --git a/couchbase-sdk-async/mvnw.cmd b/couchbase-sdk/mvnw.cmd
similarity index 100%
rename from couchbase-sdk-async/mvnw.cmd
rename to couchbase-sdk/mvnw.cmd
diff --git a/couchbase-sdk-async/pom.xml b/couchbase-sdk/pom.xml
similarity index 95%
rename from couchbase-sdk-async/pom.xml
rename to couchbase-sdk/pom.xml
index 9062ef8e15..4c277f4c85 100644
--- a/couchbase-sdk-async/pom.xml
+++ b/couchbase-sdk/pom.xml
@@ -3,11 +3,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0com.baeldung
- couchbase-sdk-async
+ couchbase-sdk0.1-SNAPSHOTjar
- couchbase-sdk-async
- Couchbase SDK Asynchronous Operations
+ couchbase-sdk
+ Couchbase SDK Tutorials
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java
similarity index 70%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java
index 4d2500197b..16e1876719 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async;
public interface CouchbaseEntity {
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java
similarity index 94%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java
index bf248c3999..32ed2ebbe4 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java
@@ -1,6 +1,6 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.async.person;
-import com.baeldung.couchbase.service.CouchbaseEntity;
+import com.baeldung.couchbase.async.CouchbaseEntity;
public class Person implements CouchbaseEntity {
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java
similarity index 77%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java
index d5302bd6db..b2ef985725 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.async.person;
import javax.annotation.PostConstruct;
@@ -6,8 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
-import com.baeldung.couchbase.service.AbstractCrudService;
-import com.baeldung.couchbase.service.BucketService;
+import com.baeldung.couchbase.async.service.AbstractCrudService;
+import com.baeldung.couchbase.async.service.BucketService;
@Service
public class PersonCrudService extends AbstractCrudService {
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java
similarity index 88%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java
index cfb20a2bfb..8646cf247a 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java
@@ -1,8 +1,8 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.async.person;
import org.springframework.stereotype.Service;
-import com.baeldung.couchbase.service.JsonDocumentConverter;
+import com.baeldung.couchbase.async.service.JsonDocumentConverter;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java
similarity index 93%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java
index 53af1c4041..926cd7f4e8 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.async.person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java
similarity index 93%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java
index 08acf5deed..cbc03cbcda 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import com.couchbase.client.java.Bucket;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java
similarity index 98%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java
index ce95074015..861e2404e5 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import java.util.ArrayList;
import java.util.List;
@@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.baeldung.couchbase.async.CouchbaseEntity;
import com.couchbase.client.core.BackpressureException;
import com.couchbase.client.core.time.Delay;
import com.couchbase.client.java.AsyncBucket;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java
similarity index 69%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java
index df9156d87d..28470be99f 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import com.couchbase.client.java.Bucket;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java
similarity index 74%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java
index 437ec00ff4..ee67405b12 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import com.couchbase.client.java.Bucket;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
similarity index 95%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
index c8ff56269d..7ce75d21f5 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java
similarity index 89%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java
index e0f0831abb..5bd0e52214 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import java.util.List;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java
similarity index 79%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java
index 87331d2a17..85e14a87ce 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import com.couchbase.client.java.document.JsonDocument;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
similarity index 93%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
index 2e40321272..459585d995 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import javax.annotation.PostConstruct;
diff --git a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java
similarity index 98%
rename from couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java
index 088f7af7b1..2cb9e1f4f7 100644
--- a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.examples;
+package com.baeldung.couchbase.intro;
import java.util.List;
import java.util.UUID;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java
similarity index 97%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java
index 48b7a38780..0348ba1e5f 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.spring.person;
public class Person {
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java
similarity index 88%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java
index 0203bf30bb..de035f1d2c 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.spring.person;
import java.util.List;
import java.util.UUID;
@@ -8,8 +8,9 @@ import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
-import com.baeldung.couchbase.service.CrudService;
-import com.baeldung.couchbase.service.TutorialBucketService;import com.couchbase.client.java.Bucket;
+import com.baeldung.couchbase.spring.service.CrudService;
+import com.baeldung.couchbase.spring.service.TutorialBucketService;
+import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.ReplicaMode;
import com.couchbase.client.java.document.JsonDocument;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java
similarity index 88%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java
index cfb20a2bfb..030c9fde27 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java
@@ -1,8 +1,8 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.spring.person;
import org.springframework.stereotype.Service;
-import com.baeldung.couchbase.service.JsonDocumentConverter;
+import com.baeldung.couchbase.spring.service.JsonDocumentConverter;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java
similarity index 93%
rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java
index 53af1c4041..5ffe7acf24 100644
--- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.spring.person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java
similarity index 69%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java
index c2562dd38e..97ff1e4fd5 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import com.couchbase.client.java.Bucket;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java
similarity index 90%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java
index 4713893899..a8543fbd91 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import java.util.List;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java
similarity index 98%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java
index 3c355d2a27..3499fa956e 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import java.util.ArrayList;
import java.util.List;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java
similarity index 82%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java
index 20ee851b39..f683b9f562 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
public interface CrudService {
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java
similarity index 79%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java
index 87331d2a17..cf4861fbeb 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import com.couchbase.client.java.document.JsonDocument;
diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java
similarity index 93%
rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java
rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java
index 903a568399..8a28deb1d6 100644
--- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java
+++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import javax.annotation.PostConstruct;
diff --git a/couchbase-sdk-async/src/main/resources/application.properties b/couchbase-sdk/src/main/resources/application.properties
similarity index 100%
rename from couchbase-sdk-async/src/main/resources/application.properties
rename to couchbase-sdk/src/main/resources/application.properties
diff --git a/couchbase-sdk-async/src/main/resources/logback.xml b/couchbase-sdk/src/main/resources/logback.xml
similarity index 100%
rename from couchbase-sdk-async/src/main/resources/logback.xml
rename to couchbase-sdk/src/main/resources/logback.xml
diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java
similarity index 74%
rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java
index d1cc807f7a..3079fc928a 100644
--- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase;
+package com.baeldung.couchbase.async;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
@@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { IntegrationTestConfig.class })
+@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public abstract class IntegrationTest {
+public abstract class AsyncIntegrationTest {
}
diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java
new file mode 100644
index 0000000000..6afdfe04bd
--- /dev/null
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java
@@ -0,0 +1,9 @@
+package com.baeldung.couchbase.async;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan(basePackages={"com.baeldung.couchbase.async"})
+public class AsyncIntegrationTestConfig {
+}
diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java
similarity index 93%
rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java
index 3da282492c..afc5bbd53b 100644
--- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.async.person;
import static org.junit.Assert.*;
@@ -13,12 +13,15 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-import com.baeldung.couchbase.IntegrationTest;
-import com.baeldung.couchbase.service.BucketService;
+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 PersonCrudServiceTest extends IntegrationTest {
+public class PersonCrudServiceTest extends AsyncIntegrationTest {
@Autowired
private PersonCrudService personService;
diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java
similarity index 73%
rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java
index 7795f41c93..8ecb51a4b9 100644
--- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.async.service;
import static org.junit.Assert.*;
@@ -10,14 +10,15 @@ import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
-import com.baeldung.couchbase.IntegrationTest;
-import com.baeldung.couchbase.IntegrationTestConfig;
+import com.baeldung.couchbase.async.AsyncIntegrationTest;
+import com.baeldung.couchbase.async.AsyncIntegrationTestConfig;
+import com.baeldung.couchbase.async.service.ClusterService;
import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { IntegrationTestConfig.class })
+@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public class ClusterServiceTest extends IntegrationTest {
+public class ClusterServiceTest extends AsyncIntegrationTest {
@Autowired
private ClusterService couchbaseService;
diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java
similarity index 93%
rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java
index d1cc807f7a..9c0b0a50c1 100644
--- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase;
+package com.baeldung.couchbase.spring;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java
similarity index 63%
rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java
index d593aac52d..ac71911b9b 100644
--- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java
@@ -1,9 +1,9 @@
-package com.baeldung.couchbase;
+package com.baeldung.couchbase.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
-@ComponentScan(basePackages={"com.baeldung.couchbase"})
+@ComponentScan(basePackages={"com.baeldung.couchbase.spring"})
public class IntegrationTestConfig {
}
diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java
similarity index 96%
rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java
index e19e90769c..601b261f6e 100644
--- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.person;
+package com.baeldung.couchbase.spring.person;
import static org.junit.Assert.*;
@@ -8,7 +8,7 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import com.baeldung.couchbase.IntegrationTest;
+import com.baeldung.couchbase.spring.IntegrationTest;
public class PersonCrudServiceTest extends IntegrationTest {
diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java
similarity index 87%
rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java
rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java
index 7795f41c93..d1968e1c04 100644
--- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java
+++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.couchbase.service;
+package com.baeldung.couchbase.spring.service;
import static org.junit.Assert.*;
@@ -10,8 +10,8 @@ import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
-import com.baeldung.couchbase.IntegrationTest;
-import com.baeldung.couchbase.IntegrationTestConfig;
+import com.baeldung.couchbase.spring.IntegrationTest;
+import com.baeldung.couchbase.spring.IntegrationTestConfig;
import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
diff --git a/flyway-migration/README.MD b/flyway-migration/README.MD
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/flyway-migration/README.MD
@@ -0,0 +1 @@
+
diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md
deleted file mode 100644
index 5b08f6cdec..0000000000
--- a/gson-jackson-performance/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## Performance of Gson and Jackson
-
-Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity.
diff --git a/gson-jackson-performance/pom.xml b/gson-jackson-performance/pom.xml
deleted file mode 100644
index 1ea43bd7fa..0000000000
--- a/gson-jackson-performance/pom.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-
- 4.0.0
-
- com.baeldung
- gson-jackson-performance
- 0.0.1-SNAPSHOT
- jar
-
- gson-jackson-performance
- http://maven.apache.org
-
-
- UTF-8
-
-
-
- gson-jackson-performance
-
-
- src/main/resources
- true
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- 1.8
- 1.8
-
-
-
-
-
-
-
-
-
-
- com.google.code.gson
- gson
- 2.5
-
-
-
- com.fasterxml.jackson.core
- jackson-databind
- 2.7.1-1
-
-
-
- junit
- junit
- 3.8.1
- test
-
-
-
- log4j
- log4j
- 1.2.17
-
-
-
-
-
-
-
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java
deleted file mode 100644
index b69d306edf..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.baeldung.data.complex;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.data.utility.Utility;
-import com.baeldung.pojo.complex.AddressDetails;
-import com.baeldung.pojo.complex.ContactDetails;
-import com.baeldung.pojo.complex.CustomerAddressDetails;
-import com.baeldung.pojo.complex.CustomerPortfolioComplex;
-
-/**
- *
- * This class is responsible for generating data for complex type object
- */
-
-public class ComplexDataGeneration {
-
- public static CustomerPortfolioComplex generateData() {
- List customerAddressDetailsList = new ArrayList();
- for (int i = 0; i < 600000; i++) {
- CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails();
- customerAddressDetails.setAge(20);
- customerAddressDetails.setFirstName(Utility.generateRandomName());
- customerAddressDetails.setLastName(Utility.generateRandomName());
-
- List addressDetailsList = new ArrayList();
- customerAddressDetails.setAddressDetails(addressDetailsList);
-
- for (int j = 0; j < 2; j++) {
- AddressDetails addressDetails = new AddressDetails();
- addressDetails.setZipcode(Utility.generateRandomZip());
- addressDetails.setAddress(Utility.generateRandomAddress());
-
- List contactDetailsList = new ArrayList();
- addressDetails.setContactDetails(contactDetailsList);
-
- for (int k = 0; k < 2; k++) {
- ContactDetails contactDetails = new ContactDetails();
- contactDetails.setLandline(Utility.generateRandomPhone());
- contactDetails.setMobile(Utility.generateRandomPhone());
- contactDetailsList.add(contactDetails);
- contactDetails = null;
- }
-
- addressDetailsList.add(addressDetails);
- addressDetails = null;
- contactDetailsList = null;
- }
- customerAddressDetailsList.add(customerAddressDetails);
- customerAddressDetails = null;
-
- if (i % 6000 == 0) {
- Runtime.getRuntime().gc();
- }
- }
-
- CustomerPortfolioComplex customerPortfolioComplex = new CustomerPortfolioComplex();
- customerPortfolioComplex.setCustomerAddressDetailsList(customerAddressDetailsList);
- customerAddressDetailsList = null;
- return customerPortfolioComplex;
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java
deleted file mode 100644
index b97893e8f1..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.baeldung.data.complex;
-
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-import com.baeldung.data.utility.Utility;
-import com.baeldung.pojo.complex.CustomerPortfolioComplex;
-
-import com.google.gson.Gson;
-
-/**
- *
- * This class is responsible for performing functions for Complex type
- * GSON like
- * Java to Json
- * Json to Map
- * Json to Java Object
- */
-
-public class ComplexDataGson {
-
- private static final Logger logger = Logger.getLogger(ComplexDataGson.class);
-
- static Gson gson = new Gson();
-
- static long generateJsonAvgTime = 0L;
-
- static long parseJsonToMapAvgTime = 0L;
-
- static long parseJsonToActualObjectAvgTime = 0L;
-
- public static void main(String[] args) {
- CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData();
- int j = 50;
- for (int i = 0; i < j; i++) {
- logger.info("-------Round " + (i + 1));
- String jsonStr = generateJson(customerPortfolioComplex);
- logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
- logger.info("--------------------------------------------------------------------------");
- parseJsonToMap(jsonStr);
- parseJsonToActualObject(jsonStr);
- jsonStr = null;
- }
-
- generateJsonAvgTime = generateJsonAvgTime / j;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
-
- logger.info("--------------------------------------------------------------------------");
- logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
- logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
- logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
- logger.info("--------------------------------------------------------------------------");
- }
-
- private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) {
- Runtime.getRuntime().gc();
- long startParsTime = System.nanoTime();
- String json = gson.toJson(customerPortfolioComplex);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
- logger.info("Json Generation Time(ms):: " + elapsedTime);
- return json;
- }
-
- private static void parseJsonToMap(String jsonStr) {
- long startParsTime = System.nanoTime();
- Map parsedMap = gson.fromJson(jsonStr , Map.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
- logger.info("Generating Map from json Time(ms):: " + elapsedTime);
- logger.info("--------------------------------------------------------------------------");
- parsedMap = null;
- Runtime.getRuntime().gc();
- }
-
- private static void parseJsonToActualObject(String jsonStr) {
- long startParsTime = System.nanoTime();
- CustomerPortfolioComplex customerPortfolioComplex = gson.fromJson(jsonStr , CustomerPortfolioComplex.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
- logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
- logger.info("--------------------------------------------------------------------------");
- customerPortfolioComplex = null;
- Runtime.getRuntime().gc();
-
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java
deleted file mode 100644
index 07a210fb37..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.baeldung.data.complex;
-
-import java.io.IOException;
-import java.util.Map;
-
-import com.baeldung.data.utility.Utility;
-import org.apache.log4j.Logger;
-import com.baeldung.pojo.complex.CustomerPortfolioComplex;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- *
- * This class is responsible for performing functions for Complex type
- * Jackson like
- * Java to Json
- * Json to Map
- * Json to Java Object
- */
-
-public class ComplexDataJackson {
-
- private static final Logger logger = Logger.getLogger(ComplexDataJackson.class);
-
- static ObjectMapper mapper = new ObjectMapper();
-
- static long generateJsonAvgTime = 0L;
-
- static long parseJsonToMapAvgTime = 0L;
-
- static long parseJsonToActualObjectAvgTime = 0L;
-
- public static void main(String[] args) throws IOException {
- CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData();
- int j = 50;
- for (int i = 0; i < j; i++) {
- logger.info("-------Round " + (i + 1));
- String jsonStr = generateJson(customerPortfolioComplex);
- logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
- logger.info("--------------------------------------------------------------------------");
- parseJsonToMap(jsonStr);
- parseJsonToActualObject(jsonStr);
- jsonStr = null;
- }
-
- generateJsonAvgTime = generateJsonAvgTime / j;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
-
- logger.info("--------------------------------------------------------------------------");
- logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
- logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
- logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
- logger.info("--------------------------------------------------------------------------");
- }
-
- private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex)
- throws JsonProcessingException {
- Runtime.getRuntime().gc();
- long startParsTime = System.nanoTime();
- String json = mapper.writeValueAsString(customerPortfolioComplex);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
- logger.info("Json Generation Time(ms):: " + elapsedTime);
- return json;
- }
-
- private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException {
- long startParsTime = System.nanoTime();
- Map parsedMap = mapper.readValue(jsonStr , Map.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
- logger.info("Generating Map from json Time(ms):: " + elapsedTime);
- parsedMap = null;
- Runtime.getRuntime().gc();
-
- }
-
- private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException ,
- IOException {
- long startParsTime = System.nanoTime();
- CustomerPortfolioComplex customerPortfolioComplex = mapper.readValue(jsonStr , CustomerPortfolioComplex.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
- logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
- customerPortfolioComplex = null;
- Runtime.getRuntime().gc();
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java
deleted file mode 100644
index 1e186adc72..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.baeldung.data.simple;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.data.utility.Utility;
-import com.baeldung.pojo.simple.Customer;
-import com.baeldung.pojo.simple.CustomerPortfolioSimple;
-
-/**
- *
- * This class is responsible for generating data for simple type object
- */
-
-public class SimpleDataGeneration {
-
- public static CustomerPortfolioSimple generateData() {
- List customerList = new ArrayList();
- for (int i = 0; i < 1; i++) {
- Customer customer = new Customer();
- customer.setAge(20);
- customer.setFirstName(Utility.generateRandomName());
- customer.setLastName(Utility.generateRandomName());
-
- customerList.add(customer);
- customer = null;
-
- }
-
- CustomerPortfolioSimple customerPortfolioSimple = new CustomerPortfolioSimple();
- customerPortfolioSimple.setCustomerLists(customerList);
- customerList = null;
- return customerPortfolioSimple;
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java
deleted file mode 100644
index b190313462..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.baeldung.data.simple;
-
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-import com.baeldung.data.utility.Utility;
-import com.baeldung.pojo.simple.CustomerPortfolioSimple;
-
-import com.google.gson.Gson;
-
-/**
- *
- * This class is responsible for performing functions for Simple type
- * GSON like
- * Java to Json
- * Json to Map
- * Json to Java Object
- */
-
-public class SimpleDataGson {
-
- private static final Logger logger = Logger.getLogger(SimpleDataGson.class);
-
- static Gson gson = new Gson();
-
- static long generateJsonAvgTime = 0L;
-
- static long parseJsonToMapAvgTime = 0L;
-
- static long parseJsonToActualObjectAvgTime = 0L;
-
- public static void main(String[] args) {
- CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData();
- String jsonStr = null;
- int j = 5;
- for (int i = 0; i < j; i++) {
- logger.info("-------Round " + (i + 1));
- jsonStr = generateJson(customerPortfolioSimple);
- logger.info("Size of Simple content Gson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
- logger.info("--------------------------------------------------------------------------");
- parseJsonToMap(jsonStr);
- parseJsonToActualObject(jsonStr);
- jsonStr = null;
- }
- generateJsonAvgTime = generateJsonAvgTime / j;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
-
- logger.info("--------------------------------------------------------------------------");
- logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
- logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
- logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
- logger.info("--------------------------------------------------------------------------");
- }
-
- private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) {
- Runtime.getRuntime().gc();
- long startParsTime = System.nanoTime();
- String json = gson.toJson(customerPortfolioSimple);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
- logger.info("Json Generation Time(ms):: " + elapsedTime);
- return json;
- }
-
- private static void parseJsonToMap(String jsonStr) {
- long startParsTime = System.nanoTime();
- Map parsedMap = gson.fromJson(jsonStr , Map.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
- logger.info("Generating Map from json Time(ms):: " + elapsedTime);
- logger.info("--------------------------------------------------------------------------");
- parsedMap = null;
- Runtime.getRuntime().gc();
-
- }
-
- private static void parseJsonToActualObject(String jsonStr) {
- long startParsTime = System.nanoTime();
- CustomerPortfolioSimple customerPortfolioSimple = gson.fromJson(jsonStr , CustomerPortfolioSimple.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
- logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
- logger.info("--------------------------------------------------------------------------");
- customerPortfolioSimple = null;
- Runtime.getRuntime().gc();
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java
deleted file mode 100644
index 9330333604..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.baeldung.data.simple;
-
-import java.io.IOException;
-import java.util.Map;
-
-import com.baeldung.data.utility.Utility;
-import org.apache.log4j.Logger;
-import com.baeldung.pojo.simple.CustomerPortfolioSimple;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- *
- * This class is responsible for performing functions for Simple type
- * Jackson like
- * Java to Json
- * Json to Map
- * Json to Java Object
- */
-
-public class SimpleDataJackson {
-
- private static final Logger logger = Logger.getLogger(SimpleDataJackson.class);
-
- static ObjectMapper mapper = new ObjectMapper();
-
- static long generateJsonAvgTime = 0L;
-
- static long parseJsonToMapAvgTime = 0L;
-
- static long parseJsonToActualObjectAvgTime = 0L;
-
- public static void main(String[] args) throws IOException {
- CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData();
- int j = 50;
- for (int i = 0; i < j; i++) {
- logger.info("-------Round " + (i + 1));
- String jsonStr = generateJson(customerPortfolioSimple);
- logger.info("Size of Simple content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
- logger.info("--------------------------------------------------------------------------");
-
- parseJsonToMap(jsonStr);
- parseJsonToActualObject(jsonStr);
- jsonStr = null;
- }
-
- generateJsonAvgTime = generateJsonAvgTime / j;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
-
- logger.info("--------------------------------------------------------------------------");
- logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
- logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
- logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
- logger.info("--------------------------------------------------------------------------");
- }
-
- private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) throws JsonProcessingException {
- Runtime.getRuntime().gc();
- long startParsTime = System.nanoTime();
- String json = mapper.writeValueAsString(customerPortfolioSimple);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
- logger.info("Json Generation Time(ms):: " + elapsedTime);
- return json;
- }
-
- private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException {
- long startParsTime = System.nanoTime();
- Map parsedMap = mapper.readValue(jsonStr , Map.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
- logger.info("Generating Map from json Time(ms):: " + elapsedTime);
- logger.info("--------------------------------------------------------------------------");
- parsedMap = null;
- Runtime.getRuntime().gc();
- }
-
- private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException ,
- IOException {
- long startParsTime = System.nanoTime();
- CustomerPortfolioSimple customerPortfolioSimple = mapper.readValue(jsonStr , CustomerPortfolioSimple.class);
- long endParsTime = System.nanoTime();
- long elapsedTime = endParsTime - startParsTime;
- parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
- logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
- customerPortfolioSimple = null;
- Runtime.getRuntime().gc();
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java
deleted file mode 100644
index 8b0c402e47..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package com.baeldung.data.utility;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Random;
-
-public class Utility {
-
- public static String generateRandomName() {
- char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray();
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < 8; i++) {
- char c = chars[random.nextInt(chars.length)];
- sb.append(c);
- }
- return sb.toString();
- }
-
- public static String generateRandomAddress() {
- char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray();
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < 30; i++) {
- char c = chars[random.nextInt(chars.length)];
- sb.append(c);
- }
- return sb.toString();
- }
-
- public static String generateRandomZip() {
- char[] chars = "1234567890".toCharArray();
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < 8; i++) {
- char c = chars[random.nextInt(chars.length)];
- sb.append(c);
- }
- return sb.toString();
- }
-
- public static String generateRandomPhone() {
- char[] chars = "1234567890".toCharArray();
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < 10; i++) {
- char c = chars[random.nextInt(chars.length)];
- sb.append(c);
- }
- return sb.toString();
- }
-
- public static String readFile(String fileName , Class clazz) throws IOException {
- String dir = clazz.getResource("/").getFile();
- dir = dir + "/" + fileName;
-
- BufferedReader br = new BufferedReader(new FileReader(dir));
- try {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
-
- while (line != null) {
- sb.append(line);
- sb.append(System.lineSeparator());
- line = br.readLine();
- }
- return sb.toString();
- } finally {
- br.close();
- }
- }
-
- public static String bytesIntoMB(long bytes) {
- long kilobyte = 1024;
- long megabyte = kilobyte * 1024;
-
- if ((bytes >= 0) && (bytes < kilobyte)) {
- return bytes + " B";
-
- } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
- return (bytes / kilobyte) + " KB";
-
- } else if ((bytes >= megabyte)) {
- return (bytes / megabyte) + " MB";
- }
-
- return null;
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java
deleted file mode 100644
index 79725a97bd..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.baeldung.pojo.complex;
-
-import java.util.List;
-
-public class AddressDetails {
-
- private String address;
-
- private String zipcode;
-
- private List contactDetails;
-
- public String getZipcode() {
- return zipcode;
- }
-
- public void setZipcode(String zipcode) {
- this.zipcode = zipcode;
- }
-
- public List getContactDetails() {
- return contactDetails;
- }
-
- public void setContactDetails(List contactDetails) {
- this.contactDetails = contactDetails;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
-
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java
deleted file mode 100644
index 164fe3f470..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.baeldung.pojo.complex;
-
-public class ContactDetails {
-
- private String mobile;
-
- private String landline;
-
- public String getMobile() {
- return mobile;
- }
-
- public void setMobile(String mobile) {
- this.mobile = mobile;
- }
-
- public String getLandline() {
- return landline;
- }
-
- public void setLandline(String landline) {
- this.landline = landline;
- }
-
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java
deleted file mode 100644
index 9bc5951716..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.baeldung.pojo.complex;
-
-import java.util.List;
-
-import com.baeldung.pojo.simple.Customer;
-
-public class CustomerAddressDetails extends Customer {
-
- private List addressDetails;
-
- public List getAddressDetails() {
- return addressDetails;
- }
-
- public void setAddressDetails(List addressDetails) {
- this.addressDetails = addressDetails;
- }
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java
deleted file mode 100644
index 13f9d240b8..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.pojo.complex;
-
-import java.util.List;
-
-public class CustomerPortfolioComplex {
-
- private List customerAddressDetailsList;
-
- public List getCustomerAddressDetailsList() {
- return customerAddressDetailsList;
- }
-
- public void setCustomerAddressDetailsList(List customerAddressDetailsList) {
- this.customerAddressDetailsList = customerAddressDetailsList;
- }
-
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java
deleted file mode 100644
index 3d5668f85a..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.baeldung.pojo.simple;
-
-
-public class Customer {
-
- private String firstName;
-
- private String lastName;
-
- private int age;
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
-}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java
deleted file mode 100644
index 7cb684813c..0000000000
--- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.baeldung.pojo.simple;
-
-import java.util.List;
-
-public class CustomerPortfolioSimple {
-
- private List customerLists;
-
- public List getCustomerLists() {
- return customerLists;
- }
-
- public void setCustomerLists(List customerLists) {
- this.customerLists = customerLists;
- }
-}
diff --git a/gson-jackson-performance/src/main/resources/log4j.properties b/gson-jackson-performance/src/main/resources/log4j.properties
deleted file mode 100644
index 371cbc9048..0000000000
--- a/gson-jackson-performance/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-# Root logger option
-log4j.rootLogger=DEBUG, file
-
-# Redirect log messages 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
-
-# Redirect log messages to a log file, support file rolling.
-log4j.appender.file=org.apache.log4j.RollingFileAppender
-log4j.appender.file.File=log4j-application.log
-log4j.appender.file.MaxFileSize=5MB
-log4j.appender.file.MaxBackupIndex=10
-log4j.appender.file.layout=org.apache.log4j.PatternLayout
-log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/gson/pom.xml b/gson/pom.xml
index 4f331f6fd9..d864c289c2 100644
--- a/gson/pom.xml
+++ b/gson/pom.xml
@@ -19,7 +19,7 @@
com.google.guavaguava
- 18.0
+ ${guava.version}commons-io
diff --git a/guava18/pom.xml b/guava18/pom.xml
index 6002b37d74..413e9c35b8 100644
--- a/guava18/pom.xml
+++ b/guava18/pom.xml
@@ -1,7 +1,6 @@
-
+4.0.0com.baeldung
@@ -14,12 +13,15 @@
guava18.0
+
junitjunit4.12
+ test
+
diff --git a/guava19/pom.xml b/guava19/pom.xml
index 13f3b471f1..61fbf38575 100644
--- a/guava19/pom.xml
+++ b/guava19/pom.xml
@@ -1,5 +1,6 @@
-
+4.0.0com.baeldung
@@ -10,20 +11,23 @@
com.google.guavaguava
- 19.0
+ ${guava.version}
+
junitjunit4.12
+ testorg.hamcresthamcrest-all1.3
+ test
-
+
@@ -42,4 +46,8 @@
+
+ 19.0
+
+
\ No newline at end of file
diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml
index aca069e300..6dd0c95026 100644
--- a/handling-spring-static-resources/pom.xml
+++ b/handling-spring-static-resources/pom.xml
@@ -115,6 +115,7 @@
jackson-databind${jackson.version}
+
org.hibernatehibernate-validator
@@ -221,8 +222,7 @@
1.9.2.RELEASE
-
- 2.7.2
+ 2.7.81.7.13
diff --git a/jackson/pom.xml b/jackson/pom.xml
index 17b0ac507e..e795ad11a2 100644
--- a/jackson/pom.xml
+++ b/jackson/pom.xml
@@ -174,7 +174,7 @@
5.1.38
- 2.7.2
+ 2.7.81.7.13
diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml
index 265a230eb4..a91c3b9b62 100644
--- a/java-cassandra/pom.xml
+++ b/java-cassandra/pom.xml
@@ -1,56 +1,36 @@
-
+4.0.0com.baeldungcassandra-java-client1.0.0-SNAPSHOT
-
- cassandra-java-client
-
-
- UTF-8
-
-
- 1.7.21
- 1.1.7
-
-
- 1.3
- 4.12
- 1.10.19
- 6.8
- 3.5.1
-
-
- 3.5.1
-
+
+ cassandra-java-client
+
+
- 3.1.0
-
-
-
-
-
+ com.datastax.cassandracassandra-driver-core${cassandra-driver-core.version}true
-
+
org.cassandraunitcassandra-unit3.0.0.1
-
+
com.google.guavaguava
- 19.0
+ ${guava.version}
-
-
+
+
org.slf4j
@@ -74,16 +54,16 @@
log4j-over-slf4j${org.slf4j.version}
-
+
- junit
- junit
- ${junit.version}
- test
+ junit
+ junit
+ ${junit.version}
+ test
-
-
-
+
+
+ java-cassandra
@@ -97,6 +77,29 @@
-
+
+
+ UTF-8
+
+ 19.0
+
+
+ 1.7.21
+ 1.1.7
+
+
+ 1.3
+ 4.12
+ 1.10.19
+ 6.8
+ 3.5.1
+
+
+ 3.5.1
+
+
+ 3.1.0
+
+
diff --git a/log4j/pom.xml b/log4j/pom.xml
index 586769aa71..ab384d4dd1 100644
--- a/log4j/pom.xml
+++ b/log4j/pom.xml
@@ -15,24 +15,17 @@
log4j1.2.17
-
org.apache.logging.log4jlog4j-api
- 2.6
+ 2.7org.apache.logging.log4jlog4j-core
- 2.6
+ 2.7
@@ -40,13 +33,6 @@
disruptor3.3.4
-
@@ -54,14 +40,6 @@
logback-classic1.1.7
-
-
diff --git a/okhttp/pom.xml b/okhttp/pom.xml
new file mode 100644
index 0000000000..ba5bcf9725
--- /dev/null
+++ b/okhttp/pom.xml
@@ -0,0 +1,44 @@
+
+ 4.0.0
+ org.baeldung.okhttp
+ okhttp
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ com.squareup.okhttp3
+ okhttp
+ ${com.squareup.okhttp3.version}
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
+
+
+
+
+
+
+ 3.4.1
+
+
+ 1.3
+ 4.12
+
+
+
+
diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java
new file mode 100644
index 0000000000..2a33a1febd
--- /dev/null
+++ b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java
@@ -0,0 +1,26 @@
+package org.baeldung.okhttp;
+
+import java.io.IOException;
+
+import okhttp3.Interceptor;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class DefaultContentTypeInterceptor implements Interceptor {
+
+ private final String contentType;
+
+ public DefaultContentTypeInterceptor(String contentType) {
+ this.contentType = contentType;
+ }
+
+ public Response intercept(Interceptor.Chain chain) throws IOException {
+
+ Request originalRequest = chain.request();
+ Request requestWithUserAgent = originalRequest.newBuilder()
+ .header("Content-Type", contentType)
+ .build();
+
+ return chain.proceed(requestWithUserAgent);
+ }
+}
diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java
new file mode 100644
index 0000000000..6a98f8d20a
--- /dev/null
+++ b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java
@@ -0,0 +1,68 @@
+package org.baeldung.okhttp;
+
+import okhttp3.MediaType;
+import okhttp3.RequestBody;
+import okio.*;
+
+import java.io.IOException;
+
+public class ProgressRequestWrapper extends RequestBody {
+
+ protected RequestBody delegate;
+ protected ProgressListener listener;
+
+ protected CountingSink countingSink;
+
+ public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) {
+ this.delegate = delegate;
+ this.listener = listener;
+ }
+
+ @Override
+ public MediaType contentType() {
+ return delegate.contentType();
+ }
+
+ @Override
+ public long contentLength() throws IOException {
+ return delegate.contentLength();
+ }
+
+ @Override
+ public void writeTo(BufferedSink sink) throws IOException {
+
+ BufferedSink bufferedSink;
+
+ countingSink = new CountingSink(sink);
+ bufferedSink = Okio.buffer(countingSink);
+
+ delegate.writeTo(bufferedSink);
+
+ bufferedSink.flush();
+ }
+
+ protected final class CountingSink extends ForwardingSink {
+
+ private long bytesWritten = 0;
+
+ public CountingSink(Sink delegate) {
+ super(delegate);
+ }
+
+ @Override
+ public void write(Buffer source, long byteCount) throws IOException {
+
+ super.write(source, byteCount);
+
+ bytesWritten += byteCount;
+ listener.onRequestProgress(bytesWritten, contentLength());
+ }
+
+ }
+
+ public interface ProgressListener {
+ void onRequestProgress(long bytesWritten, long contentLength);
+
+ }
+}
+
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java
new file mode 100644
index 0000000000..32457fc11b
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java
@@ -0,0 +1,81 @@
+package org.baeldung.okhttp;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.baeldung.okhttp.ProgressRequestWrapper;
+import org.junit.Test;
+
+import okhttp3.Call;
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+
+public class OkHttpFileUploadingTest {
+
+ private static final String BASE_URL = "http://localhost:8080/spring-rest";
+
+ @Test
+ public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ RequestBody requestBody = new MultipartBody.Builder()
+ .setType(MultipartBody.FORM)
+ .addFormDataPart("file", "file.txt",
+ RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
+ .build();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/users/upload")
+ .post(requestBody)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ RequestBody requestBody = new MultipartBody.Builder()
+ .setType(MultipartBody.FORM)
+ .addFormDataPart("file", "file.txt",
+ RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
+ .build();
+
+
+ ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() {
+
+ public void onRequestProgress(long bytesWritten, long contentLength) {
+
+ float percentage = 100f * bytesWritten / contentLength;
+ assertFalse(Float.compare(percentage, 100) > 0);
+ }
+ };
+
+ ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener);
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/users/upload")
+ .post(countingBody)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+
+ }
+}
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java
new file mode 100644
index 0000000000..e8edff92df
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java
@@ -0,0 +1,78 @@
+package org.baeldung.okhttp;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.HttpUrl;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class OkHttpGetTest {
+
+ private static final String BASE_URL = "http://localhost:8080/spring-rest";
+
+ @Test
+ public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/date")
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
+ urlBuilder.addQueryParameter("id", "1");
+
+ String url = urlBuilder.build().toString();
+
+ Request request = new Request.Builder()
+ .url(url)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() {
+
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/date")
+ .build();
+
+ Call call = client.newCall(request);
+
+ call.enqueue(new Callback() {
+
+ public void onResponse(Call call, Response response) throws IOException {
+ assertThat(response.code(), equalTo(200));
+ }
+
+ public void onFailure(Call call, IOException e) {
+
+ }
+ });
+ }
+}
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java
new file mode 100644
index 0000000000..5b2e89eca8
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java
@@ -0,0 +1,48 @@
+package org.baeldung.okhttp;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+import okhttp3.Call;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class OkHttpHeaderTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ @Test
+ public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url(SAMPLE_URL)
+ .addHeader("Content-Type", "application/json")
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+ response.close();
+ }
+
+ @Test
+ public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient.Builder()
+ .addInterceptor(new DefaultContentTypeInterceptor("application/json"))
+ .build();
+
+ Request request = new Request.Builder()
+ .url(SAMPLE_URL)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+ response.close();
+ }
+
+
+}
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java
new file mode 100644
index 0000000000..829bafe8ef
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java
@@ -0,0 +1,113 @@
+package org.baeldung.okhttp;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Test;
+
+import okhttp3.Cache;
+import okhttp3.Call;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class OkHttpMiscTest {
+
+ private static final String BASE_URL = "http://localhost:8080/spring-rest";
+
+ //@Test
+ public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException {
+
+ OkHttpClient client = new OkHttpClient.Builder()
+ //.connectTimeout(10, TimeUnit.SECONDS)
+ //.writeTimeout(10, TimeUnit.SECONDS)
+ .readTimeout(1, TimeUnit.SECONDS)
+ .build();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+ response.close();
+ }
+
+ //@Test
+ public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException {
+
+ ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
+
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
+ .build();
+
+ final int seconds = 1;
+ //final int seconds = 3;
+
+ final long startNanos = System.nanoTime();
+ final Call call = client.newCall(request);
+
+ // Schedule a job to cancel the call in 1 second.
+ executor.schedule(new Runnable() {
+ public void run() {
+
+ System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ call.cancel();
+ System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ }
+ }, seconds, TimeUnit.SECONDS);
+
+ try {
+
+ System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ Response response = call.execute();
+ System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response);
+
+ } catch (IOException e) {
+
+ System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e);
+ }
+ }
+
+ @Test
+ public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException {
+
+ int cacheSize = 10 * 1024 * 1024; // 10 MiB
+ File cacheDirectory = new File("src/test/resources/cache");
+ Cache cache = new Cache(cacheDirectory, cacheSize);
+
+ OkHttpClient client = new OkHttpClient.Builder()
+ .cache(cache)
+ .build();
+
+ Request request = new Request.Builder()
+ .url("http://publicobject.com/helloworld.txt")
+ //.cacheControl(CacheControl.FORCE_NETWORK)
+ //.cacheControl(CacheControl.FORCE_CACHE)
+ .build();
+
+ Response response1 = client.newCall(request).execute();
+
+ String responseBody1 = response1.body().string();
+
+ System.out.println("Response 1 response: " + response1);
+ System.out.println("Response 1 cache response: " + response1.cacheResponse());
+ System.out.println("Response 1 network response: " + response1.networkResponse());
+ System.out.println("Response 1 responseBody: " + responseBody1);
+
+ Response response2 = client.newCall(request).execute();
+
+ String responseBody2 = response2.body().string();
+
+ System.out.println("Response 2 response: " + response2);
+ System.out.println("Response 2 cache response: " + response2.cacheResponse());
+ System.out.println("Response 2 network response: " + response2.networkResponse());
+ System.out.println("Response 2 responseBody: " + responseBody2);
+ }
+}
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java
new file mode 100644
index 0000000000..1ba2d517c5
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java
@@ -0,0 +1,109 @@
+package org.baeldung.okhttp;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.junit.Test;
+
+import okhttp3.Call;
+import okhttp3.Credentials;
+import okhttp3.FormBody;
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+
+public class OkHttpPostingTest {
+
+ private static final String BASE_URL = "http://localhost:8080/spring-rest";
+ private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
+
+ @Test
+ public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ RequestBody formBody = new FormBody.Builder()
+ .add("username", "test")
+ .add("password", "test")
+ .build();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/users")
+ .post(formBody)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException {
+
+ String postBody = "test post";
+
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url(URL_SECURED_BY_BASIC_AUTHENTICATION)
+ .addHeader("Authorization", Credentials.basic("test", "test"))
+ .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody))
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ String json = "{\"id\":1,\"name\":\"John\"}";
+
+ RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/users/detail")
+ .post(body)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+
+ @Test
+ public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException {
+
+ OkHttpClient client = new OkHttpClient();
+
+ RequestBody requestBody = new MultipartBody.Builder()
+ .setType(MultipartBody.FORM)
+ .addFormDataPart("username", "test")
+ .addFormDataPart("password", "test")
+ .addFormDataPart("file", "file.txt",
+ RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
+ .build();
+
+ Request request = new Request.Builder()
+ .url(BASE_URL + "/users/multipart")
+ .post(requestBody)
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(200));
+ }
+}
diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java
new file mode 100644
index 0000000000..1582a5ff7f
--- /dev/null
+++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java
@@ -0,0 +1,33 @@
+package org.baeldung.okhttp;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+import okhttp3.Call;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class OkHttpRedirectTest {
+
+ @Test
+ public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException {
+
+ OkHttpClient client = new OkHttpClient().newBuilder()
+ .followRedirects(false)
+ .build();
+
+ Request request = new Request.Builder()
+ .url("http://t.co/I5YYd9tddw")
+ .build();
+
+ Call call = client.newCall(request);
+ Response response = call.execute();
+
+ assertThat(response.code(), equalTo(301));
+ }
+}
diff --git a/okhttp/src/test/resources/test.txt b/okhttp/src/test/resources/test.txt
new file mode 100644
index 0000000000..95d09f2b10
--- /dev/null
+++ b/okhttp/src/test/resources/test.txt
@@ -0,0 +1 @@
+hello world
\ No newline at end of file
diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/student-api/app/controllers/AsyncController.java
index 33cd112837..92c84bb755 100644
--- a/play-framework/student-api/app/controllers/AsyncController.java
+++ b/play-framework/student-api/app/controllers/AsyncController.java
@@ -1,13 +1,17 @@
package controllers;
import akka.actor.ActorSystem;
+
import javax.inject.*;
+
import play.*;
import play.mvc.*;
+
import java.util.concurrent.Executor;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
+
import scala.concurrent.duration.Duration;
import scala.concurrent.ExecutionContextExecutor;
@@ -17,11 +21,11 @@ import scala.concurrent.ExecutionContextExecutor;
* asynchronously delay sending a response for 1 second.
*
* @param actorSystem We need the {@link ActorSystem}'s
- * {@link Scheduler} to run code after a delay.
- * @param exec We need a Java {@link Executor} to apply the result
- * of the {@link CompletableFuture} and a Scala
- * {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
- * An {@link ExecutionContextExecutor} implements both interfaces.
+ * {@link Scheduler} to run code after a delay.
+ * @param exec We need a Java {@link Executor} to apply the result
+ * of the {@link CompletableFuture} and a Scala
+ * {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
+ * An {@link ExecutionContextExecutor} implements both interfaces.
*/
@Singleton
public class AsyncController extends Controller {
@@ -31,14 +35,14 @@ public class AsyncController extends Controller {
@Inject
public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) {
- this.actorSystem = actorSystem;
- this.exec = exec;
+ this.actorSystem = actorSystem;
+ this.exec = exec;
}
/**
* An action that returns a plain text message after a delay
* of 1 second.
- *
+ *
* The configuration in the routes file means that this method
* will be called when the application receives a GET request with
* a path of /message.
@@ -50,9 +54,9 @@ public class AsyncController extends Controller {
private CompletionStage getFutureMessage(long time, TimeUnit timeUnit) {
CompletableFuture future = new CompletableFuture<>();
actorSystem.scheduler().scheduleOnce(
- Duration.create(time, timeUnit),
- () -> future.complete("Hi!"),
- exec
+ Duration.create(time, timeUnit),
+ () -> future.complete("Hi!"),
+ exec
);
return future;
}
diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java
index 0adedfa432..8b759b9598 100644
--- a/play-framework/student-api/app/controllers/StudentController.java
+++ b/play-framework/student-api/app/controllers/StudentController.java
@@ -1,56 +1,63 @@
package controllers;
-import models.*;
-import util.*;
-import play.mvc.*;
-import play.libs.Json;
-import play.libs.Json.*;
-import com.fasterxml.jackson.databind.JsonNode;
+
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import java.util.List;
+import models.Student;
+import models.StudentStore;
+import play.libs.Json;
+import play.mvc.Controller;
+import play.mvc.Result;
+import util.Util;
+
+import java.util.Set;
public class StudentController extends Controller {
public Result create() {
- JsonNode json = request().body().asJson();
- if(json == null)
- return badRequest(Util.createResponse("Expecting Json data",false));
- Student student=StudentStore.getInstance().addStudent((Student)Json.fromJson(json,Student.class));
- JsonNode jsonObject=Json.toJson(student);
- return created(Util.createResponse(jsonObject,true));
- }
- public Result update() {
JsonNode json = request().body().asJson();
- if(json == null)
- return badRequest(Util.createResponse("Expecting Json data",false));
- Student student=StudentStore.getInstance().updateStudent((Student)Json.fromJson(json,Student.class));
- if(student==null){
- return notFound(Util.createResponse("Student not found",false));
- }
-
- JsonNode jsonObject=Json.toJson(student);
- return ok(Util.createResponse(jsonObject,true));
+ if (json == null) {
+ return badRequest(Util.createResponse("Expecting Json data", false));
+ }
+ Student student = StudentStore.getInstance().addStudent(Json.fromJson(json, Student.class));
+ JsonNode jsonObject = Json.toJson(student);
+ return created(Util.createResponse(jsonObject, true));
}
- public Result retrieve(int id) {
- Student student=StudentStore.getInstance().getStudent(id);
- if(student==null){
- return notFound(Util.createResponse("Student with id:"+id+" not found",false));
- }
- JsonNode jsonObjects=Json.toJson(student);
- return ok(Util.createResponse(jsonObjects,true));
- }
- public Result listStudents() {
- List result=StudentStore.getInstance().getAllStudents();
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonData=mapper.convertValue(result, JsonNode.class);
- return ok(Util.createResponse(jsonData,true));
+ public Result update() {
+ JsonNode json = request().body().asJson();
+ if (json == null) {
+ return badRequest(Util.createResponse("Expecting Json data", false));
+ }
+ Student student = StudentStore.getInstance().updateStudent(Json.fromJson(json, Student.class));
+ if (student == null) {
+ return notFound(Util.createResponse("Student not found", false));
+ }
+
+ JsonNode jsonObject = Json.toJson(student);
+ return ok(Util.createResponse(jsonObject, true));
+ }
+
+ public Result retrieve(int id) {
+ if (StudentStore.getInstance().getStudent(id) == null) {
+ return notFound(Util.createResponse("Student with id:" + id + " not found", false));
+ }
+ JsonNode jsonObjects = Json.toJson(StudentStore.getInstance().getStudent(id));
+ return ok(Util.createResponse(jsonObjects, true));
+ }
+
+ public Result listStudents() {
+ Set result = StudentStore.getInstance().getAllStudents();
+ ObjectMapper mapper = new ObjectMapper();
+
+ JsonNode jsonData = mapper.convertValue(result, JsonNode.class);
+ return ok(Util.createResponse(jsonData, true));
}
- public Result delete(int id) {
- boolean status=StudentStore.getInstance().deleteStudent(id);
- if(!status){
- return notFound(Util.createResponse("Student with id:"+id+" not found",false));
- }
- return ok(Util.createResponse("Student with id:"+id+" deleted",true));
+
+ public Result delete(int id) {
+ if (!StudentStore.getInstance().deleteStudent(id)) {
+ return notFound(Util.createResponse("Student with id:" + id + " not found", false));
+ }
+ return ok(Util.createResponse("Student with id:" + id + " deleted", true));
}
}
diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/student-api/app/models/StudentStore.java
index 3290e141cd..add6a5dbd6 100644
--- a/play-framework/student-api/app/models/StudentStore.java
+++ b/play-framework/student-api/app/models/StudentStore.java
@@ -1,40 +1,39 @@
package models;
-import java.util.ArrayList;
+
import java.util.HashMap;
-import java.util.List;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
public class StudentStore {
private static StudentStore instance;
private Map students = new HashMap<>();
public static StudentStore getInstance() {
- if (instance == null)
+ if (instance == null) {
instance = new StudentStore();
+ }
return instance;
}
public Student addStudent(Student student) {
- int id = students.size() + 1;
+ int id = students.size();
student.setId(id);
students.put(id, student);
return student;
}
public Student getStudent(int id) {
- if (students.containsKey(id))
- return students.get(id);
- return null;
+ return students.get(id);
}
- public List getAllStudents() {
- return new ArrayList(students.values());
+ public Set getAllStudents() {
+ return new HashSet<>(students.values());
}
public Student updateStudent(Student student) {
- int id=student.getId();
+ int id = student.getId();
if (students.containsKey(id)) {
- student.setId(id);
students.put(id, student);
return student;
}
@@ -42,11 +41,6 @@ public class StudentStore {
}
public boolean deleteStudent(int id) {
-
- if (!students.containsKey(id))
- return false;
- students.remove(id);
- return true;
-
+ return students.remove(id) != null;
}
}
\ No newline at end of file
diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/student-api/app/util/Util.java
index 3718b50677..a853a4cb43 100644
--- a/play-framework/student-api/app/util/Util.java
+++ b/play-framework/student-api/app/util/Util.java
@@ -1,17 +1,17 @@
package util;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import play.libs.Json;
-import play.libs.Json.*;
-import com.fasterxml.jackson.databind.JsonNode;
-public class Util{
- public static ObjectNode createResponse(Object response,boolean ok){
- ObjectNode result = Json.newObject();
- result.put("isSuccessfull", ok);
- if(response instanceof String)
- result.put("body",(String)response);
- else result.put("body",(JsonNode)response);
+public class Util {
+ public static ObjectNode createResponse(Object response, boolean ok) {
+ ObjectNode result = Json.newObject();
+ result.put("isSuccessfull", ok);
+ if (response instanceof String)
+ result.put("body", (String) response);
+ else result.put("body", (JsonNode) response);
- return result;
- }
+ return result;
+ }
}
\ No newline at end of file
diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java
index 3d7c4875aa..1133978e9a 100644
--- a/play-framework/student-api/test/ApplicationTest.java
+++ b/play-framework/student-api/test/ApplicationTest.java
@@ -1,45 +1,172 @@
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
-import play.mvc.*;
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Arrays;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Test;
+import model.Student;
import play.test.*;
-import play.data.DynamicForm;
-import play.data.validation.ValidationError;
-import play.data.validation.Constraints.RequiredValidator;
-import play.i18n.Lang;
-import play.libs.F;
-import play.libs.F.*;
-import play.twirl.api.Content;
-
import static play.test.Helpers.*;
-import static org.junit.Assert.*;
-
-
-/**
- *
- * Simple (JUnit) tests that can call all parts of a play app.
- * If you are interested in mocking a whole application, see the wiki for more details.
- *
- */
-public class ApplicationTest {
-
- @Test
- public void simpleCheck() {
- int a = 1 + 1;
- assertEquals(2, a);
- }
-
- @Test
- public void renderTemplate() {
- Content html = views.html.index.render("Your new application is ready.");
- assertEquals("text/html", html.contentType());
- assertTrue(html.body().contains("Your new application is ready."));
- }
+public class ApplicationTest{
+ private static final String BASE_URL = "http://localhost:9000";
+ @Test
+public void testInServer() throws Exception {
+ TestServer server = testServer(3333);
+ running(server, () -> {
+ try {
+ WSClient ws = play.libs.ws.WS.newClient(3333);
+ CompletionStage completionStage = ws.url("/").get();
+ WSResponse response = completionStage.toCompletableFuture().get();
+ ws.close();
+ assertEquals(OK, response.getStatus());
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ }
+ });
+}
+ @Test
+ public void whenCreatesRecord_thenCorrect() {
+ Student student = new Student("jody", "west", 50);
+ JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student)));
+ assertTrue(obj.getBoolean("isSuccessfull"));
+ JSONObject body = obj.getJSONObject("body");
+ assertEquals(student.getAge(), body.getInt("age"));
+ assertEquals(student.getFirstName(), body.getString("firstName"));
+ assertEquals(student.getLastName(), body.getString("lastName"));
+ }
+
+ @Test
+ public void whenDeletesCreatedRecord_thenCorrect() {
+ Student student = new Student("Usain", "Bolt", 25);
+ JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
+ int id = ob1.getInt("id");
+ JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
+ assertTrue(obj1.getBoolean("isSuccessfull"));
+ makeRequest(BASE_URL + "/" + id, "DELETE", null);
+ JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
+ assertFalse(obj2.getBoolean("isSuccessfull"));
+ }
+
+ @Test
+ public void whenUpdatesCreatedRecord_thenCorrect() {
+ Student student = new Student("john", "doe", 50);
+ JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
+ assertEquals(student.getAge(), body1.getInt("age"));
+ int newAge = 60;
+ body1.put("age", newAge);
+ JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body");
+ assertFalse(student.getAge() == body2.getInt("age"));
+ assertTrue(newAge == body2.getInt("age"));
+ }
+
+ @Test
+ public void whenGetsAllRecords_thenCorrect() {
+ Student student1 = new Student("jane", "daisy", 50);
+ Student student2 = new Student("john", "daniel", 60);
+ Student student3 = new Student("don", "mason", 55);
+ Student student4 = new Student("scarlet", "ohara", 90);
+
+ makeRequest(BASE_URL, "POST", new JSONObject(student1));
+ makeRequest(BASE_URL, "POST", new JSONObject(student2));
+ makeRequest(BASE_URL, "POST", new JSONObject(student3));
+ makeRequest(BASE_URL, "POST", new JSONObject(student4));
+
+ JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null));
+ assertTrue(objects.getBoolean("isSuccessfull"));
+ JSONArray array = objects.getJSONArray("body");
+ assertTrue(array.length() >= 4);
+ }
+
+ public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) {
+
+ URL url = null;
+ try {
+ url = new URL(myUrl);
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ HttpURLConnection conn = null;
+ try {
+
+ conn = (HttpURLConnection) url.openConnection();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ conn.setDoInput(true);
+
+ conn.setReadTimeout(10000);
+
+ conn.setRequestProperty("Content-Type", "application/json");
+ DataOutputStream dos = null;
+ int respCode = 0;
+ String inputString = null;
+ try {
+ conn.setRequestMethod(httpMethod);
+
+ if (Arrays.asList("POST", "PUT").contains(httpMethod)) {
+ String params = parameters.toString();
+
+ conn.setDoOutput(true);
+
+ dos = new DataOutputStream(conn.getOutputStream());
+ dos.writeBytes(params);
+ dos.flush();
+ dos.close();
+ }
+ respCode = conn.getResponseCode();
+ if (respCode != 200 && respCode != 201) {
+ String error = inputStreamToString(conn.getErrorStream());
+ return error;
+ }
+ inputString = inputStreamToString(conn.getInputStream());
+
+ } catch (IOException e) {
+
+ e.printStackTrace();
+ }
+ return inputString;
+ }
+
+ public static String inputStreamToString(InputStream is) {
+ BufferedReader br = null;
+ StringBuilder sb = new StringBuilder();
+
+ String line;
+ try {
+
+ br = new BufferedReader(new InputStreamReader(is));
+ while ((line = br.readLine()) != null) {
+ sb.append(line);
+ }
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ return sb.toString();
+
+ }
}
diff --git a/pom.xml b/pom.xml
index 7f7a145056..709c3e4e00 100644
--- a/pom.xml
+++ b/pom.xml
@@ -22,20 +22,18 @@
cdicore-javacore-java-8
+ couchbase-sdk
- couchbase-sdk-intro
- couchbase-sdk-spring-servicedozerdependency-injectiondeltaspike
- enterprise-patterns
+ patternsfeign-clientgson
- gson-jackson-performanceguavaguava18guava19
@@ -70,6 +68,7 @@
rest-assuredrest-testingresteasy
+ okhttpspring-allspring-akka
@@ -80,7 +79,6 @@
spring-cucumberspring-data-cassandraspring-data-couchbase-2
- spring-data-couchbase-2bspring-data-elasticsearchspring-data-neo4jspring-data-mongodb
@@ -91,12 +89,13 @@
spring-hibernate3spring-hibernate4spring-jpa
+ spring-jmsspring-katharsisspring-mockitospring-mvc-javaspring-mvc-no-xmlspring-mvc-xml
- spring-mvc-tiles
+ spring-mvc-tilesspring-openidspring-protobufspring-quartz
diff --git a/rest-assured/pom.xml b/rest-assured/pom.xml
index 47241b18bd..e2a2af9cd9 100644
--- a/rest-assured/pom.xml
+++ b/rest-assured/pom.xml
@@ -1,257 +1,226 @@
- 4.0.0
- com.baeldung
- rest-assured
- 1.0
- rest-assured
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
- 8
- 8
-
-
-
-
-
-
-
- javax.servlet
- javax.servlet-api
- 3.1-b06
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ 4.0.0
+ com.baeldung
+ rest-assured
+ 1.0
+ rest-assured
-
-
- javax.servlet
- servlet-api
- 2.5
-
+
+
+ javax.servlet
+ javax.servlet-api
+ 3.1-b06
+
+
+ javax.servlet
+ servlet-api
+ 2.5
+
+
+ org.eclipse.jetty
+ jetty-security
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-servlet
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-servlets
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-io
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-http
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-server
+ 9.2.0.M1
+
+
+ org.eclipse.jetty
+ jetty-util
+ 9.2.0.M1
+
-
-
- org.eclipse.jetty
- jetty-security
- 9.2.0.M1
-
+
+ org.slf4j
+ slf4j-api
+ 1.7.21
+
-
-
- org.eclipse.jetty
- jetty-servlet
- 9.2.0.M1
-
+
+ log4j
+ log4j
+ 1.2.17
+
+
+ org.slf4j
+ slf4j-log4j12
+ 1.7.21
+
-
-
- org.eclipse.jetty
- jetty-servlets
- 9.2.0.M1
-
+
+ commons-logging
+ commons-logging
+ 1.2
+
-
-
- org.eclipse.jetty
- jetty-io
- 9.2.0.M1
-
+
+ org.apache.httpcomponents
+ httpcore
+ 4.4.5
+
-
-
- org.eclipse.jetty
- jetty-http
- 9.2.0.M1
-
+
+ org.apache.commons
+ commons-lang3
+ 3.4
+
+
+ com.github.fge
+ uri-template
+ 0.9
+
+
+ com.googlecode.libphonenumber
+ libphonenumber
+ 7.4.5
+
-
-
- org.eclipse.jetty
- jetty-server
- 9.2.0.M1
-
+
+ javax.mail
+ mail
+ 1.4.7
+
-
-
- org.eclipse.jetty
- jetty-util
- 9.2.0.M1
-
+
+ joda-time
+ joda-time
+ 2.9.4
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+ ${jackson.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
-
- org.slf4j
- slf4j-api
- 1.7.21
-
+
+ com.github.fge
+ msg-simple
+ 1.1
+
-
-
- log4j
- log4j
- 1.2.17
-
-
-
- org.slf4j
- slf4j-log4j12
- 1.7.21
-
+
+ com.github.fge
+ jackson-coreutils
+ 1.8
+
-
-
-
- commons-logging
- commons-logging
- 1.2
-
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ com.github.fge
+ btf
+ 1.2
+
-
- org.apache.httpcomponents
- httpcore
- 4.4.5
-
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
-
-
- org.apache.commons
- commons-lang3
- 3.4
-
+
+ org.codehaus.groovy
+ groovy-all
+ 2.4.7
+
-
-
-
- com.github.fge
- uri-template
- 0.9
-
+
+ com.github.tomakehurst
+ wiremock
+ 2.1.7
+
+
+ io.rest-assured
+ rest-assured
+ 3.0.0
+ test
+
+
+ io.rest-assured
+ json-schema-validator
+ 3.0.0
+
+
+ com.github.fge
+ json-schema-validator
+ 2.2.6
+
+
+ com.github.fge
+ json-schema-core
+ 1.2.5
+
+
+ junit
+ junit
+ 4.3
+ test
+
-
-
- com.googlecode.libphonenumber
- libphonenumber
- 7.4.5
-
+
+ org.hamcrest
+ hamcrest-all
+ 1.3
+
+
+ commons-collections
+ commons-collections
+ 3.2.2
+
-
- javax.mail
- mail
- 1.4.7
-
+
-
- joda-time
- joda-time
- 2.9.4
-
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.3
+
+ 8
+ 8
+
+
+
+
-
- com.fasterxml.jackson.core
- jackson-annotations
- 2.8.0
-
+
+ 2.8.3
+ 19.0
+
-
- com.fasterxml.jackson.core
- jackson-databind
- 2.8.0
-
-
-
- com.fasterxml.jackson.core
- jackson-core
- 2.8.0
-
-
-
- com.github.fge
- msg-simple
- 1.1
-
-
-
- com.github.fge
- jackson-coreutils
- 1.8
-
-
-
-
-
- com.google.guava
- guava
- 18.0
-
-
- com.github.fge
- btf
- 1.2
-
-
-
- org.apache.httpcomponents
- httpclient
- 4.5.2
-
-
-
- org.codehaus.groovy
- groovy-all
- 2.4.7
-
-
-
- com.github.tomakehurst
- wiremock
- 2.1.7
-
-
- io.rest-assured
- rest-assured
- 3.0.0
- test
-
-
- io.rest-assured
- json-schema-validator
- 3.0.0
-
-
- com.github.fge
- json-schema-validator
- 2.2.6
-
-
- com.github.fge
- json-schema-core
- 1.2.5
-
-
- junit
- junit
- 4.3
- test
-
-
-
- org.hamcrest
- hamcrest-all
- 1.3
-
-
-
- commons-collections
- commons-collections
- 3.2.2
-
-
-
diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml
index 652f2ab601..819e8de8a5 100644
--- a/rest-testing/pom.xml
+++ b/rest-testing/pom.xml
@@ -156,7 +156,7 @@
- 2.7.2
+ 2.7.81.7.13
diff --git a/routing-in-play/.gitignore b/routing-in-play/.gitignore
new file mode 100644
index 0000000000..eb372fc719
--- /dev/null
+++ b/routing-in-play/.gitignore
@@ -0,0 +1,8 @@
+logs
+target
+/.idea
+/.idea_modules
+/.classpath
+/.project
+/.settings
+/RUNNING_PID
diff --git a/routing-in-play/LICENSE b/routing-in-play/LICENSE
new file mode 100644
index 0000000000..4baedcb95f
--- /dev/null
+++ b/routing-in-play/LICENSE
@@ -0,0 +1,8 @@
+This software is licensed under the Apache 2 license, quoted below.
+
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with
+the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
+
+Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
+language governing permissions and limitations under the License.
\ No newline at end of file
diff --git a/routing-in-play/README b/routing-in-play/README
new file mode 100644
index 0000000000..f21d092edf
--- /dev/null
+++ b/routing-in-play/README
@@ -0,0 +1,49 @@
+This is your new Play application
+=================================
+
+This file will be packaged with your application when using `activator dist`.
+
+There are several demonstration files available in this template.
+
+Controllers
+===========
+
+- HomeController.java:
+
+ Shows how to handle simple HTTP requests.
+
+- AsyncController.java:
+
+ Shows how to do asynchronous programming when handling a request.
+
+- CountController.java:
+
+ Shows how to inject a component into a controller and use the component when
+ handling requests.
+
+Components
+==========
+
+- Module.java:
+
+ Shows how to use Guice to bind all the components needed by your application.
+
+- Counter.java:
+
+ An example of a component that contains state, in this case a simple counter.
+
+- ApplicationTimer.java:
+
+ An example of a component that starts when the application starts and stops
+ when the application stops.
+
+Filters
+=======
+
+- Filters.java:
+
+ Creates the list of HTTP filters used by your application.
+
+- ExampleFilter.java
+
+ A simple filter that adds a header to every response.
\ No newline at end of file
diff --git a/routing-in-play/app/Filters.java b/routing-in-play/app/Filters.java
new file mode 100644
index 0000000000..255de8ca93
--- /dev/null
+++ b/routing-in-play/app/Filters.java
@@ -0,0 +1,46 @@
+import javax.inject.*;
+import play.*;
+import play.mvc.EssentialFilter;
+import play.http.HttpFilters;
+import play.mvc.*;
+
+import filters.ExampleFilter;
+
+/**
+ * This class configures filters that run on every request. This
+ * class is queried by Play to get a list of filters.
+ *
+ * Play will automatically use filters from any class called
+ * Filters that is placed the root package. You can load filters
+ * from a different class by adding a `play.http.filters` setting to
+ * the application.conf configuration file.
+ */
+@Singleton
+public class Filters implements HttpFilters {
+
+ private final Environment env;
+ private final EssentialFilter exampleFilter;
+
+ /**
+ * @param env Basic environment settings for the current application.
+ * @param exampleFilter A demonstration filter that adds a header to
+ */
+ @Inject
+ public Filters(Environment env, ExampleFilter exampleFilter) {
+ this.env = env;
+ this.exampleFilter = exampleFilter;
+ }
+
+ @Override
+ public EssentialFilter[] filters() {
+ // Use the example filter if we're running development mode. If
+ // we're running in production or test mode then don't use any
+ // filters at all.
+ if (env.mode().equals(Mode.DEV)) {
+ return new EssentialFilter[] { exampleFilter };
+ } else {
+ return new EssentialFilter[] {};
+ }
+ }
+
+}
diff --git a/routing-in-play/app/Module.java b/routing-in-play/app/Module.java
new file mode 100644
index 0000000000..6e7d1766ef
--- /dev/null
+++ b/routing-in-play/app/Module.java
@@ -0,0 +1,31 @@
+import com.google.inject.AbstractModule;
+import java.time.Clock;
+
+import services.ApplicationTimer;
+import services.AtomicCounter;
+import services.Counter;
+
+/**
+ * This class is a Guice module that tells Guice how to bind several
+ * different types. This Guice module is created when the Play
+ * application starts.
+ *
+ * Play will automatically use any class called `Module` that is in
+ * the root package. You can create modules in other locations by
+ * adding `play.modules.enabled` settings to the `application.conf`
+ * configuration file.
+ */
+public class Module extends AbstractModule {
+
+ @Override
+ public void configure() {
+ // Use the system clock as the default implementation of Clock
+ bind(Clock.class).toInstance(Clock.systemDefaultZone());
+ // Ask Guice to create an instance of ApplicationTimer when the
+ // application starts.
+ bind(ApplicationTimer.class).asEagerSingleton();
+ // Set AtomicCounter as the implementation for Counter.
+ bind(Counter.class).to(AtomicCounter.class);
+ }
+
+}
diff --git a/routing-in-play/app/controllers/HomeController.java b/routing-in-play/app/controllers/HomeController.java
new file mode 100644
index 0000000000..6e340d594f
--- /dev/null
+++ b/routing-in-play/app/controllers/HomeController.java
@@ -0,0 +1,33 @@
+package controllers;
+
+import play.mvc.*;
+
+import views.html.*;
+
+/**
+ * This controller contains an action to handle HTTP requests
+ * to the application's home page.
+ */
+public class HomeController extends Controller {
+
+ /**
+ * An action that renders an HTML page with a welcome message.
+ * The configuration in the routes file means that
+ * this method will be called when the application receives a
+ * GET request with a path of /.
+ */
+ public Result index(String author,int id) {
+ return ok("Routing in Play by:"+author+" ID:"+id);
+ }
+ public Result greet(String name,int age) {
+ return ok("Hello "+name+", you are "+age+" years old");
+ }
+ public Result introduceMe(String data) {
+ String[] clientData=data.split(",");
+ return ok("Your name is "+clientData[0]+", you are "+clientData[1]+" years old");
+ }
+ public Result squareMe(Long num) {
+ return ok(num+" Squared is "+(num*num));
+ }
+
+}
diff --git a/routing-in-play/app/filters/ExampleFilter.java b/routing-in-play/app/filters/ExampleFilter.java
new file mode 100644
index 0000000000..67a6a36cc3
--- /dev/null
+++ b/routing-in-play/app/filters/ExampleFilter.java
@@ -0,0 +1,45 @@
+package filters;
+
+import akka.stream.Materializer;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.function.Function;
+import javax.inject.*;
+import play.mvc.*;
+import play.mvc.Http.RequestHeader;
+
+
+/**
+ * This is a simple filter that adds a header to all requests. It's
+ * added to the application's list of filters by the
+ * {@link Filters} class.
+ */
+@Singleton
+public class ExampleFilter extends Filter {
+
+ private final Executor exec;
+
+ /**
+ * @param mat This object is needed to handle streaming of requests
+ * and responses.
+ * @param exec This class is needed to execute code asynchronously.
+ * It is used below by the thenAsyncApply method.
+ */
+ @Inject
+ public ExampleFilter(Materializer mat, Executor exec) {
+ super(mat);
+ this.exec = exec;
+ }
+
+ @Override
+ public CompletionStage apply(
+ Function> next,
+ RequestHeader requestHeader) {
+
+ return next.apply(requestHeader).thenApplyAsync(
+ result -> result.withHeader("X-ExampleFilter", "foo"),
+ exec
+ );
+ }
+
+}
diff --git a/routing-in-play/app/services/ApplicationTimer.java b/routing-in-play/app/services/ApplicationTimer.java
new file mode 100644
index 0000000000..a951562b1d
--- /dev/null
+++ b/routing-in-play/app/services/ApplicationTimer.java
@@ -0,0 +1,50 @@
+package services;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.util.concurrent.CompletableFuture;
+import javax.inject.*;
+import play.Logger;
+import play.inject.ApplicationLifecycle;
+
+/**
+ * This class demonstrates how to run code when the
+ * application starts and stops. It starts a timer when the
+ * application starts. When the application stops it prints out how
+ * long the application was running for.
+ *
+ * This class is registered for Guice dependency injection in the
+ * {@link Module} class. We want the class to start when the application
+ * starts, so it is registered as an "eager singleton". See the code
+ * in the {@link Module} class to see how this happens.
+ *
+ * This class needs to run code when the server stops. It uses the
+ * application's {@link ApplicationLifecycle} to register a stop hook.
+ */
+@Singleton
+public class ApplicationTimer {
+
+ private final Clock clock;
+ private final ApplicationLifecycle appLifecycle;
+ private final Instant start;
+
+ @Inject
+ public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) {
+ this.clock = clock;
+ this.appLifecycle = appLifecycle;
+ // This code is called when the application starts.
+ start = clock.instant();
+ Logger.info("ApplicationTimer demo: Starting application at " + start);
+
+ // When the application starts, register a stop hook with the
+ // ApplicationLifecycle object. The code inside the stop hook will
+ // be run when the application stops.
+ appLifecycle.addStopHook(() -> {
+ Instant stop = clock.instant();
+ Long runningTime = stop.getEpochSecond() - start.getEpochSecond();
+ Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s.");
+ return CompletableFuture.completedFuture(null);
+ });
+ }
+
+}
diff --git a/routing-in-play/app/services/AtomicCounter.java b/routing-in-play/app/services/AtomicCounter.java
new file mode 100644
index 0000000000..41f741cbf7
--- /dev/null
+++ b/routing-in-play/app/services/AtomicCounter.java
@@ -0,0 +1,26 @@
+package services;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.inject.*;
+
+/**
+ * This class is a concrete implementation of the {@link Counter} trait.
+ * It is configured for Guice dependency injection in the {@link Module}
+ * class.
+ *
+ * This class has a {@link Singleton} annotation because we need to make
+ * sure we only use one counter per application. Without this
+ * annotation we would get a new instance every time a {@link Counter} is
+ * injected.
+ */
+@Singleton
+public class AtomicCounter implements Counter {
+
+ private final AtomicInteger atomicCounter = new AtomicInteger();
+
+ @Override
+ public int nextCount() {
+ return atomicCounter.getAndIncrement();
+ }
+
+}
diff --git a/routing-in-play/app/services/Counter.java b/routing-in-play/app/services/Counter.java
new file mode 100644
index 0000000000..dadad8b09d
--- /dev/null
+++ b/routing-in-play/app/services/Counter.java
@@ -0,0 +1,13 @@
+package services;
+
+/**
+ * This interface demonstrates how to create a component that is injected
+ * into a controller. The interface represents a counter that returns a
+ * incremented number each time it is called.
+ *
+ * The {@link Modules} class binds this interface to the
+ * {@link AtomicCounter} implementation.
+ */
+public interface Counter {
+ int nextCount();
+}
diff --git a/routing-in-play/app/views/index.scala.html b/routing-in-play/app/views/index.scala.html
new file mode 100644
index 0000000000..4539f5a10b
--- /dev/null
+++ b/routing-in-play/app/views/index.scala.html
@@ -0,0 +1,20 @@
+@*
+ * This template takes a single argument, a String containing a
+ * message to display.
+ *@
+@(message: String)
+
+@*
+ * Call the `main` template with two arguments. The first
+ * argument is a `String` with the title of the page, the second
+ * argument is an `Html` object containing the body of the page.
+ *@
+@main("Welcome to Play") {
+
+ @*
+ * Get an `Html` object by calling the built-in Play welcome
+ * template and passing a `String` message.
+ *@
+ @play20.welcome(message, style = "Java")
+
+}
diff --git a/routing-in-play/app/views/main.scala.html b/routing-in-play/app/views/main.scala.html
new file mode 100644
index 0000000000..9414f4be6e
--- /dev/null
+++ b/routing-in-play/app/views/main.scala.html
@@ -0,0 +1,23 @@
+@*
+ * This template is called from the `index` template. This template
+ * handles the rendering of the page header and body tags. It takes
+ * two arguments, a `String` for the title of the page and an `Html`
+ * object to insert into the body of the page.
+ *@
+@(title: String)(content: Html)
+
+
+
+
+ @* Here's where we render the page title `String`. *@
+ @title
+
+
+
+
+
+ @* And here's where we render the `Html` object containing
+ * the page content. *@
+ @content
+
+
diff --git a/routing-in-play/bin/activator b/routing-in-play/bin/activator
new file mode 100644
index 0000000000..a8b11d482f
--- /dev/null
+++ b/routing-in-play/bin/activator
@@ -0,0 +1,397 @@
+#!/usr/bin/env bash
+
+### ------------------------------- ###
+### Helper methods for BASH scripts ###
+### ------------------------------- ###
+
+realpath () {
+(
+ TARGET_FILE="$1"
+ FIX_CYGPATH="$2"
+
+ cd "$(dirname "$TARGET_FILE")"
+ TARGET_FILE=$(basename "$TARGET_FILE")
+
+ COUNT=0
+ while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ]
+ do
+ TARGET_FILE=$(readlink "$TARGET_FILE")
+ cd "$(dirname "$TARGET_FILE")"
+ TARGET_FILE=$(basename "$TARGET_FILE")
+ COUNT=$(($COUNT + 1))
+ done
+
+ # make sure we grab the actual windows path, instead of cygwin's path.
+ if [[ "x$FIX_CYGPATH" != "x" ]]; then
+ echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")"
+ else
+ echo "$(pwd -P)/$TARGET_FILE"
+ fi
+)
+}
+
+
+# Uses uname to detect if we're in the odd cygwin environment.
+is_cygwin() {
+ local os=$(uname -s)
+ case "$os" in
+ CYGWIN*) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+# TODO - Use nicer bash-isms here.
+CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi)
+
+
+# This can fix cygwin style /cygdrive paths so we get the
+# windows style paths.
+cygwinpath() {
+ local file="$1"
+ if [[ "$CYGWIN_FLAG" == "true" ]]; then
+ echo $(cygpath -w $file)
+ else
+ echo $file
+ fi
+}
+
+# Make something URI friendly
+make_url() {
+ url="$1"
+ local nospaces=${url// /%20}
+ if is_cygwin; then
+ echo "/${nospaces//\\//}"
+ else
+ echo "$nospaces"
+ fi
+}
+
+declare -a residual_args
+declare -a java_args
+declare -a scalac_args
+declare -a sbt_commands
+declare java_cmd=java
+declare java_version
+declare -r real_script_path="$(realpath "$0")"
+declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")"
+declare -r sbt_bin_dir="$(dirname "$real_script_path")"
+declare -r app_version="1.3.10"
+
+declare -r script_name=activator
+declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" )
+userhome="$HOME"
+if is_cygwin; then
+ # cygwin sets home to something f-d up, set to real windows homedir
+ userhome="$USERPROFILE"
+fi
+declare -r activator_user_home_dir="${userhome}/.activator"
+declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt"
+declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt"
+
+echoerr () {
+ echo 1>&2 "$@"
+}
+vlog () {
+ [[ $verbose || $debug ]] && echoerr "$@"
+}
+dlog () {
+ [[ $debug ]] && echoerr "$@"
+}
+
+jar_file () {
+ echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")"
+}
+
+acquire_sbt_jar () {
+ sbt_jar="$(jar_file)"
+
+ if [[ ! -f "$sbt_jar" ]]; then
+ echoerr "Could not find launcher jar: $sbt_jar"
+ exit 2
+ fi
+}
+
+execRunner () {
+ # print the arguments one to a line, quoting any containing spaces
+ [[ $verbose || $debug ]] && echo "# Executing command line:" && {
+ for arg; do
+ if printf "%s\n" "$arg" | grep -q ' '; then
+ printf "\"%s\"\n" "$arg"
+ else
+ printf "%s\n" "$arg"
+ fi
+ done
+ echo ""
+ }
+
+ # THis used to be exec, but we loose the ability to re-hook stty then
+ # for cygwin... Maybe we should flag the feature here...
+ "$@"
+}
+
+addJava () {
+ dlog "[addJava] arg = '$1'"
+ java_args=( "${java_args[@]}" "$1" )
+}
+addSbt () {
+ dlog "[addSbt] arg = '$1'"
+ sbt_commands=( "${sbt_commands[@]}" "$1" )
+}
+addResidual () {
+ dlog "[residual] arg = '$1'"
+ residual_args=( "${residual_args[@]}" "$1" )
+}
+addDebugger () {
+ addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1"
+}
+
+get_mem_opts () {
+ # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings.
+ # The reason is the Xms/Xmx, if they don't line up, cause errors.
+ if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then
+ echo ""
+ else
+ # a ham-fisted attempt to move some memory settings in concert
+ # so they need not be messed around with individually.
+ local mem=${1:-1024}
+ local codecache=$(( $mem / 8 ))
+ (( $codecache > 128 )) || codecache=128
+ (( $codecache < 512 )) || codecache=512
+ local class_metadata_size=$(( $codecache * 2 ))
+ local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize")
+
+ echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m"
+ fi
+}
+
+require_arg () {
+ local type="$1"
+ local opt="$2"
+ local arg="$3"
+ if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then
+ echo "$opt requires <$type> argument"
+ exit 1
+ fi
+}
+
+is_function_defined() {
+ declare -f "$1" > /dev/null
+}
+
+# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter
+detect_terminal_for_ui() {
+ [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && {
+ addResidual "ui"
+ }
+ # SPECIAL TEST FOR MAC
+ [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && {
+ echo "Detected MAC OSX launched script...."
+ echo "Swapping to UI"
+ addResidual "ui"
+ }
+}
+
+process_args () {
+ while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -h|-help) usage; exit 1 ;;
+ -v|-verbose) verbose=1 && shift ;;
+ -d|-debug) debug=1 && shift ;;
+
+ -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;;
+ -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;;
+ -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;;
+ -batch) exec &1 | awk -F '"' '/version/ {print $2}')
+ vlog "[process_args] java_version = '$java_version'"
+}
+
+# Detect that we have java installed.
+checkJava() {
+ local required_version="$1"
+ # Now check to see if it's a good enough version
+ if [[ "$java_version" == "" ]]; then
+ echo
+ echo No java installations was detected.
+ echo Please go to http://www.java.com/getjava/ and download
+ echo
+ exit 1
+ elif [[ ! "$java_version" > "$required_version" ]]; then
+ echo
+ echo The java installation you have is not up to date
+ echo $script_name requires at least version $required_version+, you have
+ echo version $java_version
+ echo
+ echo Please go to http://www.java.com/getjava/ and download
+ echo a valid Java Runtime and install before running $script_name.
+ echo
+ exit 1
+ fi
+}
+
+
+run() {
+ # no jar? download it.
+ [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || {
+ # still no jar? uh-oh.
+ echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar"
+ exit 1
+ }
+
+ # process the combined args, then reset "$@" to the residuals
+ process_args "$@"
+ detect_terminal_for_ui
+ set -- "${residual_args[@]}"
+ argumentCount=$#
+
+ # TODO - java check should be configurable...
+ checkJava "1.6"
+
+ #If we're in cygwin, we should use the windows config, and terminal hacks
+ if [[ "$CYGWIN_FLAG" == "true" ]]; then
+ stty -icanon min 1 -echo > /dev/null 2>&1
+ addJava "-Djline.terminal=jline.UnixTerminal"
+ addJava "-Dsbt.cygwin=true"
+ fi
+
+ # run sbt
+ execRunner "$java_cmd" \
+ "-Dactivator.home=$(make_url "$sbt_home")" \
+ ${SBT_OPTS:-$default_sbt_opts} \
+ $(get_mem_opts $sbt_mem) \
+ ${JAVA_OPTS} \
+ ${java_args[@]} \
+ -jar "$sbt_jar" \
+ "${sbt_commands[@]}" \
+ "${residual_args[@]}"
+
+ exit_code=$?
+
+ # Clean up the terminal from cygwin hacks.
+ if [[ "$CYGWIN_FLAG" == "true" ]]; then
+ stty icanon echo > /dev/null 2>&1
+ fi
+ exit $exit_code
+}
+
+
+declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy"
+declare -r sbt_opts_file=".sbtopts"
+declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts"
+declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt"
+
+usage() {
+ cat < path to global settings/plugins directory (default: ~/.sbt)
+ -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series)
+ -ivy path to local Ivy repository (default: ~/.ivy2)
+ -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem))
+ -no-share use all local caches; no sharing
+ -no-global uses global caches, but does not use global ~/.sbt directory.
+ -jvm-debug Turn on JVM debugging, open at the given port.
+ -batch Disable interactive mode
+
+ # sbt version (default: from project/build.properties if present, else latest release)
+ -sbt-version use the specified version of sbt
+ -sbt-jar use the specified jar as the sbt launcher
+ -sbt-rc use an RC version of sbt
+ -sbt-snapshot use a snapshot version of sbt
+
+ # java version (default: java from PATH, currently $(java -version 2>&1 | grep version))
+ -java-home alternate JAVA_HOME
+
+ # jvm options and output control
+ JAVA_OPTS environment variable, if unset uses "$java_opts"
+ SBT_OPTS environment variable, if unset uses "$default_sbt_opts"
+ ACTIVATOR_OPTS Environment variable, if unset uses ""
+ .sbtopts if this file exists in the current directory, it is
+ prepended to the runner args
+ /etc/sbt/sbtopts if this file exists, it is prepended to the runner args
+ -Dkey=val pass -Dkey=val directly to the java runtime
+ -J-X pass option -X directly to the java runtime
+ (-J is stripped)
+ -S-X add -X to sbt's scalacOptions (-S is stripped)
+
+In the case of duplicated or conflicting options, the order above
+shows precedence: JAVA_OPTS lowest, command line options highest.
+EOM
+}
+
+
+
+process_my_args () {
+ while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;;
+ -no-share) addJava "$noshare_opts" && shift ;;
+ -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;;
+ -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;;
+ -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;;
+ -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;;
+ -batch) exec ^&1') do (
+ if %%~j==java set JAVAINSTALLED=1
+ if %%~j==openjdk set JAVAINSTALLED=1
+)
+
+rem Detect the same thing about javac
+if "%_JAVACCMD%"=="" (
+ if not "%JAVA_HOME%"=="" (
+ if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe"
+ )
+)
+if "%_JAVACCMD%"=="" set _JAVACCMD=javac
+for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do (
+ if %%~j==javac set JAVACINSTALLED=1
+)
+
+rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style
+set JAVAOK=true
+if not defined JAVAINSTALLED set JAVAOK=false
+if not defined JAVACINSTALLED set JAVAOK=false
+
+if "%JAVAOK%"=="false" (
+ echo.
+ echo A Java JDK is not installed or can't be found.
+ if not "%JAVA_HOME%"=="" (
+ echo JAVA_HOME = "%JAVA_HOME%"
+ )
+ echo.
+ echo Please go to
+ echo http://www.oracle.com/technetwork/java/javase/downloads/index.html
+ echo and download a valid Java JDK and install before running Activator.
+ echo.
+ echo If you think this message is in error, please check
+ echo your environment variables to see if "java.exe" and "javac.exe" are
+ echo available via JAVA_HOME or PATH.
+ echo.
+ if defined DOUBLECLICKED pause
+ exit /B 1
+)
+
+rem Check what Java version is being used to determine what memory options to use
+for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
+ set JAVA_VERSION=%%g
+)
+
+rem Strips away the " characters
+set JAVA_VERSION=%JAVA_VERSION:"=%
+
+rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below
+for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do (
+ set MAJOR=%%v
+ set MINOR=%%w
+ set BUILD=%%x
+
+ set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M
+ if "!MINOR!" LSS "8" (
+ set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M
+ )
+
+ set MEM_OPTS=!META_SIZE!
+ )
+
+rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config.
+set _JAVA_OPTS=%JAVA_OPTS%
+if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS%
+
+set DEBUG_OPTS=
+
+rem Loop through the arguments, building remaining args in args variable
+set args=
+:argsloop
+if not "%~1"=="" (
+ rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them.
+ rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack.
+ set arg1=%~1
+ if "!arg1:~0,2!"=="-D" (
+ set "args=%args% "%~1"="%~2""
+ shift
+ shift
+ goto argsloop
+ )
+
+ if "%~1"=="-jvm-debug" (
+ if not "%~2"=="" (
+ rem This piece of magic somehow checks that an argument is a number
+ for /F "delims=0123456789" %%i in ("%~2") do (
+ set var="%%i"
+ )
+ if defined var (
+ rem Not a number, assume no argument given and default to 9999
+ set JPDA_PORT=9999
+ ) else (
+ rem Port was given, shift arguments
+ set JPDA_PORT=%~2
+ shift
+ )
+ ) else (
+ set JPDA_PORT=9999
+ )
+ shift
+
+ set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT!
+ goto argsloop
+ )
+ rem else
+ set "args=%args% "%~1""
+ shift
+ goto argsloop
+)
+
+:run
+
+if "!args!"=="" (
+ if defined DOUBLECLICKED (
+ set CMDS="ui"
+ ) else set CMDS=!args!
+) else set CMDS=!args!
+
+rem We add a / in front, so we get file:///C: instead of file://C:
+rem Java considers the later a UNC path.
+rem We also attempt a solid effort at making it URI friendly.
+rem We don't even bother with UNC paths.
+set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/!
+set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20!
+
+rem Checks if the command contains spaces to know if it should be wrapped in quotes or not
+set NON_SPACED_CMD=%_JAVACMD: =%
+if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS%
+if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS%
+
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+
+@endlocal
+
+exit /B %ERROR_CODE%
diff --git a/routing-in-play/build.sbt b/routing-in-play/build.sbt
new file mode 100644
index 0000000000..083d071676
--- /dev/null
+++ b/routing-in-play/build.sbt
@@ -0,0 +1,13 @@
+name := """webapp"""
+
+version := "1.0-SNAPSHOT"
+
+lazy val root = (project in file(".")).enablePlugins(PlayJava)
+
+scalaVersion := "2.11.7"
+
+libraryDependencies ++= Seq(
+ javaJdbc,
+ cache,
+ javaWs
+)
diff --git a/routing-in-play/conf/application.conf b/routing-in-play/conf/application.conf
new file mode 100644
index 0000000000..489d3f9b3e
--- /dev/null
+++ b/routing-in-play/conf/application.conf
@@ -0,0 +1,353 @@
+# This is the main configuration file for the application.
+# https://www.playframework.com/documentation/latest/ConfigFile
+# ~~~~~
+# Play uses HOCON as its configuration file format. HOCON has a number
+# of advantages over other config formats, but there are two things that
+# can be used when modifying settings.
+#
+# You can include other configuration files in this main application.conf file:
+#include "extra-config.conf"
+#
+# You can declare variables and substitute for them:
+#mykey = ${some.value}
+#
+# And if an environment variable exists when there is no other subsitution, then
+# HOCON will fall back to substituting environment variable:
+#mykey = ${JAVA_HOME}
+
+## Akka
+# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration
+# https://www.playframework.com/documentation/latest/JavaAkka#Configuration
+# ~~~~~
+# Play uses Akka internally and exposes Akka Streams and actors in Websockets and
+# other streaming HTTP responses.
+akka {
+ # "akka.log-config-on-start" is extraordinarly useful because it log the complete
+ # configuration at INFO level, including defaults and overrides, so it s worth
+ # putting at the very top.
+ #
+ # Put the following in your conf/logback.xml file:
+ #
+ #
+ #
+ # And then uncomment this line to debug the configuration.
+ #
+ #log-config-on-start = true
+}
+
+## Secret key
+# http://www.playframework.com/documentation/latest/ApplicationSecret
+# ~~~~~
+# The secret key is used to sign Play's session cookie.
+# This must be changed for production, but we don't recommend you change it in this file.
+play.crypto.secret = "changeme"
+
+## Modules
+# https://www.playframework.com/documentation/latest/Modules
+# ~~~~~
+# Control which modules are loaded when Play starts. Note that modules are
+# the replacement for "GlobalSettings", which are deprecated in 2.5.x.
+# Please see https://www.playframework.com/documentation/latest/GlobalSettings
+# for more information.
+#
+# You can also extend Play functionality by using one of the publically available
+# Play modules: https://playframework.com/documentation/latest/ModuleDirectory
+play.modules {
+ # By default, Play will load any class called Module that is defined
+ # in the root package (the "app" directory), or you can define them
+ # explicitly below.
+ # If there are any built-in modules that you want to disable, you can list them here.
+ #enabled += my.application.Module
+
+ # If there are any built-in modules that you want to disable, you can list them here.
+ #disabled += ""
+}
+
+## IDE
+# https://www.playframework.com/documentation/latest/IDE
+# ~~~~~
+# Depending on your IDE, you can add a hyperlink for errors that will jump you
+# directly to the code location in the IDE in dev mode. The following line makes
+# use of the IntelliJ IDEA REST interface:
+#play.editor="http://localhost:63342/api/file/?file=%s&line=%s"
+
+## Internationalisation
+# https://www.playframework.com/documentation/latest/JavaI18N
+# https://www.playframework.com/documentation/latest/ScalaI18N
+# ~~~~~
+# Play comes with its own i18n settings, which allow the user's preferred language
+# to map through to internal messages, or allow the language to be stored in a cookie.
+play.i18n {
+ # The application languages
+ langs = [ "en" ]
+
+ # Whether the language cookie should be secure or not
+ #langCookieSecure = true
+
+ # Whether the HTTP only attribute of the cookie should be set to true
+ #langCookieHttpOnly = true
+}
+
+## Play HTTP settings
+# ~~~~~
+play.http {
+ ## Router
+ # https://www.playframework.com/documentation/latest/JavaRouting
+ # https://www.playframework.com/documentation/latest/ScalaRouting
+ # ~~~~~
+ # Define the Router object to use for this application.
+ # This router will be looked up first when the application is starting up,
+ # so make sure this is the entry point.
+ # Furthermore, it's assumed your route file is named properly.
+ # So for an application router like `my.application.Router`,
+ # you may need to define a router file `conf/my.application.routes`.
+ # Default to Routes in the root package (aka "apps" folder) (and conf/routes)
+ #router = my.application.Router
+
+ ## Action Creator
+ # https://www.playframework.com/documentation/latest/JavaActionCreator
+ # ~~~~~
+ #actionCreator = null
+
+ ## ErrorHandler
+ # https://www.playframework.com/documentation/latest/JavaRouting
+ # https://www.playframework.com/documentation/latest/ScalaRouting
+ # ~~~~~
+ # If null, will attempt to load a class called ErrorHandler in the root package,
+ #errorHandler = null
+
+ ## Filters
+ # https://www.playframework.com/documentation/latest/ScalaHttpFilters
+ # https://www.playframework.com/documentation/latest/JavaHttpFilters
+ # ~~~~~
+ # Filters run code on every request. They can be used to perform
+ # common logic for all your actions, e.g. adding common headers.
+ # Defaults to "Filters" in the root package (aka "apps" folder)
+ # Alternatively you can explicitly register a class here.
+ #filters = my.application.Filters
+
+ ## Session & Flash
+ # https://www.playframework.com/documentation/latest/JavaSessionFlash
+ # https://www.playframework.com/documentation/latest/ScalaSessionFlash
+ # ~~~~~
+ session {
+ # Sets the cookie to be sent only over HTTPS.
+ #secure = true
+
+ # Sets the cookie to be accessed only by the server.
+ #httpOnly = true
+
+ # Sets the max-age field of the cookie to 5 minutes.
+ # NOTE: this only sets when the browser will discard the cookie. Play will consider any
+ # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout,
+ # you need to put a timestamp in the session and check it at regular intervals to possibly expire it.
+ #maxAge = 300
+
+ # Sets the domain on the session cookie.
+ #domain = "example.com"
+ }
+
+ flash {
+ # Sets the cookie to be sent only over HTTPS.
+ #secure = true
+
+ # Sets the cookie to be accessed only by the server.
+ #httpOnly = true
+ }
+}
+
+## Netty Provider
+# https://www.playframework.com/documentation/latest/SettingsNetty
+# ~~~~~
+play.server.netty {
+ # Whether the Netty wire should be logged
+ #log.wire = true
+
+ # If you run Play on Linux, you can use Netty's native socket transport
+ # for higher performance with less garbage.
+ #transport = "native"
+}
+
+## WS (HTTP Client)
+# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS
+# ~~~~~
+# The HTTP client primarily used for REST APIs. The default client can be
+# configured directly, but you can also create different client instances
+# with customized settings. You must enable this by adding to build.sbt:
+#
+# libraryDependencies += ws // or javaWs if using java
+#
+play.ws {
+ # Sets HTTP requests not to follow 302 requests
+ #followRedirects = false
+
+ # Sets the maximum number of open HTTP connections for the client.
+ #ahc.maxConnectionsTotal = 50
+
+ ## WS SSL
+ # https://www.playframework.com/documentation/latest/WsSSL
+ # ~~~~~
+ ssl {
+ # Configuring HTTPS with Play WS does not require programming. You can
+ # set up both trustManager and keyManager for mutual authentication, and
+ # turn on JSSE debugging in development with a reload.
+ #debug.handshake = true
+ #trustManager = {
+ # stores = [
+ # { type = "JKS", path = "exampletrust.jks" }
+ # ]
+ #}
+ }
+}
+
+## Cache
+# https://www.playframework.com/documentation/latest/JavaCache
+# https://www.playframework.com/documentation/latest/ScalaCache
+# ~~~~~
+# Play comes with an integrated cache API that can reduce the operational
+# overhead of repeated requests. You must enable this by adding to build.sbt:
+#
+# libraryDependencies += cache
+#
+play.cache {
+ # If you want to bind several caches, you can bind the individually
+ #bindCaches = ["db-cache", "user-cache", "session-cache"]
+}
+
+## Filters
+# https://www.playframework.com/documentation/latest/Filters
+# ~~~~~
+# There are a number of built-in filters that can be enabled and configured
+# to give Play greater security. You must enable this by adding to build.sbt:
+#
+# libraryDependencies += filters
+#
+play.filters {
+ ## CORS filter configuration
+ # https://www.playframework.com/documentation/latest/CorsFilter
+ # ~~~~~
+ # CORS is a protocol that allows web applications to make requests from the browser
+ # across different domains.
+ # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has
+ # dependencies on CORS settings.
+ cors {
+ # Filter paths by a whitelist of path prefixes
+ #pathPrefixes = ["/some/path", ...]
+
+ # The allowed origins. If null, all origins are allowed.
+ #allowedOrigins = ["http://www.example.com"]
+
+ # The allowed HTTP methods. If null, all methods are allowed
+ #allowedHttpMethods = ["GET", "POST"]
+ }
+
+ ## CSRF Filter
+ # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter
+ # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter
+ # ~~~~~
+ # Play supports multiple methods for verifying that a request is not a CSRF request.
+ # The primary mechanism is a CSRF token. This token gets placed either in the query string
+ # or body of every form submitted, and also gets placed in the users session.
+ # Play then verifies that both tokens are present and match.
+ csrf {
+ # Sets the cookie to be sent only over HTTPS
+ #cookie.secure = true
+
+ # Defaults to CSRFErrorHandler in the root package.
+ #errorHandler = MyCSRFErrorHandler
+ }
+
+ ## Security headers filter configuration
+ # https://www.playframework.com/documentation/latest/SecurityHeaders
+ # ~~~~~
+ # Defines security headers that prevent XSS attacks.
+ # If enabled, then all options are set to the below configuration by default:
+ headers {
+ # The X-Frame-Options header. If null, the header is not set.
+ #frameOptions = "DENY"
+
+ # The X-XSS-Protection header. If null, the header is not set.
+ #xssProtection = "1; mode=block"
+
+ # The X-Content-Type-Options header. If null, the header is not set.
+ #contentTypeOptions = "nosniff"
+
+ # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set.
+ #permittedCrossDomainPolicies = "master-only"
+
+ # The Content-Security-Policy header. If null, the header is not set.
+ #contentSecurityPolicy = "default-src 'self'"
+ }
+
+ ## Allowed hosts filter configuration
+ # https://www.playframework.com/documentation/latest/AllowedHostsFilter
+ # ~~~~~
+ # Play provides a filter that lets you configure which hosts can access your application.
+ # This is useful to prevent cache poisoning attacks.
+ hosts {
+ # Allow requests to example.com, its subdomains, and localhost:9000.
+ #allowed = [".example.com", "localhost:9000"]
+ }
+}
+
+## Evolutions
+# https://www.playframework.com/documentation/latest/Evolutions
+# ~~~~~
+# Evolutions allows database scripts to be automatically run on startup in dev mode
+# for database migrations. You must enable this by adding to build.sbt:
+#
+# libraryDependencies += evolutions
+#
+play.evolutions {
+ # You can disable evolutions for a specific datasource if necessary
+ #db.default.enabled = false
+}
+
+## Database Connection Pool
+# https://www.playframework.com/documentation/latest/SettingsJDBC
+# ~~~~~
+# Play doesn't require a JDBC database to run, but you can easily enable one.
+#
+# libraryDependencies += jdbc
+#
+play.db {
+ # The combination of these two settings results in "db.default" as the
+ # default JDBC pool:
+ #config = "db"
+ #default = "default"
+
+ # Play uses HikariCP as the default connection pool. You can override
+ # settings by changing the prototype:
+ prototype {
+ # Sets a fixed JDBC connection pool size of 50
+ #hikaricp.minimumIdle = 50
+ #hikaricp.maximumPoolSize = 50
+ }
+}
+
+## JDBC Datasource
+# https://www.playframework.com/documentation/latest/JavaDatabase
+# https://www.playframework.com/documentation/latest/ScalaDatabase
+# ~~~~~
+# Once JDBC datasource is set up, you can work with several different
+# database options:
+#
+# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick
+# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA
+# EBean: https://playframework.com/documentation/latest/JavaEbean
+# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm
+#
+db {
+ # You can declare as many datasources as you want.
+ # By convention, the default datasource is named `default`
+
+ # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database
+ #default.driver = org.h2.Driver
+ #default.url = "jdbc:h2:mem:play"
+ #default.username = sa
+ #default.password = ""
+
+ # You can turn on SQL logging for any datasource
+ # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements
+ #default.logSql=true
+}
diff --git a/routing-in-play/conf/logback.xml b/routing-in-play/conf/logback.xml
new file mode 100644
index 0000000000..86ec12c0af
--- /dev/null
+++ b/routing-in-play/conf/logback.xml
@@ -0,0 +1,41 @@
+
+
+
+
+
+
+ ${application.home:-.}/logs/application.log
+
+ %date [%level] from %logger in %thread - %message%n%xException
+
+
+
+
+
+ %coloredLevel %logger{15} - %message%n%xException{10}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/routing-in-play/conf/routes b/routing-in-play/conf/routes
new file mode 100644
index 0000000000..f72d8a1a14
--- /dev/null
+++ b/routing-in-play/conf/routes
@@ -0,0 +1,7 @@
+GET / controllers.HomeController.index(author="Baeldung",id:Int?=1)
+GET /:author controllers.HomeController.index(author,id:Int?=1)
+GET /greet/:name/:age controllers.HomeController.greet(name,age:Integer)
+GET /square/$num<[0-9]+> controllers.HomeController.squareMe(num:Long)
+# Map static resources from the /public folder to the /assets URL path
+GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
+GET /*data controllers.HomeController.introduceMe(data)
diff --git a/routing-in-play/libexec/activator-launch-1.3.10.jar b/routing-in-play/libexec/activator-launch-1.3.10.jar
new file mode 100644
index 0000000000..69050e7dec
Binary files /dev/null and b/routing-in-play/libexec/activator-launch-1.3.10.jar differ
diff --git a/routing-in-play/project/build.properties b/routing-in-play/project/build.properties
new file mode 100644
index 0000000000..6d22e3f2d1
--- /dev/null
+++ b/routing-in-play/project/build.properties
@@ -0,0 +1,4 @@
+#Activator-generated Properties
+#Fri Sep 30 14:25:10 EAT 2016
+template.uuid=26c759a5-daf0-4e02-bcfa-ac69725267c0
+sbt.version=0.13.11
diff --git a/routing-in-play/project/plugins.sbt b/routing-in-play/project/plugins.sbt
new file mode 100644
index 0000000000..e8e7f602f7
--- /dev/null
+++ b/routing-in-play/project/plugins.sbt
@@ -0,0 +1,21 @@
+// The Play plugin
+addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.8")
+
+// Web plugins
+addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")
+addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0")
+addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.4")
+addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.8")
+addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.1")
+addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0")
+addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.6")
+
+// Play enhancer - this automatically generates getters/setters for public fields
+// and rewrites accessors of these fields to use the getters/setters. Remove this
+// plugin if you prefer not to have this feature, or disable on a per project
+// basis using disablePlugins(PlayEnhancer) in your build.sbt
+addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0")
+
+// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using
+// enablePlugins(PlayEbean).
+// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.2")
diff --git a/routing-in-play/public/images/favicon.png b/routing-in-play/public/images/favicon.png
new file mode 100644
index 0000000000..c7d92d2ae4
Binary files /dev/null and b/routing-in-play/public/images/favicon.png differ
diff --git a/routing-in-play/public/javascripts/hello.js b/routing-in-play/public/javascripts/hello.js
new file mode 100644
index 0000000000..02ee13c7ca
--- /dev/null
+++ b/routing-in-play/public/javascripts/hello.js
@@ -0,0 +1,3 @@
+if (window.console) {
+ console.log("Welcome to your Play application's JavaScript!");
+}
diff --git a/couchbase-sdk-spring-service/src/main/resources/application.properties b/routing-in-play/public/stylesheets/main.css
similarity index 100%
rename from couchbase-sdk-spring-service/src/main/resources/application.properties
rename to routing-in-play/public/stylesheets/main.css
diff --git a/routing-in-play/test/ApplicationTest.java b/routing-in-play/test/ApplicationTest.java
new file mode 100644
index 0000000000..3d7c4875aa
--- /dev/null
+++ b/routing-in-play/test/ApplicationTest.java
@@ -0,0 +1,45 @@
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.*;
+
+import play.mvc.*;
+import play.test.*;
+import play.data.DynamicForm;
+import play.data.validation.ValidationError;
+import play.data.validation.Constraints.RequiredValidator;
+import play.i18n.Lang;
+import play.libs.F;
+import play.libs.F.*;
+import play.twirl.api.Content;
+
+import static play.test.Helpers.*;
+import static org.junit.Assert.*;
+
+
+/**
+ *
+ * Simple (JUnit) tests that can call all parts of a play app.
+ * If you are interested in mocking a whole application, see the wiki for more details.
+ *
+ */
+public class ApplicationTest {
+
+ @Test
+ public void simpleCheck() {
+ int a = 1 + 1;
+ assertEquals(2, a);
+ }
+
+ @Test
+ public void renderTemplate() {
+ Content html = views.html.index.render("Your new application is ready.");
+ assertEquals("text/html", html.contentType());
+ assertTrue(html.body().contains("Your new application is ready."));
+ }
+
+
+}
diff --git a/play-framework/student-api/test/IntegrationTest.java b/routing-in-play/test/IntegrationTest.java
similarity index 100%
rename from play-framework/student-api/test/IntegrationTest.java
rename to routing-in-play/test/IntegrationTest.java
diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml
index c6bd2b042c..bf5a082fba 100644
--- a/selenium-junit-testng/pom.xml
+++ b/selenium-junit-testng/pom.xml
@@ -1,36 +1,48 @@
-
- 4.0.0
- com.baeldung
- selenium-junit-testng
- 0.0.1-SNAPSHOT
-
- src
-
-
- maven-compiler-plugin
- 3.1
-
- 1.8
- 1.8
-
-
-
-
-
-
- org.seleniumhq.selenium
- selenium-java
- 2.53.1
-
-
- junit
- junit
- 4.8.1
-
-
- org.testng
- testng
- 6.9.10
-
-
+
+ 4.0.0
+ com.baeldung
+ selenium-junit-testng
+ 0.0.1-SNAPSHOT
+
+ src
+
+
+ maven-compiler-plugin
+ 3.1
+
+ 1.8
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.19.1
+
+
+
+ Test*.java
+
+
+
+
+
+
+
+ org.seleniumhq.selenium
+ selenium-java
+ 2.53.1
+
+
+ junit
+ junit
+ 4.8.1
+
+
+ org.testng
+ testng
+ 6.9.10
+
+
\ No newline at end of file
diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java
index 6020b6bd2c..d8b248df81 100644
--- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java
+++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java
@@ -6,9 +6,8 @@ import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumExample {
private WebDriver webDriver;
- private final String url = "http://www.baeldung.com/";
- private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
-
+ private String url = "http://www.baeldung.com/";
+
public SeleniumExample() {
webDriver = new FirefoxDriver();
webDriver.get(url);
@@ -18,12 +17,8 @@ public class SeleniumExample {
webDriver.close();
}
- public String getActualTitle() {
+ public String getTitle() {
return webDriver.getTitle();
}
- public String getExpectedTitle() {
- return expectedTitle;
- }
-
}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
index 371f730eb9..f183a613e7 100644
--- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
@@ -1,6 +1,7 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.After;
@@ -10,6 +11,7 @@ import org.junit.Test;
public class TestSeleniumWithJUnit {
private SeleniumExample seleniumExample;
+ private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@Before
public void setUp() {
@@ -23,8 +25,8 @@ public class TestSeleniumWithJUnit {
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String expectedTitle = seleniumExample.getExpectedTitle();
- String actualTitle = seleniumExample.getActualTitle();
+ String actualTitle = seleniumExample.getTitle();
+ assertNotNull(actualTitle);
assertEquals(actualTitle, expectedTitle);
}
}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
index ec10f9ca82..3c94f3d440 100644
--- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
@@ -1,6 +1,7 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
@@ -10,6 +11,7 @@ import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private SeleniumExample seleniumExample;
+ private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@BeforeSuite
public void setUp() {
@@ -23,8 +25,8 @@ public class TestSeleniumWithTestNG {
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String expectedTitle = seleniumExample.getExpectedTitle();
- String actualTitle = seleniumExample.getActualTitle();
+ String actualTitle = seleniumExample.getTitle();
+ assertNotNull(actualTitle);
assertEquals(actualTitle, expectedTitle);
}
}
diff --git a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java
deleted file mode 100644
index dcdfafc4f1..0000000000
--- a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.baeldun.selenium.testng;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.testng.annotations.AfterSuite;
-import org.testng.annotations.BeforeSuite;
-import org.testng.annotations.Test;
-
-public class TestSeleniumWithTestNG {
-
- private WebDriver webDriver;
- private final String url = "http://www.baeldung.com/";
- private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
-
- @BeforeSuite
- public void setUp() {
- webDriver = new FirefoxDriver();
- webDriver.get(url);
- }
-
- @AfterSuite
- public void tearDown() {
- webDriver.close();
- }
-
- @Test
- public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String actualTitleReturned = webDriver.getTitle();
- assertNotNull(actualTitleReturned);
- assertEquals(expectedTitle, actualTitleReturned);
- }
-}
diff --git a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
deleted file mode 100644
index a7b36c4e4e..0000000000
--- a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.baeldung.selenium.junit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.firefox.FirefoxDriver;
-
-public class TestSeleniumWithJUnit {
-
- private WebDriver webDriver;
- private final String url = "http://www.baeldung.com/";
- private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
-
- @Before
- public void setUp() {
- webDriver = new FirefoxDriver();
- webDriver.get(url);
- }
-
- @After
- public void tearDown() {
- webDriver.close();
- }
-
- @Test
- public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String actualTitleReturned = webDriver.getTitle();
- assertNotNull(actualTitleReturned);
- assertEquals(expectedTitle, actualTitleReturned);
- }
-}
diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java
index 624e289812..aa5941c763 100644
--- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java
+++ b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java
@@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId
- 4.0.0
- com.baeldung
- spring-all
- 0.1-SNAPSHOT
+
+ 4.0.0
+ com.baeldung
+ spring-all
+ 0.1-SNAPSHOT
- spring-all
- war
+ spring-all
+ war
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.3.6.RELEASE
-
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.3.6.RELEASE
+
-
-
- com.fasterxml.jackson.core
- jackson-databind
-
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
-
+
-
- org.springframework
- spring-web
-
-
- org.springframework
- spring-webmvc
-
-
- org.springframework
- spring-orm
-
-
- org.springframework
- spring-context
-
+
+ org.springframework
+ spring-web
+
+
+ org.springframework
+ spring-webmvc
+
+
+ org.springframework
+ spring-orm
+
+
+ org.springframework
+ spring-context
+
-
+
-
- org.springframework
- spring-aspects
-
+
+ org.springframework
+ spring-aspects
+
-
+
-
- org.hibernate
- hibernate-core
- ${hibernate.version}
-
-
- org.javassist
- javassist
-
-
- mysql
- mysql-connector-java
- runtime
-
-
- org.hsqldb
- hsqldb
-
-
-
+
+ org.hibernate
+ hibernate-core
+ ${hibernate.version}
+
+
+ org.javassist
+ javassist
+
+
+ mysql
+ mysql-connector-java
+ runtime
+
+
+ org.hsqldb
+ hsqldb
+
-
- org.hibernate
- hibernate-validator
-
+
-
+
+ org.hibernate
+ hibernate-validator
+
-
- javax.servlet
- javax.servlet-api
- provided
-
+
-
- javax.servlet
- jstl
- runtime
-
+
+ javax.servlet
+ javax.servlet-api
+ provided
+
-
+
+ javax.servlet
+ jstl
+ runtime
+
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
+
-
- org.slf4j
- slf4j-api
-
-
- ch.qos.logback
- logback-classic
-
-
-
- org.slf4j
- jcl-over-slf4j
-
-
-
- org.slf4j
- log4j-over-slf4j
-
+
+ com.google.guava
+ guava
+ ${guava.version}
+
-
+
-
- org.springframework
- spring-test
- test
-
+
+ org.slf4j
+ slf4j-api
+
+
+ ch.qos.logback
+ logback-classic
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+
+
+
+ org.slf4j
+ log4j-over-slf4j
+
-
- junit
- junit
- test
-
+
-
- org.assertj
- assertj-core
- 3.5.1
- test
-
+
+ org.springframework
+ spring-test
+ test
+
-
- org.hamcrest
- hamcrest-core
- test
-
-
- org.hamcrest
- hamcrest-library
- test
-
+
+ junit
+ junit
+ test
+
-
- org.mockito
- mockito-core
- test
-
+
+ org.assertj
+ assertj-core
+ 3.5.1
+ test
+
-
- org.easymock
- easymock
- 3.4
- test
-
+
+ org.hamcrest
+ hamcrest-core
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ test
+
-
+
+ org.mockito
+ mockito-core
+ test
+
-
+
+ org.easymock
+ easymock
+ 3.4
+ test
+
+
+ org.ehcache
+ ehcache
+ 3.1.3
+
-
+
-
- org.springframework
- spring-framework-bom
- ${org.springframework.version}
- pom
- import
-
+
-
- org.springframework
- spring-core
- ${org.springframework.version}
-
+
-
+
+ org.springframework
+ spring-framework-bom
+ ${org.springframework.version}
+ pom
+ import
+
-
+
+ org.springframework
+ spring-core
+ ${org.springframework.version}
+
-
- spring-all
-
-
- src/main/resources
- true
-
-
+
-
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- 1.8
- 1.8
-
-
+
+ spring-all
+
+
+ src/main/resources
+ true
+
+
-
- org.apache.maven.plugins
- maven-war-plugin
-
- false
-
-
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
-
-
-
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
-
- org.codehaus.cargo
- cargo-maven2-plugin
- ${cargo-maven2-plugin.version}
-
- true
-
- jetty8x
- embedded
-
-
-
-
-
-
- 8082
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-war-plugin
+
+ false
+
+
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+
+
+
+
+
+
+
-
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+ true
+
+ jetty8x
+ embedded
+
+
+
+
+
+
+ 8082
+
+
+
+
-
-
- 4.3.1.RELEASE
- 4.0.4.RELEASE
- 3.20.0-GA
- 1.2
+
-
- 4.3.11.Final
- 5.1.38
+
-
- 1.7.13
- 1.1.3
+
+
+ 4.3.1.RELEASE
+ 4.0.4.RELEASE
+ 3.20.0-GA
+ 1.2
-
- 5.2.2.Final
+
+ 4.3.11.Final
+ 5.1.38
-
- 19.0
- 3.4
+
+ 1.7.13
+ 1.1.3
-
- 1.3
- 4.12
- 1.10.19
+
+ 5.2.2.Final
- 4.4.1
- 4.5
+
+ 19.0
+ 3.4
- 2.9.0
+
+ 1.3
+ 4.12
+ 1.10.19
-
- 3.5.1
- 2.6
- 2.19.1
- 2.7
- 1.4.18
+ 4.4.1
+ 4.5
-
+ 2.9.0
+
+
+ 3.5.1
+ 2.6
+ 2.19.1
+ 2.7
+ 1.4.18
+
+
\ No newline at end of file
diff --git a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java
index 38b5a5a3ec..02b8c3c159 100644
--- a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java
+++ b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java
@@ -72,5 +72,5 @@ public abstract class AbstractService {
public String getAddress5(final Customer customer) {
return customer.getAddress();
}
-
+
}
diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java
index 443635fb70..ec6cf19785 100644
--- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java
+++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java
@@ -11,21 +11,21 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class StudentControllerConfig implements WebApplicationInitializer {
-
- @Override
- public void onStartup(ServletContext sc) throws ServletException {
- AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
- root.register(WebConfig.class);
- root.setServletContext(sc);
+ @Override
+ public void onStartup(ServletContext sc) throws ServletException {
+ AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
+ root.register(WebConfig.class);
- // Manages the lifecycle of the root application context
- sc.addListener(new ContextLoaderListener(root));
+ root.setServletContext(sc);
- DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext());
+ // Manages the lifecycle of the root application context
+ sc.addListener(new ContextLoaderListener(root));
- ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
- appServlet.setLoadOnStartup(1);
- appServlet.addMapping("/test/*");
- }
+ DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext());
+
+ ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
+ appServlet.setLoadOnStartup(1);
+ appServlet.addMapping("/test/*");
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java
index f55af69c88..251a1affa1 100644
--- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java
+++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java
@@ -11,13 +11,13 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
-@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" })
+@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
-
+
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
diff --git a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java
index 95903bcc40..4b38b4dd34 100644
--- a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java
+++ b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java
@@ -7,15 +7,15 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
-public class RestController{
+public class RestController {
- @GetMapping(value="/student/{studentId}")
- public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
- Student student = new Student();
- student.setName("Peter");
- student.setId(studentId);
+ @GetMapping(value = "/student/{studentId}")
+ public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
+ Student student = new Student();
+ student.setName("Peter");
+ student.setId(studentId);
- return student;
+ return student;
- }
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/controller/student/Student.java b/spring-all/src/main/java/org/baeldung/controller/student/Student.java
index ee706d7028..5f49e5ceb9 100644
--- a/spring-all/src/main/java/org/baeldung/controller/student/Student.java
+++ b/spring-all/src/main/java/org/baeldung/controller/student/Student.java
@@ -1,33 +1,33 @@
package org.baeldung.controller.student;
public class Student {
- private String name;
-
- private int id;
+ private String name;
- public String getName() {
- return name;
- }
+ private int id;
- public void setName(String name) {
- this.name = name;
- }
+ public String getName() {
+ return name;
+ }
- public int getId() {
- return id;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public void setId(int id) {
- this.id = id;
- }
-
- @Override
- public int hashCode(){
- return this.id;
- }
-
- @Override
- public boolean equals(Object obj){
- return this.name.equals(((Student)obj).getName());
- }
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @Override
+ public int hashCode() {
+ return this.id;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return this.name.equals(((Student) obj).getName());
+ }
}
\ No newline at end of file
diff --git a/spring-all/src/main/java/org/baeldung/ehcache/app/App.java b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java
new file mode 100755
index 0000000000..99370186a3
--- /dev/null
+++ b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java
@@ -0,0 +1,24 @@
+package org.baeldung.ehcache.app;
+
+import org.baeldung.ehcache.calculator.SquaredCalculator;
+import org.baeldung.ehcache.config.CacheHelper;
+
+public class App {
+
+ public static void main(String[] args) {
+
+ SquaredCalculator squaredCalculator = new SquaredCalculator();
+ CacheHelper cacheHelper = new CacheHelper();
+
+ squaredCalculator.setCache(cacheHelper);
+
+ calculate(squaredCalculator);
+ calculate(squaredCalculator);
+ }
+
+ private static void calculate(SquaredCalculator squaredCalculator) {
+ for (int i = 10; i < 15; i++) {
+ System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
+ }
+ }
+}
diff --git a/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java
new file mode 100755
index 0000000000..25957539df
--- /dev/null
+++ b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java
@@ -0,0 +1,24 @@
+package org.baeldung.ehcache.calculator;
+
+import org.baeldung.ehcache.config.CacheHelper;
+
+public class SquaredCalculator {
+ private CacheHelper cache;
+
+ public int getSquareValueOfNumber(int input) {
+ if (cache.getSquareNumberCache().containsKey(input)) {
+ return cache.getSquareNumberCache().get(input);
+ }
+
+ System.out.println("Calculating square value of " + input + " and caching result.");
+
+ int squaredValue = (int) Math.pow(input, 2);
+ cache.getSquareNumberCache().put(input, squaredValue);
+
+ return squaredValue;
+ }
+
+ public void setCache(CacheHelper cache) {
+ this.cache = cache;
+ }
+}
diff --git a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java
new file mode 100755
index 0000000000..387a57880b
--- /dev/null
+++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java
@@ -0,0 +1,25 @@
+package org.baeldung.ehcache.config;
+
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.config.builders.ResourcePoolsBuilder;
+
+public class CacheHelper {
+
+ private CacheManager cacheManager;
+ private Cache squareNumberCache;
+
+ public CacheHelper() {
+ cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))).build();
+ cacheManager.init();
+
+ squareNumberCache = cacheManager.getCache("squaredNumber", Integer.class, Integer.class);
+ }
+
+ public Cache getSquareNumberCache() {
+ return squareNumberCache;
+ }
+
+}
diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java
index f96184a8a3..97d7fe0ffa 100644
--- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java
+++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java
@@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
super();
}
-
@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() {
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
diff --git a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java
index ae1c6157db..562069bc9a 100644
--- a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java
+++ b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java
@@ -2,14 +2,14 @@ package org.baeldung.scopes;
public class HelloMessageGenerator {
- private String message;
+ private String message;
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(final String message) {
- this.message = message;
- }
+ public void setMessage(final String message) {
+ this.message = message;
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/scopes/Person.java b/spring-all/src/main/java/org/baeldung/scopes/Person.java
index e6139c31dd..b070007a5c 100644
--- a/spring-all/src/main/java/org/baeldung/scopes/Person.java
+++ b/spring-all/src/main/java/org/baeldung/scopes/Person.java
@@ -1,27 +1,27 @@
package org.baeldung.scopes;
public class Person {
- private String name;
- private int age;
+ private String name;
+ private int age;
- public Person() {
- }
+ public Person() {
+ }
- public Person(final String name, final int age) {
- this.name = name;
- }
+ public Person(final String name, final int age) {
+ this.name = name;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(final String name) {
- this.name = name;
- }
+ public void setName(final String name) {
+ this.name = name;
+ }
- @Override
- public String toString() {
- return "Person [name=" + name + "]";
- }
+ @Override
+ public String toString() {
+ return "Person [name=" + name + "]";
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java
index bf733b75f9..1e3d5f3b14 100644
--- a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java
+++ b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java
@@ -9,23 +9,23 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ScopesController {
- public static final Logger LOG = Logger.getLogger(ScopesController.class);
+ public static final Logger LOG = Logger.getLogger(ScopesController.class);
- @Resource(name = "requestMessage")
- HelloMessageGenerator requestMessage;
+ @Resource(name = "requestMessage")
+ HelloMessageGenerator requestMessage;
- @Resource(name = "sessionMessage")
- HelloMessageGenerator sessionMessage;
+ @Resource(name = "sessionMessage")
+ HelloMessageGenerator sessionMessage;
- @RequestMapping("/scopes")
- public String getScopes(final Model model) {
- LOG.info("Request Message:" + requestMessage.getMessage());
- LOG.info("Session Message" + sessionMessage.getMessage());
- requestMessage.setMessage("Good morning!");
- sessionMessage.setMessage("Good afternoon!");
- model.addAttribute("requestMessage", requestMessage.getMessage());
- model.addAttribute("sessionMessage", sessionMessage.getMessage());
- return "scopesExample";
- }
+ @RequestMapping("/scopes")
+ public String getScopes(final Model model) {
+ LOG.info("Request Message:" + requestMessage.getMessage());
+ LOG.info("Session Message" + sessionMessage.getMessage());
+ requestMessage.setMessage("Good morning!");
+ sessionMessage.setMessage("Good afternoon!");
+ model.addAttribute("requestMessage", requestMessage.getMessage());
+ model.addAttribute("sessionMessage", sessionMessage.getMessage());
+ return "scopesExample";
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java
index 5a9b266388..a9bc298db3 100644
--- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java
+++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java
@@ -16,42 +16,42 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver;
@ComponentScan("org.baeldung.scopes")
@EnableWebMvc
public class ScopesConfig {
- @Bean
- public UrlBasedViewResolver setupViewResolver() {
- final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
- resolver.setPrefix("/WEB-INF/view/");
- resolver.setSuffix(".jsp");
- resolver.setViewClass(JstlView.class);
- return resolver;
- }
+ @Bean
+ public UrlBasedViewResolver setupViewResolver() {
+ final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
+ resolver.setPrefix("/WEB-INF/view/");
+ resolver.setSuffix(".jsp");
+ resolver.setViewClass(JstlView.class);
+ return resolver;
+ }
- @Bean
- @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
- public HelloMessageGenerator requestMessage() {
- return new HelloMessageGenerator();
- }
+ @Bean
+ @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
+ public HelloMessageGenerator requestMessage() {
+ return new HelloMessageGenerator();
+ }
- @Bean
- @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
- public HelloMessageGenerator sessionMessage() {
- return new HelloMessageGenerator();
- }
+ @Bean
+ @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
+ public HelloMessageGenerator sessionMessage() {
+ return new HelloMessageGenerator();
+ }
- @Bean
- @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
- public HelloMessageGenerator globalSessionMessage() {
- return new HelloMessageGenerator();
- }
+ @Bean
+ @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
+ public HelloMessageGenerator globalSessionMessage() {
+ return new HelloMessageGenerator();
+ }
- @Bean
- @Scope("prototype")
- public Person personPrototype() {
- return new Person();
- }
+ @Bean
+ @Scope("prototype")
+ public Person personPrototype() {
+ return new Person();
+ }
- @Bean
- @Scope("singleton")
- public Person personSingleton() {
- return new Person();
- }
+ @Bean
+ @Scope("singleton")
+ public Person personSingleton() {
+ return new Person();
+ }
}
diff --git a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java
index 4abd3cc813..ce34adf6c1 100644
--- a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java
+++ b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java
@@ -11,7 +11,6 @@ public class Foo {
private static final AtomicInteger instanceCount = new AtomicInteger(0);
-
private final int instanceNum;
public Foo() {
diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java
index 44f1767405..84bc3a8033 100644
--- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java
@@ -18,17 +18,16 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
-
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
-@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class )
+@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ControllerAnnotationTest {
-
- private MockMvc mockMvc;
+
+ private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
-
+
private Student selectedStudent;
@Before
@@ -43,9 +42,7 @@ public class ControllerAnnotationTest {
@Test
public void testTestController() throws Exception {
- ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
- .andReturn()
- .getModelAndView();
+ ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@@ -57,9 +54,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestController() throws Exception {
- String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
- .andReturn().getResponse()
- .getContentAsString();
+ String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@@ -72,9 +67,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestAnnotatedController() throws Exception {
- String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
- .andReturn().getResponse()
- .getContentAsString();
+ String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java
index f5e41cd5a2..47915b8ce9 100644
--- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java
+++ b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java
@@ -19,7 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
-@ContextConfiguration({"classpath:test-mvc.xml"})
+@ContextConfiguration({ "classpath:test-mvc.xml" })
public class ControllerTest {
private MockMvc mockMvc;
@@ -41,9 +41,7 @@ public class ControllerTest {
@Test
public void testTestController() throws Exception {
- ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
- .andReturn()
- .getModelAndView();
+ ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@@ -55,9 +53,7 @@ public class ControllerTest {
@Test
public void testRestController() throws Exception {
- String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
- .andReturn().getResponse()
- .getContentAsString();
+ String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@@ -70,9 +66,7 @@ public class ControllerTest {
@Test
public void testRestAnnotatedController() throws Exception {
- String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
- .andReturn().getResponse()
- .getContentAsString();
+ String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java
index b1dd248c26..59b9e225ad 100644
--- a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java
+++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java
@@ -8,36 +8,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopesTest {
- private static final String NAME = "John Smith";
- private static final String NAME_OTHER = "Anna Jones";
+ private static final String NAME = "John Smith";
+ private static final String NAME_OTHER = "Anna Jones";
- @Test
- public void testScopeSingleton() {
- final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
+ @Test
+ public void testScopeSingleton() {
+ final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
- final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
- final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
+ final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
+ final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
- personSingletonA.setName(NAME);
- Assert.assertEquals(NAME, personSingletonB.getName());
+ personSingletonA.setName(NAME);
+ Assert.assertEquals(NAME, personSingletonB.getName());
- ((AbstractApplicationContext) applicationContext).close();
- }
+ ((AbstractApplicationContext) applicationContext).close();
+ }
- @Test
- public void testScopePrototype() {
- final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
+ @Test
+ public void testScopePrototype() {
+ final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
- final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
- final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
+ final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
+ final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
- personPrototypeA.setName(NAME);
- personPrototypeB.setName(NAME_OTHER);
+ personPrototypeA.setName(NAME);
+ personPrototypeB.setName(NAME_OTHER);
- Assert.assertEquals(NAME, personPrototypeA.getName());
- Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
+ Assert.assertEquals(NAME, personPrototypeA.getName());
+ Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
- ((AbstractApplicationContext) applicationContext).close();
- }
+ ((AbstractApplicationContext) applicationContext).close();
+ }
}
diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java
index aa3acb113f..5162a067d7 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java
@@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
- .build();
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
- String result = this.mockMvc.perform(get("/test")
- .accept(MediaType.ALL))
- .andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
+ String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assert.assertEquals("login = john, query = invoices", result);
}
diff --git a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java
index 04fabbc834..75d828c3d3 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java
@@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
- .build();
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
- this.mockMvc.perform(get("/appointments")
- .accept(MediaType.ALL))
- .andExpect(status().isOk());
+ this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
verify(appointmentService);
}
diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java
index 82caae15fe..3edf693a13 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java
@@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
-@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class})
+@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
@Autowired
diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java
index 946b19d00d..8a8cec3f86 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java
@@ -1,6 +1,5 @@
package org.baeldung.spring43.defaultmethods;
-
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
diff --git a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java
index b696760f68..ecf14f0d6c 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java
@@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
- .build();
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
MockHttpSession session = new MockHttpSession();
- String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request")
- .session(session)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
+ String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
- String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request")
- .session(session)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
+ String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
}
@@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
- String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session")
- .session(session1)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
- String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session")
- .session(session1)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
- String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session")
- .session(session2)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
+ String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
+ String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
+ String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
@@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
- String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application")
- .session(session1)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
- String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application")
- .session(session2)
- .accept(MediaType.ALL)).andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getContentAsString();
+ String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
+ String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java
index 725a9b8406..18ff11a49c 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java
@@ -3,9 +3,9 @@ package com.baeldung.autowire.sample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
- public static void main(String[] args) {
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
- FooService fooService = ctx.getBean(FooService.class);
- fooService.doStuff();
- }
+ public static void main(String[] args) {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
+ FooService fooService = ctx.getBean(FooService.class);
+ fooService.doStuff();
+ }
}
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java
index fb704453fc..e67a376d25 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java
@@ -9,5 +9,5 @@ public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
-
+
}
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java
index 73966e9e43..57f93a53d7 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java
@@ -9,5 +9,5 @@ public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
-
+
}
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java
index eccea4351a..c55d93da11 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java
@@ -5,13 +5,13 @@ import org.springframework.stereotype.Component;
@Component
public class FooService {
-
+
@Autowired
@FormatterType("Foo")
private Formatter formatter;
-
- public String doStuff(){
+
+ public String doStuff() {
return formatter.format();
}
-
+
}
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java
index 83716d6e92..59d718050a 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java
@@ -2,6 +2,6 @@ package com.baeldung.autowire.sample;
public interface Formatter {
- String format();
+ String format();
}
diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java
index 7ffc308c9a..f2961745b5 100644
--- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java
+++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java
@@ -8,10 +8,10 @@ import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier
-@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER})
+@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface FormatterType {
-
+
String value();
}
diff --git a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java
index 4607f527d9..50e89fcc55 100644
--- a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java
+++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java
@@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FooServiceTest {
-
+
@Autowired
FooService fooService;
-
+
@Test
- public void whenFooFormatterType_thenReturnFoo(){
+ public void whenFooFormatterType_thenReturnFoo() {
Assert.assertEquals("foo", fooService.doStuff());
}
}
diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml
index 5a20ff5602..5281b9b2c0 100644
--- a/spring-boot/pom.xml
+++ b/spring-boot/pom.xml
@@ -88,12 +88,12 @@
org.webjarsbootstrap
- 3.3.4
+ 3.3.7-1org.webjarsjquery
- 2.1.4
+ 3.1.1
diff --git a/spring-boot/src/main/java/com/baeldung/TestController.java b/spring-boot/src/main/java/com/baeldung/TestController.java
index 19a1c18c6b..0e28ca67f8 100644
--- a/spring-boot/src/main/java/com/baeldung/TestController.java
+++ b/spring-boot/src/main/java/com/baeldung/TestController.java
@@ -6,10 +6,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
-
- @RequestMapping(value="/")
- public String welcome(Model model){
- return "index";
- }
+
+ @RequestMapping(value = "/")
+ public String welcome(Model model) {
+ return "index";
+ }
}
diff --git a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java
index c14dc682af..35490131c6 100644
--- a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java
+++ b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java
@@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebjarsdemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(WebjarsdemoApplication.class, args);
- }
+ public static void main(String[] args) {
+ SpringApplication.run(WebjarsdemoApplication.class, args);
+ }
}
diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java
index 95abbf894c..cd696eae70 100644
--- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java
+++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
-@SpringBootApplication(scanBasePackages = { "com.baeldung.git"})
+@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
public class CommitIdApplication {
public static void main(String[] args) {
SpringApplication.run(CommitIdApplication.class, args);
@@ -21,6 +21,3 @@ public class CommitIdApplication {
return c;
}
}
-
-
-
diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java
index 1da2bd2989..6d44e02ec2 100644
--- a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java
+++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java
@@ -22,7 +22,7 @@ public class CommitInfoController {
@RequestMapping("/commitId")
public Map getCommitId() {
Map result = new HashMap<>();
- result.put("Commit message",commitMessage);
+ result.put("Commit message", commitMessage);
result.put("Commit branch", branch);
result.put("Commit id", commitId);
return result;
diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html
index 046d21600a..2c4387ed10 100644
--- a/spring-boot/src/main/resources/templates/index.html
+++ b/spring-boot/src/main/resources/templates/index.html
@@ -1,19 +1,19 @@
WebJars Demo
-
+