+ Your shopping cart is holding
+ <% if (order.getItems().size() == 1) { %>
+ 1 item.
+ <% } else { %>
+ <%= (order.getItems().size()) %> items.
+ <% } %>
+ Checkout
+
+ <% } %>
+<% } %>
diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp
new file mode 100644
index 0000000000..5f71d2e54e
--- /dev/null
+++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp
@@ -0,0 +1,29 @@
+<%@ page import="com.baeldung.patterns.intercepting.filter.data.Book" %>
+<%@ page import="com.baeldung.patterns.intercepting.filter.data.Order" %>
+<%@ page import="java.util.Map" %>
+
+
+
+ boolean add(E book);
-
- Book findByTitle(String title);
-}
diff --git a/play-framework/student-api/.gitignore b/play-framework/introduction/.gitignore
similarity index 100%
rename from play-framework/student-api/.gitignore
rename to play-framework/introduction/.gitignore
diff --git a/play-framework/student-api/LICENSE b/play-framework/introduction/LICENSE
similarity index 100%
rename from play-framework/student-api/LICENSE
rename to play-framework/introduction/LICENSE
diff --git a/play-framework/student-api/README b/play-framework/introduction/README
similarity index 100%
rename from play-framework/student-api/README
rename to play-framework/introduction/README
diff --git a/play-framework/student-api/app/Filters.java b/play-framework/introduction/app/Filters.java
similarity index 100%
rename from play-framework/student-api/app/Filters.java
rename to play-framework/introduction/app/Filters.java
diff --git a/play-framework/student-api/app/Module.java b/play-framework/introduction/app/Module.java
similarity index 100%
rename from play-framework/student-api/app/Module.java
rename to play-framework/introduction/app/Module.java
diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/introduction/app/controllers/AsyncController.java
similarity index 73%
rename from play-framework/student-api/app/controllers/AsyncController.java
rename to play-framework/introduction/app/controllers/AsyncController.java
index 33cd112837..92c84bb755 100644
--- a/play-framework/student-api/app/controllers/AsyncController.java
+++ b/play-framework/introduction/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/CountController.java b/play-framework/introduction/app/controllers/CountController.java
similarity index 100%
rename from play-framework/student-api/app/controllers/CountController.java
rename to play-framework/introduction/app/controllers/CountController.java
diff --git a/play-framework/student-api/app/controllers/HomeController.java b/play-framework/introduction/app/controllers/HomeController.java
similarity index 100%
rename from play-framework/student-api/app/controllers/HomeController.java
rename to play-framework/introduction/app/controllers/HomeController.java
diff --git a/play-framework/introduction/app/controllers/StudentController.java b/play-framework/introduction/app/controllers/StudentController.java
new file mode 100644
index 0000000000..8b759b9598
--- /dev/null
+++ b/play-framework/introduction/app/controllers/StudentController.java
@@ -0,0 +1,63 @@
+package controllers;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+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(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(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) {
+ 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/filters/ExampleFilter.java b/play-framework/introduction/app/filters/ExampleFilter.java
similarity index 100%
rename from play-framework/student-api/app/filters/ExampleFilter.java
rename to play-framework/introduction/app/filters/ExampleFilter.java
diff --git a/play-framework/student-api/app/models/Student.java b/play-framework/introduction/app/models/Student.java
similarity index 100%
rename from play-framework/student-api/app/models/Student.java
rename to play-framework/introduction/app/models/Student.java
diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/introduction/app/models/StudentStore.java
similarity index 60%
rename from play-framework/student-api/app/models/StudentStore.java
rename to play-framework/introduction/app/models/StudentStore.java
index 3290e141cd..add6a5dbd6 100644
--- a/play-framework/student-api/app/models/StudentStore.java
+++ b/play-framework/introduction/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/services/ApplicationTimer.java b/play-framework/introduction/app/services/ApplicationTimer.java
similarity index 100%
rename from play-framework/student-api/app/services/ApplicationTimer.java
rename to play-framework/introduction/app/services/ApplicationTimer.java
diff --git a/play-framework/student-api/app/services/AtomicCounter.java b/play-framework/introduction/app/services/AtomicCounter.java
similarity index 100%
rename from play-framework/student-api/app/services/AtomicCounter.java
rename to play-framework/introduction/app/services/AtomicCounter.java
diff --git a/play-framework/student-api/app/services/Counter.java b/play-framework/introduction/app/services/Counter.java
similarity index 100%
rename from play-framework/student-api/app/services/Counter.java
rename to play-framework/introduction/app/services/Counter.java
diff --git a/play-framework/introduction/app/util/Util.java b/play-framework/introduction/app/util/Util.java
new file mode 100644
index 0000000000..a853a4cb43
--- /dev/null
+++ b/play-framework/introduction/app/util/Util.java
@@ -0,0 +1,17 @@
+package util;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import play.libs.Json;
+
+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;
+ }
+}
\ No newline at end of file
diff --git a/play-framework/student-api/app/views/index.scala.html b/play-framework/introduction/app/views/index.scala.html
similarity index 100%
rename from play-framework/student-api/app/views/index.scala.html
rename to play-framework/introduction/app/views/index.scala.html
diff --git a/play-framework/student-api/app/views/main.scala.html b/play-framework/introduction/app/views/main.scala.html
similarity index 100%
rename from play-framework/student-api/app/views/main.scala.html
rename to play-framework/introduction/app/views/main.scala.html
diff --git a/play-framework/student-api/bin/activator b/play-framework/introduction/bin/activator
similarity index 100%
rename from play-framework/student-api/bin/activator
rename to play-framework/introduction/bin/activator
diff --git a/play-framework/student-api/bin/activator.bat b/play-framework/introduction/bin/activator.bat
similarity index 100%
rename from play-framework/student-api/bin/activator.bat
rename to play-framework/introduction/bin/activator.bat
diff --git a/play-framework/student-api/build.sbt b/play-framework/introduction/build.sbt
similarity index 100%
rename from play-framework/student-api/build.sbt
rename to play-framework/introduction/build.sbt
diff --git a/play-framework/student-api/conf/application.conf b/play-framework/introduction/conf/application.conf
similarity index 100%
rename from play-framework/student-api/conf/application.conf
rename to play-framework/introduction/conf/application.conf
diff --git a/play-framework/student-api/conf/logback.xml b/play-framework/introduction/conf/logback.xml
similarity index 100%
rename from play-framework/student-api/conf/logback.xml
rename to play-framework/introduction/conf/logback.xml
diff --git a/play-framework/student-api/conf/routes b/play-framework/introduction/conf/routes
similarity index 100%
rename from play-framework/student-api/conf/routes
rename to play-framework/introduction/conf/routes
diff --git a/play-framework/student-api/libexec/activator-launch-1.3.10.jar b/play-framework/introduction/libexec/activator-launch-1.3.10.jar
similarity index 100%
rename from play-framework/student-api/libexec/activator-launch-1.3.10.jar
rename to play-framework/introduction/libexec/activator-launch-1.3.10.jar
diff --git a/play-framework/student-api/project/build.properties b/play-framework/introduction/project/build.properties
similarity index 100%
rename from play-framework/student-api/project/build.properties
rename to play-framework/introduction/project/build.properties
diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/introduction/project/plugins.sbt
similarity index 100%
rename from play-framework/student-api/project/plugins.sbt
rename to play-framework/introduction/project/plugins.sbt
diff --git a/play-framework/student-api/public/images/favicon.png b/play-framework/introduction/public/images/favicon.png
similarity index 100%
rename from play-framework/student-api/public/images/favicon.png
rename to play-framework/introduction/public/images/favicon.png
diff --git a/play-framework/student-api/public/javascripts/hello.js b/play-framework/introduction/public/javascripts/hello.js
similarity index 100%
rename from play-framework/student-api/public/javascripts/hello.js
rename to play-framework/introduction/public/javascripts/hello.js
diff --git a/play-framework/student-api/public/stylesheets/main.css b/play-framework/introduction/public/stylesheets/main.css
similarity index 100%
rename from play-framework/student-api/public/stylesheets/main.css
rename to play-framework/introduction/public/stylesheets/main.css
diff --git a/play-framework/introduction/test/ApplicationTest.java b/play-framework/introduction/test/ApplicationTest.java
new file mode 100644
index 0000000000..1133978e9a
--- /dev/null
+++ b/play-framework/introduction/test/ApplicationTest.java
@@ -0,0 +1,172 @@
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+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 static play.test.Helpers.*;
+
+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/play-framework/routing-in-play/.gitignore b/play-framework/routing-in-play/.gitignore
new file mode 100644
index 0000000000..eb372fc719
--- /dev/null
+++ b/play-framework/routing-in-play/.gitignore
@@ -0,0 +1,8 @@
+logs
+target
+/.idea
+/.idea_modules
+/.classpath
+/.project
+/.settings
+/RUNNING_PID
diff --git a/play-framework/routing-in-play/LICENSE b/play-framework/routing-in-play/LICENSE
new file mode 100644
index 0000000000..4baedcb95f
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/README b/play-framework/routing-in-play/README
new file mode 100644
index 0000000000..f21d092edf
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/Filters.java b/play-framework/routing-in-play/app/Filters.java
new file mode 100644
index 0000000000..255de8ca93
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/Module.java b/play-framework/routing-in-play/app/Module.java
new file mode 100644
index 0000000000..6e7d1766ef
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/controllers/HomeController.java b/play-framework/routing-in-play/app/controllers/HomeController.java
new file mode 100644
index 0000000000..6e340d594f
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/filters/ExampleFilter.java b/play-framework/routing-in-play/app/filters/ExampleFilter.java
new file mode 100644
index 0000000000..67a6a36cc3
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/services/ApplicationTimer.java b/play-framework/routing-in-play/app/services/ApplicationTimer.java
new file mode 100644
index 0000000000..a951562b1d
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/services/AtomicCounter.java b/play-framework/routing-in-play/app/services/AtomicCounter.java
new file mode 100644
index 0000000000..41f741cbf7
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/services/Counter.java b/play-framework/routing-in-play/app/services/Counter.java
new file mode 100644
index 0000000000..dadad8b09d
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/views/index.scala.html b/play-framework/routing-in-play/app/views/index.scala.html
new file mode 100644
index 0000000000..4539f5a10b
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/app/views/main.scala.html b/play-framework/routing-in-play/app/views/main.scala.html
new file mode 100644
index 0000000000..9414f4be6e
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/bin/activator b/play-framework/routing-in-play/bin/activator
new file mode 100644
index 0000000000..a8b11d482f
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/build.sbt b/play-framework/routing-in-play/build.sbt
new file mode 100644
index 0000000000..083d071676
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/conf/application.conf b/play-framework/routing-in-play/conf/application.conf
new file mode 100644
index 0000000000..489d3f9b3e
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/conf/logback.xml b/play-framework/routing-in-play/conf/logback.xml
new file mode 100644
index 0000000000..86ec12c0af
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/conf/routes b/play-framework/routing-in-play/conf/routes
new file mode 100644
index 0000000000..f72d8a1a14
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar b/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar
new file mode 100644
index 0000000000..69050e7dec
Binary files /dev/null and b/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar differ
diff --git a/play-framework/routing-in-play/project/build.properties b/play-framework/routing-in-play/project/build.properties
new file mode 100644
index 0000000000..6d22e3f2d1
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/project/plugins.sbt b/play-framework/routing-in-play/project/plugins.sbt
new file mode 100644
index 0000000000..e8e7f602f7
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/public/images/favicon.png b/play-framework/routing-in-play/public/images/favicon.png
new file mode 100644
index 0000000000..c7d92d2ae4
Binary files /dev/null and b/play-framework/routing-in-play/public/images/favicon.png differ
diff --git a/play-framework/routing-in-play/public/javascripts/hello.js b/play-framework/routing-in-play/public/javascripts/hello.js
new file mode 100644
index 0000000000..02ee13c7ca
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/public/stylesheets/main.css
similarity index 100%
rename from couchbase-sdk-spring-service/src/main/resources/application.properties
rename to play-framework/routing-in-play/public/stylesheets/main.css
diff --git a/play-framework/routing-in-play/test/ApplicationTest.java b/play-framework/routing-in-play/test/ApplicationTest.java
new file mode 100644
index 0000000000..3d7c4875aa
--- /dev/null
+++ b/play-framework/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/play-framework/routing-in-play/test/IntegrationTest.java
similarity index 100%
rename from play-framework/student-api/test/IntegrationTest.java
rename to play-framework/routing-in-play/test/IntegrationTest.java
diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java
deleted file mode 100644
index 0adedfa432..0000000000
--- a/play-framework/student-api/app/controllers/StudentController.java
+++ /dev/null
@@ -1,56 +0,0 @@
-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.ObjectMapper;
-import java.util.List;
-
-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));
- }
- 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 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));
- }
-
-}
diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/student-api/app/util/Util.java
deleted file mode 100644
index 3718b50677..0000000000
--- a/play-framework/student-api/app/util/Util.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package util;
-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);
-
- 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 b4158ef67e..95182ab63c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -17,25 +17,23 @@
assertj
apache-cxf
- autovalue-tutorial
-
+ autovalue
+
cdi
core-java
- core-java-8
+ couchbase-sdk
- couchbase-sdk-intro
- couchbase-sdk-spring-service
dozer
- dependency-injection
deltaspike
patterns
- feign-client
+ feign
+ flyway
+
gson
- gson-jackson-performance
guava
guava18
guava19
@@ -48,19 +46,19 @@
jackson
javaxval
jjwt
- jooq-spring
+
jpa-storedprocedure
json
json-path
junit5
- jee7schedule
+ jee7
log4j
mockito
mocks
- mutation-testing
+ testing
orika
@@ -77,26 +75,29 @@
spring-autowire
spring-batch
spring-boot
+ spring-core
spring-cucumber
spring-data-cassandra
spring-data-couchbase-2
- spring-data-couchbase-2b
spring-data-elasticsearch
spring-data-neo4j
spring-data-mongodb
spring-data-redis
spring-data-rest
+
spring-exceptions
spring-freemarker
spring-hibernate3
spring-hibernate4
+ spring-jms
+ spring-jooq
spring-jpa
spring-katharsis
spring-mockito
spring-mvc-java
spring-mvc-no-xml
spring-mvc-xml
- spring-mvc-tiles
+ spring-mvc-tiles
spring-openid
spring-protobuf
spring-quartz
@@ -127,6 +128,7 @@
jsf
xml
+ xmlunit2
lombok
redis
diff --git a/querydsl/README.md b/querydsl/README.md
new file mode 100644
index 0000000000..ef9f8f894c
--- /dev/null
+++ b/querydsl/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl)
diff --git a/querydsl/pom.xml b/querydsl/pom.xml
index bed0cf90e5..13528526ea 100644
--- a/querydsl/pom.xml
+++ b/querydsl/pom.xml
@@ -20,6 +20,7 @@
5.2.1.Final
4.1.3
1.7.21
+ 2.19.1
@@ -166,7 +167,55 @@
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java
similarity index 98%
rename from querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java
rename to querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java
index 0e5996a8c8..a666aea8da 100644
--- a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java
+++ b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java
@@ -17,7 +17,7 @@ import junit.framework.Assert;
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(defaultRollback = true)
-public class PersonDaoTest {
+public class PersonDaoIntegrationTest {
@Autowired
private PersonDao personDao;
diff --git a/raml/resource-types-and-traits/README.md b/raml/resource-types-and-traits/README.md
new file mode 100644
index 0000000000..72e7b454d6
--- /dev/null
+++ b/raml/resource-types-and-traits/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Eliminate Redundancies in RAML with Resource Types and Traits](http://www.baeldung.com/simple-raml-with-resource-types-and-traits)
diff --git a/redis/src/test/java/com/baeldung/JedisTest.java b/redis/src/test/java/com/baeldung/JedisTest.java
index 766fd7b5e9..582bb266aa 100644
--- a/redis/src/test/java/com/baeldung/JedisTest.java
+++ b/redis/src/test/java/com/baeldung/JedisTest.java
@@ -1,28 +1,15 @@
package com.baeldung;
+import org.junit.*;
+import redis.clients.jedis.*;
+import redis.embedded.RedisServer;
+
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import redis.clients.jedis.Jedis;
-import redis.clients.jedis.JedisPool;
-import redis.clients.jedis.JedisPoolConfig;
-import redis.clients.jedis.Pipeline;
-import redis.clients.jedis.Response;
-import redis.clients.jedis.Transaction;
-import redis.embedded.RedisServer;
-
-/**
- * Unit test for Redis Java library - Jedis.
- */
public class JedisTest {
private Jedis jedis;
@@ -140,9 +127,9 @@ public class JedisTest {
scores.put("PlayerTwo", 1500.0);
scores.put("PlayerThree", 8200.0);
- for (String player : scores.keySet()) {
+ scores.keySet().forEach(player -> {
jedis.zadd(key, scores.get(player), player);
- }
+ });
Set players = jedis.zrevrange(key, 0, 1);
Assert.assertEquals("PlayerThree", players.iterator().next());
diff --git a/rest-assured/README.md b/rest-assured/README.md
index e69de29bb2..50f36f61eb 100644
--- a/rest-assured/README.md
+++ b/rest-assured/README.md
@@ -0,0 +1,2 @@
+###Relevant Articles:
+- [A Guide to REST-assured](http://www.baeldung.com/rest-assured-tutorial)
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/README.md b/rest-testing/README.md
index 54a2e98dda..5dd4e49162 100644
--- a/rest-testing/README.md
+++ b/rest-testing/README.md
@@ -7,3 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/)
+- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock)
+- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing)
diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml
index 652f2ab601..90c160af15 100644
--- a/rest-testing/pom.xml
+++ b/rest-testing/pom.xml
@@ -148,15 +148,57 @@
org.apache.maven.plugins
maven-surefire-plugin
${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*UnitTest.java
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
- 2.7.2
+ 2.7.8
1.7.13
diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java
similarity index 84%
rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java
rename to rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java
index 041de592e9..f80178a43d 100644
--- a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java
+++ b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java
@@ -6,5 +6,5 @@ import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:Feature")
-public class CucumberTest {
+public class CucumberIntegrationTest {
}
\ No newline at end of file
diff --git a/resteasy/pom.xml b/resteasy/pom.xml
index ec9e87b0d1..04e8576e1f 100644
--- a/resteasy/pom.xml
+++ b/resteasy/pom.xml
@@ -10,6 +10,8 @@
3.0.14.Final
+ 2.19.1
+ 1.6.0
@@ -23,6 +25,35 @@
1.8
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+ true
+
+ jetty8x
+ embedded
+
+
+
+ 8082
+
+
+
+
@@ -73,5 +104,66 @@
+
+
+ live
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*IntegrationTest.java
+
+
+ **/*LiveTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+ false
+
+
+
+ start-server
+ pre-integration-test
+
+ start
+
+
+
+ stop-server
+ post-integration-test
+
+ stop
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java
similarity index 61%
rename from resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java
rename to resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java
index ef18b0f23f..7e709edb96 100644
--- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java
+++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java
@@ -1,7 +1,15 @@
package com.baeldung.server;
-import com.baeldung.client.ServicesInterface;
-import com.baeldung.model.Movie;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.List;
+import java.util.Locale;
+
+import javax.naming.NamingException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+
import org.apache.commons.io.IOUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
@@ -14,18 +22,13 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.junit.Before;
import org.junit.Test;
-import javax.naming.NamingException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.text.SimpleDateFormat;
-import java.util.List;
-import java.util.Locale;
-public class RestEasyClientTest {
+import com.baeldung.client.ServicesInterface;
+import com.baeldung.model.Movie;
- public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest");
+public class RestEasyClientLiveTest {
+
+ public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest");
Movie transformerMovie = null;
Movie batmanMovie = null;
ObjectMapper jsonMapper = null;
@@ -35,22 +38,22 @@ public class RestEasyClientTest {
jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
- SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
+ final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
jsonMapper.setDateFormat(sdf);
- try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) {
- String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+ try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) {
+ final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Test is going to die ...", e);
}
- try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) {
- String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+ try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) {
+ final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new RuntimeException("Test is going to die ...", e);
}
}
@@ -58,41 +61,41 @@ public class RestEasyClientTest {
@Test
public void testListAllMovies() {
- ResteasyClient client = new ResteasyClientBuilder().build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final ResteasyClient client = new ResteasyClientBuilder().build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(transformerMovie);
moviesResponse.close();
moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
- List movies = proxy.listMovies();
+ final List movies = proxy.listMovies();
System.out.println(movies);
}
@Test
public void testMovieByImdbId() {
- String transformerImdbId = "tt0418279";
+ final String transformerImdbId = "tt0418279";
- ResteasyClient client = new ResteasyClientBuilder().build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final ResteasyClient client = new ResteasyClientBuilder().build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
- Response moviesResponse = proxy.addMovie(transformerMovie);
+ final Response moviesResponse = proxy.addMovie(transformerMovie);
moviesResponse.close();
- Movie movies = proxy.movieByImdbId(transformerImdbId);
+ final Movie movies = proxy.movieByImdbId(transformerImdbId);
System.out.println(movies);
}
@Test
public void testAddMovie() {
- ResteasyClient client = new ResteasyClientBuilder().build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final ResteasyClient client = new ResteasyClientBuilder().build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
@@ -109,17 +112,15 @@ public class RestEasyClientTest {
@Test
public void testAddMovieMultiConnection() {
- PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
- CloseableHttpClient httpClient = HttpClients.custom()
- .setConnectionManager(cm)
- .build();
- ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
- ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
+ final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
+ final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
+ final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
- Response batmanResponse = proxy.addMovie(batmanMovie);
- Response transformerResponse = proxy.addMovie(transformerMovie);
+ final Response batmanResponse = proxy.addMovie(batmanMovie);
+ final Response transformerResponse = proxy.addMovie(transformerMovie);
if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
@@ -132,16 +133,14 @@ public class RestEasyClientTest {
transformerResponse.close();
cm.close();
-
-
}
@Test
public void testDeleteMovie() {
- ResteasyClient client = new ResteasyClientBuilder().build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final ResteasyClient client = new ResteasyClientBuilder().build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
@@ -159,9 +158,9 @@ public class RestEasyClientTest {
@Test
public void testUpdateMovie() {
- ResteasyClient client = new ResteasyClientBuilder().build();
- ResteasyWebTarget target = client.target(FULL_PATH);
- ServicesInterface proxy = target.proxy(ServicesInterface.class);
+ final ResteasyClient client = new ResteasyClientBuilder().build();
+ final ResteasyWebTarget target = client.target(FULL_PATH);
+ final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml
index c6bd2b042c..861c0b1986 100644
--- a/selenium-junit-testng/pom.xml
+++ b/selenium-junit-testng/pom.xml
@@ -1,36 +1,69 @@
-
- 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
+
+ true
+
+ **/*UnitTest.java
+
+
+
+
+
+
+
+
+ live
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.19.1
+
+
+ **/*LiveTest.java
+
+
+
+
+
+
+
+
+
+
+ org.seleniumhq.selenium
+ selenium-java
+ 2.53.1
+
+
+ junit
+ junit
+ 4.12
+
+
+ org.testng
+ testng
+ 6.9.13.6
+
+
\ 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..ce60a1f638 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
@@ -1,16 +1,23 @@
package main.java.com.baeldung.selenium;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.concurrent.TimeUnit;
+
+import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
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.manage().window().maximize();
+ webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
webDriver.get(url);
}
@@ -18,12 +25,32 @@ public class SeleniumExample {
webDriver.close();
}
- public String getActualTitle() {
+ public String getTitle() {
return webDriver.getTitle();
}
- public String getExpectedTitle() {
- return expectedTitle;
+ public void getAboutBaeldungPage() throws Exception {
+ closeOverlay();
+ clickAboutLink();
+ clickAboutUsLink();
}
+ private void closeOverlay() throws Exception {
+ List webElementList = webDriver.findElements(By.tagName("a"));
+ if (webElementList != null && !webElementList.isEmpty() && webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().isPresent()) {
+ webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
+ }
+ }
+
+ private void clickAboutLink() {
+ webDriver.findElement(By.partialLinkText("About")).click();
+ }
+
+ private void clickAboutUsLink() {
+ webDriver.findElement(By.partialLinkText("About Baeldung.")).click();
+ }
+
+ public boolean isAuthorInformationAvailable() {
+ return webDriver.findElement(By.xpath("//*[contains(text(), 'Eugen an engineer')]")).isDisplayed();
+ }
}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java
new file mode 100644
index 0000000000..f8d9a5dada
--- /dev/null
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java
@@ -0,0 +1,41 @@
+package test.java.com.baeldung.selenium.junit;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import main.java.com.baeldung.selenium.SeleniumExample;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class SeleniumWithJUnitLiveTest {
+
+ private static SeleniumExample seleniumExample;
+ private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung";
+
+ @BeforeClass
+ public static void setUp() {
+ seleniumExample = new SeleniumExample();
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ seleniumExample.closeWindow();
+ }
+
+ @Test
+ public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
+ try {
+ seleniumExample.getAboutBaeldungPage();
+ String actualTitle = seleniumExample.getTitle();
+ assertNotNull(actualTitle);
+ assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
+ assertTrue(seleniumExample.isAuthorInformationAvailable());
+ } catch (Exception exception) {
+ exception.printStackTrace();
+ seleniumExample.closeWindow();
+ }
+ }
+
+}
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
deleted file mode 100644
index 371f730eb9..0000000000
--- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package test.java.com.baeldung.selenium.junit;
-
-import static org.testng.Assert.assertEquals;
-import main.java.com.baeldung.selenium.SeleniumExample;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class TestSeleniumWithJUnit {
-
- private SeleniumExample seleniumExample;
-
- @Before
- public void setUp() {
- seleniumExample = new SeleniumExample();
- }
-
- @After
- public void tearDown() {
- seleniumExample.closeWindow();
- }
-
- @Test
- public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String expectedTitle = seleniumExample.getExpectedTitle();
- String actualTitle = seleniumExample.getActualTitle();
- assertEquals(actualTitle, expectedTitle);
- }
-}
diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java
new file mode 100644
index 0000000000..5ec9ade39f
--- /dev/null
+++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java
@@ -0,0 +1,40 @@
+package test.java.com.baeldung.selenium.testng;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import main.java.com.baeldung.selenium.SeleniumExample;
+
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.BeforeSuite;
+import org.testng.annotations.Test;
+
+public class SeleniumWithTestNGLiveTest {
+
+ private SeleniumExample seleniumExample;
+ private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung";
+
+ @BeforeSuite
+ public void setUp() {
+ seleniumExample = new SeleniumExample();
+ }
+
+ @AfterSuite
+ public void tearDown() {
+ seleniumExample.closeWindow();
+ }
+
+ @Test
+ public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
+ try {
+ seleniumExample.getAboutBaeldungPage();
+ String actualTitle = seleniumExample.getTitle();
+ assertNotNull(actualTitle);
+ assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
+ assertTrue(seleniumExample.isAuthorInformationAvailable());
+ } catch (Exception exception) {
+ exception.printStackTrace();
+ seleniumExample.closeWindow();
+ }
+ }
+}
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
deleted file mode 100644
index ec10f9ca82..0000000000
--- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package test.java.com.baeldung.selenium.testng;
-
-import static org.testng.Assert.assertEquals;
-import main.java.com.baeldung.selenium.SeleniumExample;
-
-import org.testng.annotations.AfterSuite;
-import org.testng.annotations.BeforeSuite;
-import org.testng.annotations.Test;
-
-public class TestSeleniumWithTestNG {
-
- private SeleniumExample seleniumExample;
-
- @BeforeSuite
- public void setUp() {
- seleniumExample = new SeleniumExample();
- }
-
- @AfterSuite
- public void tearDown() {
- seleniumExample.closeWindow();
- }
-
- @Test
- public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
- String expectedTitle = seleniumExample.getExpectedTitle();
- String actualTitle = seleniumExample.getActualTitle();
- 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/sockets/pom.xml b/sockets/pom.xml
deleted file mode 100644
index 24e8e436f3..0000000000
--- a/sockets/pom.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
- 4.0.0
- com.baeldung
- sockets
- 1.0
- sockets
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
- 8
- 8
-
-
-
-
-
-
- junit
- junit
- 4.3
- test
-
-
-
-
diff --git a/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/sockets/src/main/java/com/baeldung/socket/EchoClient.java
deleted file mode 100644
index e8ec97c80a..0000000000
--- a/sockets/src/main/java/com/baeldung/socket/EchoClient.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package com.baeldung.socket;
-
-import java.io.*;
-import java.net.*;
-
-public class EchoClient {
- private Socket clientSocket;
- private PrintWriter out;
- private BufferedReader in;
-
- public void startConnection(String ip, int port) {
- try {
- clientSocket = new Socket(ip, port);
- out = new PrintWriter(clientSocket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(
- clientSocket.getInputStream()));
- } catch (IOException e) {
- System.out.print(e);
- }
-
- }
-
- public String sendMessage(String msg) {
- try {
- out.println(msg);
- String resp = in.readLine();
- return resp;
- } catch (Exception e) {
- return null;
- }
- }
-
- public void stopConnection() {
- try {
- in.close();
- out.close();
- clientSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-}
diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java
deleted file mode 100644
index 2ece1ceebe..0000000000
--- a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.baeldung.socket;
-
-import java.net.*;
-import java.io.*;
-
-public class EchoMultiServer {
- private ServerSocket serverSocket;
-
- public void start(int port) {
- try {
- serverSocket = new ServerSocket(port);
- while (true)
- new EchoClientHandler(serverSocket.accept()).run();
-
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- stop();
- }
-
- }
-
- public void stop() {
- try {
-
- serverSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- private static class EchoClientHandler extends Thread {
- private Socket clientSocket;
- private PrintWriter out;
- private BufferedReader in;
-
- public EchoClientHandler(Socket socket) {
- this.clientSocket = socket;
- }
-
- public void run() {
- try {
- out = new PrintWriter(clientSocket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(
- clientSocket.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- if (".".equals(inputLine)) {
- out.println("bye");
- break;
- }
- out.println(inputLine);
- }
-
- in.close();
- out.close();
- clientSocket.close();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public static void main(String[] args) {
- EchoMultiServer server = new EchoMultiServer();
- server.start(5555);
- }
-
-}
diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/sockets/src/main/java/com/baeldung/socket/EchoServer.java
deleted file mode 100644
index 3607afa7f5..0000000000
--- a/sockets/src/main/java/com/baeldung/socket/EchoServer.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.baeldung.socket;
-
-import java.net.*;
-import java.io.*;
-
-public class EchoServer {
- private ServerSocket serverSocket;
- private Socket clientSocket;
- private PrintWriter out;
- private BufferedReader in;
-
- public void start(int port) {
- try {
- serverSocket = new ServerSocket(port);
- clientSocket = serverSocket.accept();
- out = new PrintWriter(clientSocket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(
- clientSocket.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- if (".".equals(inputLine)) {
- out.println("good bye");
- break;
- }
- out.println(inputLine);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- public void stop() {
- try {
- in.close();
- out.close();
- clientSocket.close();
- serverSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- public static void main(String[] args) {
- EchoServer server = new EchoServer();
- server.start(4444);
- }
-
-}
diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/sockets/src/main/java/com/baeldung/socket/GreetClient.java
deleted file mode 100644
index 7252827c87..0000000000
--- a/sockets/src/main/java/com/baeldung/socket/GreetClient.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.socket;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.net.Socket;
-
-public class GreetClient {
- private Socket clientSocket;
- private PrintWriter out;
- private BufferedReader in;
-
- public void startConnection(String ip, int port) {
- try {
- clientSocket = new Socket(ip, port);
- out = new PrintWriter(clientSocket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(
- clientSocket.getInputStream()));
- } catch (IOException e) {
-
- }
-
- }
-
- public String sendMessage(String msg) {
- try {
- out.println(msg);
- String resp = in.readLine();
- return resp;
- } catch (Exception e) {
- return null;
- }
- }
-
- public void stopConnection() {
- try {
- in.close();
- out.close();
- clientSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/sockets/src/main/java/com/baeldung/socket/GreetServer.java
deleted file mode 100644
index 8bf675c7b9..0000000000
--- a/sockets/src/main/java/com/baeldung/socket/GreetServer.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.baeldung.socket;
-
-import java.net.*;
-import java.io.*;
-
-public class GreetServer {
- private ServerSocket serverSocket;
- private Socket clientSocket;
- private PrintWriter out;
- private BufferedReader in;
-
-
- public void start(int port) {
- try {
- serverSocket = new ServerSocket(port);
- clientSocket = serverSocket.accept();
- out = new PrintWriter(clientSocket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(
- clientSocket.getInputStream()));
- String greeting = in.readLine();
- if ("hello server".equals(greeting))
- out.println("hello client");
- else
- out.println("unrecognised greeting");
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- public void stop() {
- try {
- in.close();
- out.close();
- clientSocket.close();
- serverSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
- public static void main(String[] args) {
- GreetServer server=new GreetServer();
- server.start(6666);
- }
-
-}
diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java
deleted file mode 100644
index 19a59c211c..0000000000
--- a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.baeldung.socket;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.concurrent.Executors;
-
-import static org.junit.Assert.assertEquals;
-
-public class EchoMultiTest {
-
- {
- Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555));
- }
-
-
- @Test
- public void givenClient1_whenServerResponds_thenCorrect() {
- EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", 5555);
- String msg1 = client.sendMessage("hello");
- String msg2 = client.sendMessage("world");
- String terminate = client.sendMessage(".");
- assertEquals(msg1, "hello");
- assertEquals(msg2, "world");
- assertEquals(terminate, "bye");
- client.stopConnection();
- }
-
- @Test
- public void givenClient2_whenServerResponds_thenCorrect() {
- EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", 5555);
- String msg1 = client.sendMessage("hello");
- String msg2 = client.sendMessage("world");
- String terminate = client.sendMessage(".");
- assertEquals(msg1, "hello");
- assertEquals(msg2, "world");
- assertEquals(terminate, "bye");
- client.stopConnection();
- }
-
- @Test
- public void givenClient3_whenServerResponds_thenCorrect() {
- EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", 5555);
- String msg1 = client.sendMessage("hello");
- String msg2 = client.sendMessage("world");
- String terminate = client.sendMessage(".");
- assertEquals(msg1, "hello");
- assertEquals(msg2, "world");
- assertEquals(terminate, "bye");
- client.stopConnection();
- }
-
-}
diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/sockets/src/test/java/com/baeldung/socket/EchoTest.java
deleted file mode 100644
index 0f0c02e4d8..0000000000
--- a/sockets/src/test/java/com/baeldung/socket/EchoTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.baeldung.socket;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.concurrent.Executors;
-
-import static org.junit.Assert.assertEquals;
-
-public class EchoTest {
- {
- Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444));
- }
-
- EchoClient client = new EchoClient();
-
- @Before
- public void init() {
- client.startConnection("127.0.0.1", 4444);
- }
-
- @Test
- public void givenClient_whenServerEchosMessage_thenCorrect() {
-
- String resp1 = client.sendMessage("hello");
- String resp2 = client.sendMessage("world");
- String resp3 = client.sendMessage("!");
- String resp4 = client.sendMessage(".");
- assertEquals("hello", resp1);
- assertEquals("world", resp2);
- assertEquals("!", resp3);
- assertEquals("good bye", resp4);
- }
-
- @After
- public void tearDown() {
- client.stopConnection();
- }
-
-}
diff --git a/spring-akka/README.md b/spring-akka/README.md
new file mode 100644
index 0000000000..0f1c013214
--- /dev/null
+++ b/spring-akka/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Introduction to Spring with Akka](http://www.baeldung.com/akka-with-spring)
diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml
index 6299448ec8..eb33ca4848 100644
--- a/spring-akka/pom.xml
+++ b/spring-akka/pom.xml
@@ -65,9 +65,54 @@
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
-
-
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
4.3.2.RELEASE
@@ -75,6 +120,8 @@
4.12
3.5.1
+ 2.19.1
+
\ No newline at end of file
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
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
-
+
-
-
- 4.3.1.RELEASE
- 4.0.4.RELEASE
- 3.20.0-GA
- 1.2
+
-
- 4.3.11.Final
- 5.1.38
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+
+
+ 4.3.1.RELEASE
+ 4.0.4.RELEASE
+ 3.20.0-GA
+ 1.2
-
- 1.7.13
- 1.1.3
+
+ 4.3.11.Final
+ 5.1.38
-
- 5.2.2.Final
+
+ 1.7.13
+ 1.1.3
-
- 19.0
- 3.4
+
+ 5.2.2.Final
-
- 1.3
- 4.12
- 1.10.19
+
+ 19.0
+ 3.4
- 4.4.1
- 4.5
+
+ 1.3
+ 4.12
+ 1.10.19
- 2.9.0
+ 4.4.1
+ 4.5
-
- 3.5.1
- 2.6
- 2.19.1
- 2.7
- 1.4.18
+ 2.9.0
-
+
+ 3.5.1
+ 2.6
+ 2.19.1
+ 2.7
+ 1.4.18
+
+
\ No newline at end of file
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/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..7f59ad8cfb
--- /dev/null
+++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java
@@ -0,0 +1,29 @@
+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().build();
+ cacheManager.init();
+
+ squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10)));
+ }
+
+ public Cache getSquareNumberCache() {
+ return squareNumberCache;
+ }
+
+ public Cache getSquareNumberCacheFromCacheManager() {
+ return cacheManager.getCache("squaredNumber", Integer.class, Integer.class);
+ }
+
+}
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/async/AsyncAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java
similarity index 97%
rename from spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java
rename to spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java
index 2f41766cb6..0c010cf732 100644
--- a/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java
+++ b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java
@@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class AsyncAnnotationExampleTest {
+public class AsyncAnnotationExampleIntegrationTest {
@Autowired
private AsyncComponent asyncAnnotationExample;
diff --git a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java
similarity index 95%
rename from spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java
rename to spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java
index b91666261c..ffaa653a9a 100644
--- a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java
+++ b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java
@@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springAsync-config.xml")
-public class AsyncWithXMLTest {
+public class AsyncWithXMLIntegrationTest {
@Autowired
private AsyncComponent asyncAnnotationExample;
diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java
similarity index 80%
rename from spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java
rename to spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java
index 44f1767405..82c8704360 100644
--- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.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 )
-public class ControllerAnnotationTest {
-
- private MockMvc mockMvc;
+@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
+public class ControllerAnnotationIntegrationTest {
+
+ 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/ControllerIntegrationTest.java
similarity index 85%
rename from spring-all/src/test/java/org/baeldung/controller/ControllerTest.java
rename to spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java
index f5e41cd5a2..8e8a021530 100644
--- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java
+++ b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java
@@ -19,8 +19,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
-@ContextConfiguration({"classpath:test-mvc.xml"})
-public class ControllerTest {
+@ContextConfiguration({ "classpath:test-mvc.xml" })
+public class ControllerIntegrationTest {
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/customannotation/DataAccessAnnotationTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
similarity index 97%
rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java
rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
index ec0d46876e..ae3d53fb9b 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
@@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
-public class DataAccessAnnotationTest {
+public class DataAccessAnnotationIntegrationTest {
@DataAccess(entity = Person.class)
private GenericDAO personGenericDAO;
diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
similarity index 97%
rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
index e47d03c961..bab2574cd2 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
@@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
-public class DataAccessFieldCallbackTest {
+public class DataAccessFieldCallbackIntegrationTest {
@Autowired
private ConfigurableListableBeanFactory configurableListableBeanFactory;
diff --git a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java
new file mode 100644
index 0000000000..ab7aebf7a1
--- /dev/null
+++ b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java
@@ -0,0 +1,43 @@
+package org.baeldung.ehcache;
+
+import org.baeldung.ehcache.calculator.SquaredCalculator;
+import org.baeldung.ehcache.config.CacheHelper;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class SquareCalculatorTest {
+ private SquaredCalculator squaredCalculator = new SquaredCalculator();
+ private CacheHelper cacheHelper = new CacheHelper();
+
+ @Before
+ public void setup() {
+ squaredCalculator.setCache(cacheHelper);
+ }
+
+ @Test
+ public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() {
+ for (int i = 10; i < 15; i++) {
+ assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
+ System.out.println("Square value of " + i + " is: "
+ + squaredCalculator.getSquareValueOfNumber(i) + "\n");
+ }
+ }
+
+ @Test
+ public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() {
+ for (int i = 10; i < 15; i++) {
+ assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
+ System.out.println("Square value of " + i + " is: "
+ + squaredCalculator.getSquareValueOfNumber(i) + "\n");
+ }
+
+ for (int i = 10; i < 15; i++) {
+ assertTrue(cacheHelper.getSquareNumberCache().containsKey(i));
+ System.out.println("Square value of " + i + " is: "
+ + squaredCalculator.getSquareValueOfNumber(i) + "\n");
+ }
+ }
+}
diff --git a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
similarity index 99%
rename from spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java
rename to spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
index d544409254..4a92aa838f 100644
--- a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java
+++ b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
@@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class EmployeeDAOTest {
+public class EmployeeDAOIntegrationTest {
@Autowired
private EmployeeDAO employeeDao;
diff --git a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java
similarity index 93%
rename from spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java
rename to spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java
index 2b65928da8..cf5ca132e6 100644
--- a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java
@@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class DevProfileWithAnnotationTest {
+public class DevProfileWithAnnotationIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
diff --git a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java
similarity index 94%
rename from spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java
rename to spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java
index 551636bd31..5bacaef07b 100644
--- a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java
@@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("production")
@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class ProductionProfileWithAnnotationTest {
+public class ProductionProfileWithAnnotationIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java
similarity index 96%
rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java
rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java
index 92af3f52f0..e0eccc978a 100644
--- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java
+++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java
@@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfig2.class), @ContextConfiguration(classes = ChildConfig2.class) })
-public class ParentChildPropertyPlaceHolderPropertiesTest {
+public class ParentChildPropertyPlaceHolderPropertiesIntegrationTest {
@Autowired
private WebApplicationContext wac;
diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java
similarity index 96%
rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java
rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java
index 3ffd490c87..e9990523a7 100644
--- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java
+++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java
@@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class), @ContextConfiguration(classes = ChildConfig.class) })
-public class ParentChildPropertySourcePropertiesTest {
+public class ParentChildPropertySourcePropertiesIntegrationTest {
@Autowired
private WebApplicationContext wac;
diff --git a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java
similarity index 90%
rename from spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java
rename to spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java
index 9317c7bb7f..c5ca78aaa1 100644
--- a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java
+++ b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java
@@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringSchedulingConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class ScheduledAnnotationExampleTest {
+public class ScheduledAnnotationExampleIntegrationTest {
@Test
public void testScheduledAnnotation() throws InterruptedException {
diff --git a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java
similarity index 89%
rename from spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java
rename to spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java
index 0fca4d21c8..08df73f8fd 100644
--- a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java
+++ b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java
@@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springScheduled-config.xml")
-public class SchedulingWithXmlConfigTest {
+public class SchedulingWithXmlConfigIntegrationTest {
@Test
public void testXmlBasedScheduling() throws InterruptedException {
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/AttributeAnnotationIntegrationTest.java
similarity index 75%
rename from spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java
index aa3acb113f..fff2716a64 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java
@@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@ContextConfiguration(classes = AttributeAnnotationConfiguration.class)
@WebAppConfiguration
-public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
+public class AttributeAnnotationIntegrationTest extends AbstractJUnit4SpringContextTests {
private MockMvc mockMvc;
@@ -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/cache/CacheRefinementsTest.java b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java
similarity index 92%
rename from spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java
index bfd6e5047c..986932dafe 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java
@@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertEquals;
@ContextConfiguration(classes = CacheRefinementsConfiguration.class)
-public class CacheRefinementsTest extends AbstractJUnit4SpringContextTests {
+public class CacheRefinementsIntegrationTest extends AbstractJUnit4SpringContextTests {
private ExecutorService executorService = Executors.newFixedThreadPool(10);
diff --git a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java
similarity index 80%
rename from spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java
index 04fabbc834..d0af48cd0e 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java
@@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@ContextConfiguration(classes = ComposedMappingConfiguration.class)
@WebAppConfiguration
-public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
+public class ComposedMappingIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private AppointmentService appointmentService;
@@ -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/ConfigurationConstructorInjectionIntegrationTest.java
similarity index 71%
rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java
index 82caae15fe..871a985479 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java
@@ -7,8 +7,8 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
-@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class})
-public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
+@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
+public class ConfigurationConstructorInjectionIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
public FooService fooService;
diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java
similarity index 86%
rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java
index be0cf77a62..83fa11294e 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java
@@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration("classpath:implicit-ctor-context.xml")
-public class ImplicitConstructorTest extends AbstractJUnit4SpringContextTests {
+public class ImplicitConstructorIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private FooService fooService;
diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java
similarity index 87%
rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java
index e29d89a679..956df44821 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java
@@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertEquals;
@ContextConfiguration("classpath:defaultmethods-context.xml")
-public class DefaultMethodsInjectionTest extends AbstractJUnit4SpringContextTests {
+public class DefaultMethodsInjectionIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private IDateHolder dateHolder;
diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java
similarity index 76%
rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java
index 89c96ba1d4..b4ac7e8ccf 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java
@@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
@ContextConfiguration(classes = TransactionalTestConfiguration.class)
-public class TransactionalTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest {
+public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest {
@Test
public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() {
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/depresolution/ObjectProviderTest.java b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java
similarity index 87%
rename from spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java
index eeeb005f81..6d06bfdc2a 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java
@@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(classes = ObjectProviderConfiguration.class)
-public class ObjectProviderTest extends AbstractJUnit4SpringContextTests {
+public class ObjectProviderIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private FooService fooService;
diff --git a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java
similarity index 58%
rename from spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java
rename to spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java
index b696760f68..69cce15029 100644
--- a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java
+++ b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java
@@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@ContextConfiguration(classes = ScopeAnnotationsConfiguration.class)
@WebAppConfiguration
-public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
+public class ScopeAnnotationsIntegrationTest extends AbstractJUnit4SpringContextTests {
private MockMvc mockMvc;
@@ -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-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java
similarity index 93%
rename from spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java
rename to spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java
index 2b45ae4e68..e12baed7e0 100644
--- a/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java
+++ b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java
@@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AsynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class AsynchronousCustomSpringEventsTest {
+public class AsynchronousCustomSpringEventsIntegrationTest {
@Autowired
private CustomSpringEventPublisher publisher;
diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java
similarity index 92%
rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java
rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java
index d971698e3f..ac8758bbf6 100644
--- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java
+++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java
@@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class ContextRefreshedListenerTest {
+public class ContextRefreshedListenerIntegrationTest {
@Test
public void testContextRefreshedListener() throws InterruptedException {
diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java
similarity index 93%
rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java
rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java
index b559ca9fc9..f9783f57dc 100644
--- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java
+++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java
@@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class SynchronousCustomSpringEventsTest {
+public class SynchronousCustomSpringEventsIntegrationTest {
@Autowired
private CustomSpringEventPublisher publisher;
diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java
similarity index 97%
rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java
rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java
index 523a27c2c4..6263482948 100644
--- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java
+++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java
@@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class SpringStartupTest {
+public class SpringStartupIntegrationTest {
@Autowired
private ApplicationContext ctx;
diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java
similarity index 93%
rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java
rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java
index 19a35bb92b..a46d24fa3b 100644
--- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java
+++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java
@@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:startupConfig.xml")
-public class SpringStartupXMLConfigTest {
+public class SpringStartupXMLConfigIntegrationTest {
@Autowired
private ApplicationContext ctx;
diff --git a/spring-autowire/README.md b/spring-autowire/README.md
new file mode 100644
index 0000000000..d5b8221b25
--- /dev/null
+++ b/spring-autowire/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire)
diff --git a/spring-autowire/pom.xml b/spring-autowire/pom.xml
index e28efdae61..fd03c77605 100644
--- a/spring-autowire/pom.xml
+++ b/spring-autowire/pom.xml
@@ -57,7 +57,48 @@
org.apache.maven.plugins
maven-surefire-plugin
${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
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/FooServiceIntegrationTest.java
similarity index 74%
rename from spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java
rename to spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java
index 4607f527d9..34ba7902ca 100644
--- a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java
+++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.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)
-public class FooServiceTest {
-
+@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
+public class FooServiceIntegrationTest {
+
@Autowired
FooService fooService;
-
+
@Test
- public void whenFooFormatterType_thenReturnFoo(){
+ public void whenFooFormatterType_thenReturnFoo() {
Assert.assertEquals("foo", fooService.doStuff());
}
}
diff --git a/spring-boot-data-dynamodb/.gitignore b/spring-boot-data-dynamodb/.gitignore
new file mode 100644
index 0000000000..e26d6af438
--- /dev/null
+++ b/spring-boot-data-dynamodb/.gitignore
@@ -0,0 +1,4 @@
+/target/
+.settings/
+.classpath
+.project
diff --git a/spring-boot-data-dynamodb/README.MD b/spring-boot-data-dynamodb/README.MD
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/spring-boot-data-dynamodb/README.MD
@@ -0,0 +1 @@
+
diff --git a/spring-boot-data-dynamodb/pom.xml b/spring-boot-data-dynamodb/pom.xml
new file mode 100644
index 0000000000..11e1366f3e
--- /dev/null
+++ b/spring-boot-data-dynamodb/pom.xml
@@ -0,0 +1,177 @@
+
+ 4.0.0
+ com.baeldung
+ spring-boot-dynamodb
+ 0.0.1-SNAPSHOT
+ jar
+ Spring Boot Actuator
+ This is simple boot application for Spring boot actuator test
+
+
+ spring-boot-starter-parent
+ org.springframework.boot
+ 1.2.3.RELEASE
+
+
+
+
+
+ com.baeldung.Application
+ UTF-8
+ 1.8
+ 4.3.1.RELEASE
+
+
+
+
+
+ org.springframework.data
+ spring-data-releasetrain
+ Gosling-SR1
+ pom
+ import
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-actuator
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+
+ io.dropwizard.metrics
+ metrics-core
+
+
+
+ com.h2database
+ h2
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-starter
+
+
+ com.jayway.jsonpath
+ json-path
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-mail
+
+
+
+ org.webjars
+ bootstrap
+ 3.3.4
+
+
+
+ com.amazonaws
+ aws-java-sdk-dynamodb
+ 1.11.34
+
+
+ com.github.derjust
+ spring-data-dynamodb
+ 4.3.1
+
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
+
+
+
+ spring-boot
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+
+
+
+
+
+
+
+
+ spring-snapshots
+ Spring Snapshots
+ https://repo.spring.io/snapshot
+
+ true
+
+
+
+ spring-milestones
+ Spring Milestones
+ https://repo.spring.io/milestone
+
+ false
+
+
+
+
+
+ spring-snapshots
+ Spring Snapshots
+ https://repo.spring.io/snapshot
+
+ true
+
+
+
+ spring-milestones
+ Spring Milestones
+ https://repo.spring.io/milestone
+
+ false
+
+
+
+
+
diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java
new file mode 100644
index 0000000000..f5e0e98fd4
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java
@@ -0,0 +1,13 @@
+package com.baeldung;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+@ComponentScan(basePackages = { "com.baeldung" })
+public class Application {
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+}
diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java
new file mode 100644
index 0000000000..4bc8a128bc
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java
@@ -0,0 +1,40 @@
+package com.baeldung.spring.data.es.config;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
+import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.util.StringUtils;
+
+@Configuration
+@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.es.repositories")
+public class DynamoDBConfig {
+
+ @Value("${amazon.dynamodb.endpoint}")
+ private String amazonDynamoDBEndpoint;
+
+ @Value("${amazon.aws.accesskey}")
+ private String amazonAWSAccessKey;
+
+ @Value("${amazon.aws.secretkey}")
+ private String amazonAWSSecretKey;
+
+ @Bean
+ public AmazonDynamoDB amazonDynamoDB() {
+ AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(amazonAWSCredentials());
+ if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) {
+ amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
+ }
+ return amazonDynamoDB;
+ }
+
+ @Bean
+ public AWSCredentials amazonAWSCredentials() {
+ return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
+ }
+
+}
diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java
new file mode 100644
index 0000000000..3e75c9e6f2
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java
@@ -0,0 +1,49 @@
+package com.baeldung.spring.data.es.model;
+
+import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
+import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
+import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
+import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
+
+@DynamoDBTable(tableName = "ProductInfo")
+public class ProductInfo {
+ private String id;
+ private String msrp;
+ private String cost;
+
+ public ProductInfo() {
+ }
+
+ public ProductInfo(String cost, String msrp) {
+ this.msrp = msrp;
+ this.cost = cost;
+ }
+
+ @DynamoDBHashKey
+ @DynamoDBAutoGeneratedKey
+ public String getId() {
+ return id;
+ }
+
+ @DynamoDBAttribute
+ public String getMsrp() {
+ return msrp;
+ }
+
+ @DynamoDBAttribute
+ public String getCost() {
+ return cost;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setMsrp(String msrp) {
+ this.msrp = msrp;
+ }
+
+ public void setCost(String cost) {
+ this.cost = cost;
+ }
+}
diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java
new file mode 100644
index 0000000000..c5eee49634
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java
@@ -0,0 +1,12 @@
+package com.baeldung.spring.data.es.repositories;
+
+import com.baeldung.spring.data.es.model.ProductInfo;
+import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
+import org.springframework.data.repository.CrudRepository;
+
+import java.util.List;
+
+@EnableScan
+public interface ProductInfoRepository extends CrudRepository {
+ List findById(String id);
+}
diff --git a/spring-boot-data-dynamodb/src/main/resources/application.properties b/spring-boot-data-dynamodb/src/main/resources/application.properties
new file mode 100644
index 0000000000..e6911bc9e7
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/resources/application.properties
@@ -0,0 +1,32 @@
+server.port=8080
+server.contextPath=/springbootapp
+management.port=8081
+management.address=127.0.0.1
+
+endpoints.shutdown.enabled=true
+
+endpoints.jmx.domain=Spring Sample Application
+endpoints.jmx.uniqueNames=true
+
+spring.jmx.enabled=true
+endpoints.jmx.enabled=true
+
+## for pretty printing of json when endpoints accessed over HTTP
+http.mappers.jsonPrettyPrint=true
+
+## Configuring info endpoint
+info.app.name=Spring Sample Application
+info.app.description=This is my first spring boot application G1
+info.app.version=1.0.0
+
+## Spring Security Configurations
+security.user.name=admin1
+security.user.password=secret1
+management.security.role=SUPERUSER
+
+logging.level.org.springframework=INFO
+
+#AWS Keys
+amazon.dynamodb.endpoint=http://localhost:8000/
+amazon.aws.accesskey=test1
+amazon.aws.secretkey=test1
\ No newline at end of file
diff --git a/spring-boot-data-dynamodb/src/main/resources/demo.properties b/spring-boot-data-dynamodb/src/main/resources/demo.properties
new file mode 100644
index 0000000000..649b64f59b
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/resources/demo.properties
@@ -0,0 +1,6 @@
+spring.output.ansi.enabled=never
+server.port=7070
+
+# Security
+security.user.name=admin
+security.user.password=password
\ No newline at end of file
diff --git a/spring-boot-data-dynamodb/src/main/resources/logback.xml b/spring-boot-data-dynamodb/src/main/resources/logback.xml
new file mode 100644
index 0000000000..c0bc602910
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/resources/logback.xml
@@ -0,0 +1,14 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
diff --git a/spring-boot-data-dynamodb/src/main/resources/templates/index.html b/spring-boot-data-dynamodb/src/main/resources/templates/index.html
new file mode 100644
index 0000000000..046d21600a
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/main/resources/templates/index.html
@@ -0,0 +1,19 @@
+
+
+ WebJars Demo
+
+
+
+
+
+
+
+
Success! It is working as we expected.
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java b/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..df727cf727
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.spring.data.es.repository;
+
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
+import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
+import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
+import com.amazonaws.services.dynamodbv2.model.ResourceInUseException;
+import com.baeldung.Application;
+import com.baeldung.spring.data.es.model.ProductInfo;
+import com.baeldung.spring.data.es.repositories.ProductInfoRepository;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.IntegrationTest;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.WebAppConfiguration;
+
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = Application.class)
+@WebAppConfiguration
+@IntegrationTest
+@ActiveProfiles("local")
+@TestPropertySource(properties = { "amazon.dynamodb.endpoint=http://localhost:8000/", "amazon.aws.accesskey=test1", "amazon.aws.secretkey=test231" })
+public class ProductInfoRepositoryIntegrationTest {
+
+ private DynamoDBMapper dynamoDBMapper;
+
+ @Autowired
+ private AmazonDynamoDB amazonDynamoDB;
+
+ @Autowired
+ ProductInfoRepository repository;
+
+ private static final String EXPECTED_COST = "20";
+ private static final String EXPECTED_PRICE = "50";
+
+ @Before
+ public void setup() throws Exception {
+
+ try {
+ dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
+
+ CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(ProductInfo.class);
+
+ tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
+
+ amazonDynamoDB.createTable(tableRequest);
+ } catch (ResourceInUseException e) {
+ // Do nothing, table already created
+ }
+
+ // TODO How to handle different environments. i.e. AVOID deleting all entries in ProductInfoion table
+ dynamoDBMapper.batchDelete((List) repository.findAll());
+ }
+
+ @Test
+ public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() {
+
+ ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE);
+ repository.save(productInfo);
+
+ List result = (List) repository.findAll();
+ assertTrue("Not empty", result.size() > 0);
+ assertTrue("Contains item with expected cost", result.get(0).getCost().equals(EXPECTED_COST));
+ }
+}
diff --git a/spring-boot-data-dynamodb/src/test/resources/application.properties b/spring-boot-data-dynamodb/src/test/resources/application.properties
new file mode 100644
index 0000000000..01e8a2e52e
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/test/resources/application.properties
@@ -0,0 +1,7 @@
+spring.mail.host=localhost
+spring.mail.port=8025
+spring.mail.properties.mail.smtp.auth=false
+
+amazon.dynamodb.endpoint=http://localhost:8000/
+amazon.aws.accesskey=key
+amazon.aws.secretkey=key2
\ No newline at end of file
diff --git a/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties b/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties
new file mode 100644
index 0000000000..cde746acb9
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties
@@ -0,0 +1,2 @@
+spring.profiles.active=exception
+spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
diff --git a/spring-boot-data-dynamodb/src/test/resources/exception.properties b/spring-boot-data-dynamodb/src/test/resources/exception.properties
new file mode 100644
index 0000000000..c55e415a3a
--- /dev/null
+++ b/spring-boot-data-dynamodb/src/test/resources/exception.properties
@@ -0,0 +1,6 @@
+# Security
+security.user.name=admin
+security.user.password=password
+
+spring.dao.exceptiontranslation.enabled=false
+spring.profiles.active=exception
\ No newline at end of file
diff --git a/spring-boot/README.MD b/spring-boot/README.MD
index 2a87b46021..1610d77e81 100644
--- a/spring-boot/README.MD
+++ b/spring-boot/README.MD
@@ -1,2 +1,7 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
+
+###Relevant Articles:
+- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
+- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters)
+- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring)
diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml
index 5a20ff5602..a2555259b0 100644
--- a/spring-boot/pom.xml
+++ b/spring-boot/pom.xml
@@ -88,12 +88,12 @@
org.webjars
bootstrap
- 3.3.4
+ 3.3.7-1
org.webjars
jquery
- 2.1.4
+ 3.1.1
@@ -133,10 +133,56 @@
2.2.1
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
spring-snapshots
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/java/com/baeldung/git/README.md b/spring-boot/src/main/java/com/baeldung/git/README.md
new file mode 100644
index 0000000000..7e6a597c28
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/git/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)
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
-
+
-
+
×
Success! It is working as we expected.
-
-
+
+
-
\ No newline at end of file
+