diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml new file mode 100644 index 0000000000..6d07394b87 --- /dev/null +++ b/annotations/annotation-processing/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + com.baeldung + 1.0.0-SNAPSHOT + annotations + ../ + + + annotation-processing + + + 1.0-rc2 + 3.5.1 + + + + + + com.google.auto.service + auto-service + ${auto-service.version} + provided + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java new file mode 100644 index 0000000000..0883e108e7 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -0,0 +1,132 @@ +package com.baeldung.annotation.processor; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ExecutableType; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.google.auto.service.AutoService; + +@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") +@SupportedSourceVersion(SourceVersion.RELEASE_8) +@AutoService(Processor.class) +public class BuilderProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + + Map> annotatedMethods = annotatedElements.stream() + .collect(Collectors.partitioningBy(element -> + ((ExecutableType) element.asType()).getParameterTypes().size() == 1 + && element.getSimpleName().toString().startsWith("set"))); + + List setters = annotatedMethods.get(true); + List otherMethods = annotatedMethods.get(false); + + otherMethods.forEach(element -> + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + + if (setters.isEmpty()) { + continue; + } + + String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); + + Map setterMap = setters.stream().collect(Collectors.toMap( + setter -> setter.getSimpleName().toString(), + setter -> ((ExecutableType) setter.asType()) + .getParameterTypes().get(0).toString() + )); + + try { + writeBuilderFile(className, setterMap); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return true; + } + + private void writeBuilderFile(String className, Map setterMap) throws IOException { + + String packageName = null; + int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + packageName = className.substring(0, lastDot); + } + + String simpleClassName = className.substring(lastDot + 1); + String builderClassName = className + "Builder"; + String builderSimpleClassName = builderClassName.substring(lastDot + 1); + + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); + try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { + + if (packageName != null) { + out.print("package "); + out.print(packageName); + out.println(";"); + out.println(); + } + + out.print("public class "); + out.print(builderSimpleClassName); + out.println(" {"); + out.println(); + + out.print(" private "); + out.print(simpleClassName); + out.print(" object = new "); + out.print(simpleClassName); + out.println("();"); + out.println(); + + out.print(" public "); + out.print(simpleClassName); + out.println(" build() {"); + out.println(" return object;"); + out.println(" }"); + out.println(); + + setterMap.entrySet().forEach(setter -> { + String methodName = setter.getKey(); + String argumentType = setter.getValue(); + + out.print(" public "); + out.print(builderSimpleClassName); + out.print(" "); + out.print(methodName); + + out.print("("); + + out.print(argumentType); + out.println(" value) {"); + out.print(" object."); + out.print(methodName); + out.println("(value);"); + out.println(" return this;"); + out.println(" }"); + out.println(); + }); + + out.println("}"); + + } + } + +} diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java new file mode 100644 index 0000000000..84fcc73850 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation.processor; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.SOURCE) +public @interface BuilderProperty { +} diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml new file mode 100644 index 0000000000..f76f691f93 --- /dev/null +++ b/annotations/annotation-user/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + + annotations + com.baeldung + 1.0.0-SNAPSHOT + ../ + + + annotation-user + + + + + com.baeldung + annotation-processing + ${project.parent.version} + + + + junit + junit + 4.12 + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java new file mode 100644 index 0000000000..23787ba4f4 --- /dev/null +++ b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java @@ -0,0 +1,29 @@ +package com.baeldung.annotation; + +import com.baeldung.annotation.processor.BuilderProperty; + +public class Person { + + private int age; + + private String name; + + public int getAge() { + return age; + } + + @BuilderProperty + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + @BuilderProperty + public void setName(String name) { + this.name = name; + } + +} diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java new file mode 100644 index 0000000000..72f9ac8bc7 --- /dev/null +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -0,0 +1,22 @@ +package com.baeldung.annotation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PersonBuilderTest { + + @Test + public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { + + Person person = new PersonBuilder() + .setAge(25) + .setName("John") + .build(); + + assertEquals(25, person.getAge()); + assertEquals("John", person.getName()); + + } + +} diff --git a/annotations/pom.xml b/annotations/pom.xml new file mode 100644 index 0000000000..f691674cf1 --- /dev/null +++ b/annotations/pom.xml @@ -0,0 +1,20 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + annotations + pom + + + annotation-processing + annotation-user + + + \ No newline at end of file diff --git a/annotations/readme.md b/annotations/readme.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/annotations/readme.md @@ -0,0 +1 @@ + diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml new file mode 100644 index 0000000000..1f83ecf934 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + cxf-jaxrs-implementation + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + UTF-8 + 3.1.7 + 4.5.2 + + + + + org.codehaus.mojo + exec-maven-plugin + + com.baeldung.cxf.jaxrs.implementation.RestfulServer + + + + maven-surefire-plugin + 2.19.1 + + + **/ServiceTest + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java new file mode 100644 index 0000000000..5617f482f8 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -0,0 +1,68 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +@Path("baeldung") +@Produces("text/xml") +public class Baeldung { + private Map courses = new HashMap<>(); + + { + Student student1 = new Student(); + Student student2 = new Student(); + student1.setId(1); + student1.setName("Student A"); + student2.setId(2); + student2.setName("Student B"); + + List course1Students = new ArrayList<>(); + course1Students.add(student1); + course1Students.add(student2); + + Course course1 = new Course(); + Course course2 = new Course(); + course1.setId(1); + course1.setName("REST with Spring"); + course1.setStudents(course1Students); + course2.setId(2); + course2.setName("Learn Spring Security"); + + courses.put(1, course1); + courses.put(2, course2); + } + + @GET + @Path("courses/{courseOrder}") + public Course getCourse(@PathParam("courseOrder") int courseOrder) { + return courses.get(courseOrder); + } + + @PUT + @Path("courses/{courseOrder}") + public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { + Course existingCourse = courses.get(courseOrder); + Response response; + if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { + courses.put(courseOrder, course); + response = Response.ok().build(); + } else { + response = Response.notModified().build(); + } + return response; + } + + @Path("courses/{courseOrder}/students") + public Course pathToStudent(@PathParam("courseOrder") int courseOrder) { + return courses.get(courseOrder); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java new file mode 100644 index 0000000000..9ab74bea58 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -0,0 +1,73 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Course") +public class Course { + private int id; + private String name; + private List students; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } + + @GET + @Path("{studentOrder}") + public Student getStudent(@PathParam("studentOrder")int studentOrder) { + return students.get(studentOrder); + } + + @POST + public Response postStudent(Student student) { + if (students == null) { + students = new ArrayList(); + } + students.add(student); + return Response.ok(student).build(); + } + + @DELETE + @Path("{studentOrder}") + public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { + Student student = students.get(studentOrder); + Response response; + if (student != null) { + students.remove(studentOrder); + response = Response.ok().build(); + } else { + response = Response.notModified().build(); + } + return response; + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java new file mode 100644 index 0000000000..bb35bab3f8 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -0,0 +1,21 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; + +public class RestfulServer { + public static void main(String args[]) throws Exception { + JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean(); + factoryBean.setResourceClasses(Baeldung.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung())); + factoryBean.setAddress("http://localhost:8080/"); + Server server = factoryBean.create(); + + System.out.println("Server ready..."); + Thread.sleep(60 * 1000); + System.out.println("Server exiting"); + server.destroy(); + System.exit(0); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java new file mode 100644 index 0000000000..de782e4edb --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java @@ -0,0 +1,25 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Student") +public class Student { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml new file mode 100644 index 0000000000..465c337745 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml @@ -0,0 +1,4 @@ + + 3 + Apache CXF Support for RESTful + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml new file mode 100644 index 0000000000..7fb6189815 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml @@ -0,0 +1,5 @@ + + + 3 + Student C + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java new file mode 100644 index 0000000000..48749a568e --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java @@ -0,0 +1,93 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; + +import javax.xml.bind.JAXB; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +public class ServiceTest { + private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; + private static CloseableHttpClient client; + + @BeforeClass + public static void createClient() { + client = HttpClients.createDefault(); + } + + @AfterClass + public static void closeClient() throws IOException { + client.close(); + } + + @Test + public void whenPutCourse_thenCorrect() throws IOException { + HttpPut httpPut = new HttpPut(BASE_URL + "3"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPut); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Course course = getCourse(3); + assertEquals(3, course.getId()); + assertEquals("Apache CXF Support for RESTful", course.getName()); + } + + @Test + public void whenPostStudent_thenCorrect() throws IOException { + HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml"); + httpPost.setEntity(new InputStreamEntity(resourceStream)); + httpPost.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPost); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Student student = getStudent(2, 0); + assertEquals(3, student.getId()); + assertEquals("Student C", student.getName()); + } + + @Test + public void whenDeleteStudent_thenCorrect() throws IOException { + HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0"); + HttpResponse response = client.execute(httpDelete); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Course course = getCourse(1); + assertEquals(1, course.getStudents().size()); + assertEquals(2, course.getStudents().get(0).getId()); + assertEquals("Student B", course.getStudents().get(0).getName()); + } + + private Course getCourse(int courseOrder) throws IOException { + URL url = new URL(BASE_URL + courseOrder); + InputStream input = url.openStream(); + Course course = JAXB.unmarshal(new InputStreamReader(input), Course.class); + return course; + } + + private Student getStudent(int courseOrder, int studentOrder) throws IOException { + URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); + InputStream input = url.openStream(); + Student student = JAXB.unmarshal(new InputStreamReader(input), Student.class); + return student; + } +} \ No newline at end of file diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 022fc59f9b..af7949bb6c 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -8,6 +8,7 @@ cxf-introduction cxf-spring + cxf-jaxrs-implementation diff --git a/assertj/pom.xml b/assertj/pom.xml index 421afd40a5..df55ebba4b 100644 --- a/assertj/pom.xml +++ b/assertj/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -9,11 +8,18 @@ 1.0.0-SNAPSHOT + com.google.guava guava - 19.0 + ${guava.version} + + org.assertj + assertj-guava + 3.0.0 + + junit junit @@ -26,11 +32,7 @@ 3.5.1 test - - org.assertj - assertj-guava - 3.0.0 - + @@ -46,4 +48,9 @@ + + + 19.0 + + \ No newline at end of file diff --git a/core-java-8/README.md b/core-java-8/README.md index e6bac2a4c9..c130e6bd41 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,4 +11,14 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) +- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 63df0e1b95..22e3bab595 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,9 +1,10 @@ 4.0.0 + com.baeldung + 1.0.0-SNAPSHOT core-java8 - 0.1-SNAPSHOT core-java8 @@ -14,7 +15,7 @@ commons-io commons-io - 2.4 + 2.5 @@ -111,6 +112,9 @@ + + UTF-8 + 1.7.13 1.0.13 diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java-8/src/main/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-8/src/main/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java index 8143da5794..1918c801dc 100644 --- a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java +++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java @@ -1,17 +1,71 @@ package com.baeldung; +import com.google.common.collect.Lists; import org.junit.Test; -import java.util.Arrays; -import java.util.List; -import java.util.Random; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; public class RandomListElementTest { @Test - public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() { - List givenList = Arrays.asList(1, 2, 3); + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { + List givenList = Lists.newArrayList(1, 2, 3); Random rand = new Random(); + givenList.get(rand.nextInt(givenList.size())); } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { + List givenList = Lists.newArrayList(1, 2, 3); + + givenList.get((int)(Math.random() * givenList.size())); + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + } + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + givenList.remove(randomIndex); + } + } + + @Test + public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + Collections.shuffle(givenList); + + int randomSeriesLength = 3; + + givenList.subList(0, randomSeriesLength - 1); + } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size(); + + givenList.get(randomIndex); + } + } diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java new file mode 100644 index 0000000000..62d2663994 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java @@ -0,0 +1,38 @@ +package com.baeldung.encoderdecoder; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class EncoderDecoder { + + @Test + public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { + String plainURL = "http://www.baeldung.com" ; + String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; + + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); + + Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java new file mode 100644 index 0000000000..e21af9552a --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -0,0 +1,121 @@ +package com.baeldung.file; + +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +public class FileOperationsTest { + + @Test + public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + InputStream inputStream = new FileInputStream(file); + String data = readFromInputStream(inputStream); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Class clazz = FileOperationsTest.class; + InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { + String expectedData = "BSD License"; + + Class clazz = Matchers.class; + InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenURLName_whenUsingURL_thenFileData() throws IOException { + String expectedData = "Baeldung"; + + URL urlObject = new URL("http://www.baeldung.com/"); + + URLConnection urlConnection = urlObject.openConnection(); + + InputStream inputStream = urlConnection.getInputStream(); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + String data = FileUtils.readFileToString(file); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + byte[] fileBytes = Files.readAllBytes(path); + String data = new String(fileBytes); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + StringBuilder data = new StringBuilder(); + Stream lines = Files.lines(path); + lines.forEach(line -> data.append(line).append("\n")); + lines.close(); + + Assert.assertEquals(expectedData, data.toString().trim()); + } + + private String readFromInputStream(InputStream inputStream) throws IOException { + StringBuilder resultStringBuilder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line).append("\n"); + } + } + + return resultStringBuilder.toString(); + } +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index efd548a4b1..f2e7452137 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -21,7 +21,7 @@ public class JavaFolderSizeTest { @Before public void init() { final String separator = File.separator; - path = "src" + separator + "test" + separator + "resources"; + path = String.format("src%stest%sresources", separator, separator); } @Test @@ -79,7 +79,9 @@ public class JavaFolderSizeTest { final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length).sum(); assertEquals(expectedSize, size); } @@ -101,13 +103,11 @@ public class JavaFolderSizeTest { long length = 0; final File[] files = folder.listFiles(); - final int count = files.length; - - for (int i = 0; i < count; i++) { - if (files[i].isFile()) { - length += files[i].length(); + for (File file : files) { + if (file.isFile()) { + length += file.length(); } else { - length += getFolderSize(files[i]); + length += getFolderSize(file); } } return length; diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java new file mode 100644 index 0000000000..da9027060e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -0,0 +1,41 @@ +package com.baeldung.util; + +import org.junit.Test; + +import java.time.*; +import java.time.temporal.ChronoField; + +import static org.junit.Assert.assertEquals; + +public class CurrentDateTimeTest { + + private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC")); + + @Test + public void shouldReturnCurrentDate() { + + final LocalDate now = LocalDate.now(clock); + + assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(2016, now.get(ChronoField.YEAR)); + } + + @Test + public void shouldReturnCurrentTime() { + + final LocalTime now = LocalTime.now(clock); + + assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); + } + + @Test + public void shouldReturnCurrentTimestamp() { + + final Instant now = Instant.now(clock); + + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); + } +} diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt new file mode 100644 index 0000000000..652d70630f --- /dev/null +++ b/core-java-8/src/test/resources/test.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/core-java-8/src/test/resources/.gitignore b/core-java-9/.gitignore similarity index 100% rename from core-java-8/src/test/resources/.gitignore rename to core-java-9/.gitignore diff --git a/core-java-9/README.md b/core-java-9/README.md new file mode 100644 index 0000000000..b5d4dbef95 --- /dev/null +++ b/core-java-9/README.md @@ -0,0 +1,5 @@ +========= + +## Core Java 9 Examples + +http://inprogress.baeldung.com/java-9-new-features/ \ No newline at end of file diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml new file mode 100644 index 0000000000..844ad6a782 --- /dev/null +++ b/core-java-9/pom.xml @@ -0,0 +1,93 @@ + + 4.0.0 + com.baeldung + core-java9 + 0.2-SNAPSHOT + + core-java9 + + + + apache.snapshots + http://repository.apache.org/snapshots/ + + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + core-java-9 + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.9 + 1.9 + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + 1.7.13 + 1.0.13 + + + + 3.6-jigsaw-SNAPSHOT + 2.19.1 + + + 1.3 + 4.12 + 1.10.19 + + + diff --git a/spring-jpa-jndi/.gitignore b/core-java-9/src/main/java/.gitignore similarity index 100% rename from spring-jpa-jndi/.gitignore rename to core-java-9/src/main/java/.gitignore diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java new file mode 100644 index 0000000000..fd6a496b18 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java @@ -0,0 +1,23 @@ +package com.baeldung.java9.language; + +public interface PrivateInterface { + + private static String staticPrivate() { + return "static private"; + } + + private String instancePrivate() { + return "instance private"; + } + + public default void check(){ + String result = staticPrivate(); + if (!result.equals("static private")) + throw new AssertionError("Incorrect result for static private interface method"); + PrivateInterface pvt = new PrivateInterface() { + }; + result = pvt.instancePrivate(); + if (!result.equals("instance private")) + throw new AssertionError("Incorrect result for instance private interface method"); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java new file mode 100644 index 0000000000..d6682bd0c8 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -0,0 +1,44 @@ +package com.baeldung.java9.process; + +import java.io.File; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.stream.Stream; + + +public class ProcessUtils { + + public static String getClassPath(){ + String cp = System.getProperty("java.class.path"); + System.out.println("ClassPath is "+cp); + return cp; + } + + public static File getJavaCmd() throws IOException{ + String javaHome = System.getProperty("java.home"); + File javaCmd; + if(System.getProperty("os.name").startsWith("Win")){ + javaCmd = new File(javaHome, "bin/java.exe"); + }else{ + javaCmd = new File(javaHome, "bin/java"); + } + if(javaCmd.canExecute()){ + return javaCmd; + }else{ + throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable"); + } + } + + public static String getMainClass(){ + return System.getProperty("sun.java.command"); + } + + public static String getSystemProperties(){ + StringBuilder sb = new StringBuilder(); + System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) ); + return sb.toString(); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java new file mode 100644 index 0000000000..458f746496 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -0,0 +1,22 @@ +package com.baeldung.java9.process; + +import java.util.Optional; + +public class ServiceMain { + + public static void main(String[] args) throws InterruptedException { + ProcessHandle thisProcess = ProcessHandle.current(); + long pid = thisProcess.getPid(); + + + Optional opArgs = Optional.ofNullable(args); + String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); + + for (int i = 0; i < 10000; i++) { + System.out.println("Process " + procName + " with ID " + pid + " is running!"); + Thread.sleep(10000); + } + + } + +} diff --git a/spring-data-couchbase-2b/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml similarity index 64% rename from spring-data-couchbase-2b/src/main/resources/logback.xml rename to core-java-9/src/main/resources/logback.xml index d9067fd1da..eefdc7a337 100644 --- a/spring-data-couchbase-2b/src/main/resources/logback.xml +++ b/core-java-9/src/main/resources/logback.xml @@ -7,11 +7,10 @@ - - + - + \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java new file mode 100644 index 0000000000..b0684a94f8 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -0,0 +1,71 @@ +package com.baeldung.java8; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +public class Java9OptionalsStreamTest { + + private static List> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar")); + + @Test + public void filterOutPresentOptionalsWithFilter() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + + assertEquals(2, filteredList.size()); + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithFlatMap() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); + + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithFlatMap2() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); + + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithJava9() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(Optional::stream) + .collect(Collectors.toList()); + + assertEquals(2, filteredList.size()); + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java new file mode 100644 index 0000000000..a00646e4db --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -0,0 +1,47 @@ +package com.baeldung.java9; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import java.awt.Image; +import java.awt.image.BaseMultiResolutionImage; +import java.awt.image.BufferedImage; +import java.awt.image.MultiResolutionImage; +import java.util.List; + +import org.junit.Test; + +public class MultiResultionImageTest { + + + @Test + public void baseMultiResImageTest() { + int baseIndex = 1; + int length = 4; + BufferedImage[] resolutionVariants = new BufferedImage[length]; + for (int i = 0; i < length; i++) { + resolutionVariants[i] = createImage(i); + } + MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants); + List rvImageList = bmrImage.getResolutionVariants(); + assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length); + + for (int i = 0; i < length; i++) { + int imageSize = getSize(i); + Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize); + assertSame("Images should be the same", testRVImage, resolutionVariants[i]); + } + + } + + private static int getSize(int i) { + return 8 * (i + 1); + } + + + private static BufferedImage createImage(int i) { + return new BufferedImage(getSize(i), getSize(i), + BufferedImage.TYPE_INT_RGB); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java new file mode 100644 index 0000000000..56b4bb7b8c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java @@ -0,0 +1,21 @@ +package com.baeldung.java9; + +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class OptionalToStreamTest { + + @Test + public void testOptionalToStream() { + Optional op = Optional.ofNullable("String value"); + Stream strOptionalStream = op.stream(); + Stream filteredStream = strOptionalStream.filter((str) -> { + return str != null && str.startsWith("String"); + }); + assertEquals(1, filteredStream.count()); + + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD @@ -0,0 +1 @@ + diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java new file mode 100644 index 0000000000..0f8db83d9c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java @@ -0,0 +1,26 @@ +package com.baeldung.java9; + +import java.util.Set; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SetExamplesTest { + + @Test + public void testUnmutableSet() { + Set strKeySet = Set.of("key1", "key2", "key3"); + try { + strKeySet.add("newKey"); + } catch (UnsupportedOperationException uoe) { + } + assertEquals(strKeySet.size(), 3); + } + + @Test + public void testArrayToSet() { + Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; + Set intSet = Set.of(intArray); + assertEquals(intSet.size(), intArray.length); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java new file mode 100644 index 0000000000..ab28b0a805 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java @@ -0,0 +1,126 @@ +package com.baeldung.java9.httpclient; + + + +import static java.net.HttpURLConnection.HTTP_OK; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; + +import org.junit.Before; +import org.junit.Test; + +public class SimpleHttpRequestsTest { + + private URI httpURI; + + @Before + public void init() throws URISyntaxException { + httpURI = new URI("http://www.baeldung.com/"); + } + + @Test + public void quickGet() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.create( httpURI ).GET(); + HttpResponse response = request.response(); + int responseStatusCode = response.statusCode(); + String responseBody = response.body(HttpResponse.asString()); + assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); + } + + @Test + public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + HttpRequest request = HttpRequest.create(httpURI).GET(); + long before = System.currentTimeMillis(); + CompletableFuture futureResponse = request.responseAsync(); + futureResponse.thenAccept( response -> { + String responseBody = response.body(HttpResponse.asString()); + }); + HttpResponse resp = futureResponse.get(); + HttpHeaders hs = resp.headers(); + assertTrue("There should be more then 1 header.", hs.map().size() >1); + } + + @Test + public void postMehtod() throws URISyntaxException, IOException, InterruptedException { + HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI); + requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE); + HttpRequest request = requestBuilder.POST(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + @Test + public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{ + CookieManager cManager = new CookieManager(); + cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); + + SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); + + HttpClient.Builder hcBuilder = HttpClient.create(); + hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); + HttpClient httpClient = hcBuilder.build(); + HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com")); + + HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{ + SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters(); + String [] proto = sslP1.getApplicationProtocols(); + String [] cifers = sslP1.getCipherSuites(); + System.out.println(printStringArr(proto)); + System.out.println(printStringArr(cifers)); + return sslP1; + } + + String printStringArr(String ... args ){ + if(args == null){ + return null; + } + StringBuilder sb = new StringBuilder(); + for (String s : args){ + sb.append(s); + sb.append("\n"); + } + return sb.toString(); + } + + String printHeaders(HttpHeaders h){ + if(h == null){ + return null; + } + + StringBuilder sb = new StringBuilder(); + Map> hMap = h.map(); + for(String k : hMap.keySet()){ + sb.append(k).append(":"); + List l = hMap.get(k); + if( l != null ){ + l.forEach( s -> { sb.append(s).append(","); } ); + } + sb.append("\n"); + } + return sb.toString(); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java new file mode 100644 index 0000000000..33da6486f4 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java @@ -0,0 +1,36 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +public class DiamondTest { + + static class FooClass { + FooClass(X x) { + } + + FooClass(X x, Z z) { + } + } + + @Test + public void diamondTest() { + FooClass fc = new FooClass<>(1) { + }; + FooClass fc0 = new FooClass<>(1) { + }; + FooClass fc1 = new FooClass<>(1) { + }; + FooClass fc2 = new FooClass<>(1) { + }; + + FooClass fc3 = new FooClass<>(1, "") { + }; + FooClass fc4 = new FooClass<>(1, "") { + }; + FooClass fc5 = new FooClass<>(1, "") { + }; + FooClass fc6 = new FooClass<>(1, "") { + }; + + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java new file mode 100644 index 0000000000..29ef3930f8 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.language; + +import com.baeldung.java9.language.PrivateInterface; +import org.junit.Test; + +public class PrivateInterfaceTest { + + @Test + public void test() { + PrivateInterface piClass = new PrivateInterface() { + }; + piClass.check(); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java new file mode 100644 index 0000000000..687dfbc390 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java @@ -0,0 +1,70 @@ +package com.baeldung.java9.language; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class TryWithResourcesTest { + + static int closeCount = 0; + + static class MyAutoCloseable implements AutoCloseable{ + final FinalWrapper finalWrapper = new FinalWrapper(); + + public void close() { + closeCount++; + } + + static class FinalWrapper { + public final AutoCloseable finalCloseable = new AutoCloseable() { + @Override + public void close() throws Exception { + closeCount++; + } + }; + } + } + + @Test + public void tryWithResourcesTest() { + MyAutoCloseable mac = new MyAutoCloseable(); + + try (mac) { + assertEquals("Expected and Actual does not match", 0, closeCount); + } + + try (mac.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 1, closeCount); + } catch (Exception ex) { + } + + try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 2, closeCount); + } catch (Exception ex) { + } + + try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 3, closeCount); + } catch (Exception ex) { + } + + try { + throw new CloseableException(); + } catch (CloseableException ex) { + try (ex) { + assertEquals("Expected and Actual does not match", 4, closeCount); + } + } + assertEquals("Expected and Actual does not match", 5, closeCount); + } + + + static class CloseableException extends Exception implements AutoCloseable { + @Override + public void close() { + closeCount++; + } + } + +} + + diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java new file mode 100644 index 0000000000..419516cb64 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java @@ -0,0 +1,112 @@ +package com.baeldung.java9.process; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ProcessApi { + + + @Before + public void init() { + + } + + @Test + public void processInfoExample()throws NoSuchAlgorithmException{ + ProcessHandle self = ProcessHandle.current(); + long PID = self.getPid(); + ProcessHandle.Info procInfo = self.info(); + Optional args = procInfo.arguments(); + Optional cmd = procInfo.commandLine(); + Optional startTime = procInfo.startInstant(); + Optional cpuUsage = procInfo.totalCpuDuration(); + + waistCPU(); + System.out.println("Args "+ args); + System.out.println("Command " +cmd.orElse("EmptyCmd")); + System.out.println("Start time: "+ startTime.get().toString()); + System.out.println(cpuUsage.get().toMillis()); + + Stream allProc = ProcessHandle.current().children(); + allProc.forEach(p -> { + System.out.println("Proc "+ p.getPid()); + }); + + } + + @Test + public void createAndDestroyProcess() throws IOException, InterruptedException{ + int numberOfChildProcesses = 5; + for(int i=0; i < numberOfChildProcesses; i++){ + createNewJVM(ServiceMain.class, i).getPid(); + } + + Stream childProc = ProcessHandle.current().children(); + assertEquals( childProc.count(), numberOfChildProcesses); + + childProc = ProcessHandle.current().children(); + childProc.forEach(processHandle -> { + assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive()); + CompletableFuture onProcExit = processHandle.onExit(); + onProcExit.thenAccept(procHandle -> { + System.out.println("Process with PID "+ procHandle.getPid() + " has stopped"); + }); + }); + + Thread.sleep(10000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy()); + }); + + Thread.sleep(5000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive()); + }); + + } + + private Process createNewJVM(Class mainClass, int number) throws IOException{ + ArrayList cmdParams = new ArrayList(5); + cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath()); + cmdParams.add("-cp"); + cmdParams.add(ProcessUtils.getClassPath()); + cmdParams.add(mainClass.getName()); + cmdParams.add("Service "+ number); + ProcessBuilder myService = new ProcessBuilder(cmdParams); + myService.inheritIO(); + return myService.start(); + } + + private void waistCPU() throws NoSuchAlgorithmException{ + ArrayList randArr = new ArrayList(4096); + SecureRandom sr = SecureRandom.getInstanceStrong(); + Duration somecpu = Duration.ofMillis(4200L); + Instant end = Instant.now().plus(somecpu); + while (Instant.now().isBefore(end)) { + //System.out.println(sr.nextInt()); + randArr.add( sr.nextInt() ); + } + } + +} diff --git a/core-java-9/src/test/resources/.gitignore b/core-java-9/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index bc533607e7..a5e89d2a76 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -123,6 +123,12 @@ ${mockito.version} test + + + commons-codec + commons-codec + 1.10 + @@ -168,7 +174,7 @@ 5.1.38 - 2.7.2 + 2.7.8 1.7.13 diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java new file mode 100644 index 0000000000..1c034051aa --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java @@ -0,0 +1,46 @@ +package com.baeldung.java.nio.selector; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class EchoClient { + private static SocketChannel client; + private static ByteBuffer buffer; + private static EchoClient instance; + + public static EchoClient start() { + if (instance == null) + instance = new EchoClient(); + + return instance; + } + + private EchoClient() { + try { + client = SocketChannel.open(new InetSocketAddress("localhost", 5454)); + buffer = ByteBuffer.allocate(256); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String sendMessage(String msg) { + buffer = ByteBuffer.wrap(msg.getBytes()); + String response = null; + try { + client.write(buffer); + buffer.clear(); + client.read(buffer); + response = new String(buffer.array()).trim(); + System.out.println("response=" + response); + buffer.clear(); + } catch (IOException e) { + e.printStackTrace(); + } + return response; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java new file mode 100644 index 0000000000..aedcbb319b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -0,0 +1,50 @@ +package com.baeldung.java.nio.selector; + +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.Selector; +import java.nio.channels.SelectionKey; +import java.nio.ByteBuffer; +import java.io.IOException; +import java.util.Set; +import java.util.Iterator; +import java.net.InetSocketAddress; + +public class EchoServer { + + public static void main(String[] args) + + throws IOException { + Selector selector = Selector.open(); + ServerSocketChannel serverSocket = ServerSocketChannel.open(); + serverSocket.bind(new InetSocketAddress("localhost", 5454)); + serverSocket.configureBlocking(false); + serverSocket.register(selector, SelectionKey.OP_ACCEPT); + ByteBuffer buffer = ByteBuffer.allocate(256); + + while (true) { + selector.select(); + Set selectedKeys = selector.selectedKeys(); + Iterator iter = selectedKeys.iterator(); + while (iter.hasNext()) { + + SelectionKey key = iter.next(); + + if (key.isAcceptable()) { + SocketChannel client = serverSocket.accept(); + client.configureBlocking(false); + client.register(selector, SelectionKey.OP_READ); + } + + if (key.isReadable()) { + SocketChannel client = (SocketChannel) key.channel(); + client.read(buffer); + buffer.flip(); + client.write(buffer); + buffer.clear(); + } + iter.remove(); + } + } + } +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Animal.java b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java new file mode 100644 index 0000000000..3f36243c29 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java @@ -0,0 +1,23 @@ +package com.baeldung.java.reflection; + +public abstract class Animal implements Eating { + + public static final String CATEGORY = "domestic"; + + private String name; + + public Animal(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + protected abstract String getSound(); + +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Bird.java b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java new file mode 100644 index 0000000000..bd6f13094c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java @@ -0,0 +1,36 @@ +package com.baeldung.java.reflection; + +public class Bird extends Animal { + private boolean walks; + + public Bird() { + super("bird"); + } + + public Bird(String name, boolean walks) { + super(name); + setWalks(walks); + } + + public Bird(String name) { + super(name); + } + + @Override + public String eats() { + return "grains"; + } + + @Override + protected String getSound() { + return "chaps"; + } + + public boolean walks() { + return walks; + } + + public void setWalks(boolean walks) { + this.walks = walks; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Eating.java b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java new file mode 100644 index 0000000000..479425cad4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java @@ -0,0 +1,5 @@ +package com.baeldung.java.reflection; + +public interface Eating { + String eats(); +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Goat.java b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java new file mode 100644 index 0000000000..503717ae5e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java @@ -0,0 +1,24 @@ +package com.baeldung.java.reflection; + +public class Goat extends Animal implements Locomotion { + + public Goat(String name) { + super(name); + } + + @Override + protected String getSound() { + return "bleat"; + } + + @Override + public String getLocomotion() { + return "walks"; + } + + @Override + public String eats() { + return "grass"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java new file mode 100644 index 0000000000..047c00cb13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java @@ -0,0 +1,5 @@ +package com.baeldung.java.reflection; + +public interface Locomotion { + String getLocomotion(); +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Person.java b/core-java/src/main/java/com/baeldung/java/reflection/Person.java new file mode 100644 index 0000000000..f3d7f9f001 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Person.java @@ -0,0 +1,6 @@ +package com.baeldung.java.reflection; + +public class Person { + private String name; + private int age; +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java new file mode 100644 index 0000000000..d4a6a0f42e --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java @@ -0,0 +1,65 @@ +package org.baeldung.equalshashcode.entities; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ComplexClass { + + private List genericList; + private Set integerSet; + + public ComplexClass(ArrayList genericArrayList, HashSet integerHashSet) { + super(); + this.genericList = genericArrayList; + this.integerSet = integerHashSet; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((genericList == null) ? 0 : genericList.hashCode()); + result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof ComplexClass)) + return false; + ComplexClass other = (ComplexClass) obj; + if (genericList == null) { + if (other.genericList != null) + return false; + } else if (!genericList.equals(other.genericList)) + return false; + if (integerSet == null) { + if (other.integerSet != null) + return false; + } else if (!integerSet.equals(other.integerSet)) + return false; + return true; + } + + protected List getGenericList() { + return genericList; + } + + protected void setGenericArrayList(List genericList) { + this.genericList = genericList; + } + + protected Set getIntegerSet() { + return integerSet; + } + + protected void setIntegerSet(Set integerSet) { + this.integerSet = integerSet; + } +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java new file mode 100644 index 0000000000..ebe005688c --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -0,0 +1,54 @@ +package org.baeldung.equalshashcode.entities; + +public class PrimitiveClass { + + private boolean primitiveBoolean; + private int primitiveInt; + + public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) { + super(); + this.primitiveBoolean = primitiveBoolean; + this.primitiveInt = primitiveInt; + } + + protected boolean isPrimitiveBoolean() { + return primitiveBoolean; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (primitiveBoolean ? 1231 : 1237); + result = prime * result + primitiveInt; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PrimitiveClass other = (PrimitiveClass) obj; + if (primitiveBoolean != other.primitiveBoolean) + return false; + if (primitiveInt != other.primitiveInt) + return false; + return true; + } + + protected void setPrimitiveBoolean(boolean primitiveBoolean) { + this.primitiveBoolean = primitiveBoolean; + } + + protected int getPrimitiveInt() { + return primitiveInt; + } + + protected void setPrimitiveInt(int primitiveInt) { + this.primitiveInt = primitiveInt; + } +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java new file mode 100644 index 0000000000..1e1423f0b3 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java @@ -0,0 +1,58 @@ +package org.baeldung.equalshashcode.entities; + +public class Rectangle extends Shape { + private double width; + private double length; + + public Rectangle(double width, double length) { + this.width = width; + this.length = length; + } + + @Override + public double area() { + return width * length; + } + + @Override + public double perimeter() { + return 2 * (width + length); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(length); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(width); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Rectangle other = (Rectangle) obj; + if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length)) + return false; + if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width)) + return false; + return true; + } + + protected double getWidth() { + return width; + } + + protected double getLength() { + return length; + } + +} \ No newline at end of file diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java similarity index 51% rename from eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java rename to core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java index 7f779e6ef2..3bfc81da8f 100644 --- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java @@ -1,7 +1,7 @@ package org.baeldung.equalshashcode.entities; public abstract class Shape { - public abstract double area(); + public abstract double area(); - public abstract double perimeter(); + public abstract double perimeter(); } diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java new file mode 100644 index 0000000000..f11e34f0ba --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java @@ -0,0 +1,58 @@ +package org.baeldung.equalshashcode.entities; + +import java.awt.Color; + +public class Square extends Rectangle { + + Color color; + + public Square(double width, Color color) { + super(width, width); + this.color = color; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((color == null) ? 0 : color.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof Square)) { + return false; + } + Square other = (Square) obj; + if (color == null) { + if (other.color != null) { + return false; + } + } else if (!color.equals(other.color)) { + return false; + } + return true; + } + + protected Color getColor() { + return color; + } + + protected void setColor(Color color) { + this.color = color; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java new file mode 100644 index 0000000000..63da2fe2bf --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java @@ -0,0 +1,18 @@ +package com.baeldung.java.nio.selector; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class EchoTest { + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { + EchoClient client = EchoClient.start(); + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java new file mode 100644 index 0000000000..a12a2f205f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java @@ -0,0 +1,326 @@ +package com.baeldung.java.reflection; + +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; +import static org.junit.Assert.*; + +public class ReflectionTest { + + @Test + public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { + Object person = new Person(); + Field[] fields = person.getClass().getDeclaredFields(); + + List actualFieldNames = getFieldNames(fields); + + assertTrue(Arrays.asList("name", "age") + .containsAll(actualFieldNames)); + } + + @Test + public void givenObject_whenGetsClassName_thenCorrect() { + Object goat = new Goat("goat"); + Class clazz = goat.getClass(); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClassName_whenCreatesObject_thenCorrect() + throws ClassNotFoundException { + Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClass_whenRecognisesModifiers_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + int goatMods = goatClass.getModifiers(); + int animalMods = animalClass.getModifiers(); + + assertTrue(Modifier.isPublic(goatMods)); + assertTrue(Modifier.isAbstract(animalMods)); + assertTrue(Modifier.isPublic(animalMods)); + } + + @Test + public void givenClass_whenGetsPackageInfo_thenCorrect() { + Goat goat = new Goat("goat"); + Class goatClass = goat.getClass(); + Package pkg = goatClass.getPackage(); + + assertEquals("com.baeldung.java.reflection", pkg.getName()); + } + + @Test + public void givenClass_whenGetsSuperClass_thenCorrect() { + Goat goat = new Goat("goat"); + String str = "any string"; + + Class goatClass = goat.getClass(); + Class goatSuperClass = goatClass.getSuperclass(); + + assertEquals("Animal", goatSuperClass.getSimpleName()); + assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); + + } + + @Test + public void givenClass_whenGetsImplementedInterfaces_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Class[] goatInterfaces = goatClass.getInterfaces(); + Class[] animalInterfaces = animalClass.getInterfaces(); + + assertEquals(1, goatInterfaces.length); + assertEquals(1, animalInterfaces.length); + assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); + assertEquals("Eating", animalInterfaces[0].getSimpleName()); + } + + @Test + public void givenClass_whenGetsConstructor_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Constructor[] constructors = goatClass.getConstructors(); + + assertEquals(1, constructors.length); + assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); + } + + @Test + public void givenClass_whenGetsFields_thenCorrect() + throws ClassNotFoundException { + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Field[] fields = animalClass.getDeclaredFields(); + + List actualFields = getFieldNames(fields); + + assertEquals(2, actualFields.size()); + assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); + } + + @Test + public void givenClass_whenGetsMethods_thenCorrect() + throws ClassNotFoundException { + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Method[] methods = animalClass.getDeclaredMethods(); + List actualMethods = getMethodNames(methods); + + assertEquals(4, actualMethods.size()); + assertTrue(actualMethods.containsAll(Arrays.asList("getName", + "setName", "getSound"))); + } + + @Test + public void givenClass_whenGetsAllConstructors_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Constructor[] constructors = birdClass.getConstructors(); + + assertEquals(3, constructors.length); + } + + @Test + public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Constructor cons1 = birdClass.getConstructor(); + Constructor cons2 = birdClass.getConstructor(String.class); + Constructor cons3 = birdClass.getConstructor(String.class, + boolean.class); + } + + @Test + public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + + Constructor cons1 = birdClass.getConstructor(); + Constructor cons2 = birdClass.getConstructor(String.class); + Constructor cons3 = birdClass.getConstructor(String.class, + boolean.class); + + Bird bird1 = (Bird) cons1.newInstance(); + Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); + Bird bird3 = (Bird) cons3.newInstance("dove", true); + + assertEquals("bird", bird1.getName()); + assertEquals("Weaver bird", bird2.getName()); + assertEquals("dove", bird3.getName()); + assertFalse(bird1.walks()); + assertTrue(bird3.walks()); + } + + @Test + public void givenClass_whenGetsPublicFields_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field[] fields = birdClass.getFields(); + assertEquals(1, fields.length); + assertEquals("CATEGORY", fields[0].getName()); + + } + + @Test + public void givenClass_whenGetsPublicFieldByName_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getField("CATEGORY"); + assertEquals("CATEGORY", field.getName()); + + } + + @Test + public void givenClass_whenGetsDeclaredFields_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field[] fields = birdClass.getDeclaredFields(); + assertEquals(1, fields.length); + assertEquals("walks", fields[0].getName()); + } + + @Test + public void givenClass_whenGetsFieldsByName_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getDeclaredField("walks"); + assertEquals("walks", field.getName()); + + } + + @Test + public void givenClassField_whenGetsType_thenCorrect() + throws Exception { + Field field = Class.forName("com.baeldung.java.reflection.Bird") + .getDeclaredField("walks"); + Class fieldClass = field.getType(); + assertEquals("boolean", fieldClass.getSimpleName()); + } + + @Test + public void givenClassField_whenSetsAndGetsValue_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Bird bird = (Bird) birdClass.newInstance(); + Field field = birdClass.getDeclaredField("walks"); + field.setAccessible(true); + + assertFalse(field.getBoolean(bird)); + assertFalse(bird.walks()); + + field.set(bird, true); + + assertTrue(field.getBoolean(bird)); + assertTrue(bird.walks()); + + } + + @Test + public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getField("CATEGORY"); + field.setAccessible(true); + + assertEquals("domestic", field.get(null)); + } + + @Test + public void givenClass_whenGetsAllPublicMethods_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Method[] methods = birdClass.getMethods(); + List methodNames = getMethodNames(methods); + + assertTrue(methodNames.containsAll(Arrays + .asList("equals", "notifyAll", "hashCode", + "walks", "eats", "toString"))); + + } + + @Test + public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); + + List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); + + assertEquals(expectedMethodNames.size(), actualMethodNames.size()); + assertTrue(expectedMethodNames.containsAll(actualMethodNames)); + assertTrue(actualMethodNames.containsAll(expectedMethodNames)); + + } + + @Test + public void givenMethodName_whenGetsMethod_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Method walksMethod = birdClass.getDeclaredMethod("walks"); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", + boolean.class); + + assertFalse(walksMethod.isAccessible()); + assertFalse(setWalksMethod.isAccessible()); + + walksMethod.setAccessible(true); + setWalksMethod.setAccessible(true); + + assertTrue(walksMethod.isAccessible()); + assertTrue(setWalksMethod.isAccessible()); + + } + + @Test + public void givenMethod_whenInvokes_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Bird bird = (Bird) birdClass.newInstance(); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", + boolean.class); + Method walksMethod = birdClass.getDeclaredMethod("walks"); + boolean walks = (boolean) walksMethod.invoke(bird); + + assertFalse(walks); + assertFalse(bird.walks()); + + setWalksMethod.invoke(bird, true); + boolean walks2 = (boolean) walksMethod.invoke(bird); + + assertTrue(walks2); + assertTrue(bird.walks()); + + } + + private static List getFieldNames(Field[] fields) { + List fieldNames = new ArrayList<>(); + for (Field field : fields) + fieldNames.add(field.getName()); + return fieldNames; + + } + + private static List getMethodNames(Method[] methods) { + List methodNames = new ArrayList<>(); + for (Method method : methods) + methodNames.add(method.getName()); + return methodNames; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java new file mode 100644 index 0000000000..414401eb85 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java @@ -0,0 +1,502 @@ +package com.baeldung.java.regex; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class RegexTest { + private static Pattern pattern; + private static Matcher matcher; + + @Test + public void givenText_whenSimpleRegexMatches_thenCorrect() { + Pattern pattern = Pattern.compile("foo"); + Matcher matcher = pattern.matcher("foo"); + assertTrue(matcher.find()); + } + + @Test + public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() { + Pattern pattern = Pattern.compile("foo"); + Matcher matcher = pattern.matcher("foofoo"); + int matches = 0; + while (matcher.find()) + matches++; + assertEquals(matches, 2); + + } + + @Test + public void givenText_whenMatchesWithDotMetach_thenCorrect() { + int matches = runTest(".", "foo"); + assertTrue(matches > 0); + } + + @Test + public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() { + int matches = runTest("foo.", "foofoo"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenORSet_whenMatchesAny_thenCorrect() { + int matches = runTest("[abc]", "b"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenORSet_whenMatchesAnyAndAll_thenCorrect() { + int matches = runTest("[abc]", "cab"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenORSet_whenMatchesAllCombinations_thenCorrect() { + int matches = runTest("[bcr]at", "bat cat rat"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenNORSet_whenMatchesNon_thenCorrect() { + int matches = runTest("[^abc]", "g"); + assertTrue(matches > 0); + } + + @Test + public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() { + int matches = runTest("[^bcr]at", "sat mat eat"); + assertTrue(matches > 0); + } + + @Test + public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() { + int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() { + int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 26); + } + + @Test + public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() { + int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 28); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect() { + int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect2() { + int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenTwoSets_whenMatchesUnion_thenCorrect() { + int matches = runTest("[1-3[7-9]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 6); + } + + @Test + public void givenTwoSets_whenMatchesIntersection_thenCorrect() { + int matches = runTest("[1-6&&[3-9]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 4); + } + + @Test + public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() { + int matches = runTest("[0-9&&[^2468]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 5); + } + + @Test + public void givenDigits_whenMatches_thenCorrect() { + int matches = runTest("\\d", "123"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenNonDigits_whenMatches_thenCorrect() { + int matches = runTest("\\D", "a6c"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenWhiteSpace_whenMatches_thenCorrect() { + int matches = runTest("\\s", "a c"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenNonWhiteSpace_whenMatches_thenCorrect() { + int matches = runTest("\\S", "a c"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenWordCharacter_whenMatches_thenCorrect() { + int matches = runTest("\\w", "hi!"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenNonWordCharacter_whenMatches_thenCorrect() { + int matches = runTest("\\W", "hi!"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a?", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{0,1}", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a*", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{0,}", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a+", "hi"); + assertFalse(matches > 0); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{1,}", "hi"); + assertFalse(matches > 0); + } + + @Test + public void givenBraceQuantifier_whenMatches_thenCorrect() { + int matches = runTest("a{3}", "aaaaaa"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() { + int matches = runTest("a{3}", "aa"); + assertFalse(matches > 0); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() { + int matches = runTest("a{2,3}", "aaaa"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() { + int matches = runTest("a{2,3}?", "aaaa"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect() { + int matches = runTest("(\\d\\d)", "12"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect2() { + int matches = runTest("(\\d\\d)", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect3() { + int matches = runTest("(\\d\\d)(\\d\\d)", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() { + int matches = runTest("(\\d\\d)\\1", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() { + int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() { + int matches = runTest("(\\d\\d)\\1", "1213"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtBeginning_thenCorrect() { + int matches = runTest("^dog", "dogs are friendly"); + assertTrue(matches > 0); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() { + int matches = runTest("^dog", "are dogs are friendly?"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtEnd_thenCorrect() { + int matches = runTest("dog$", "Man's best friend is a dog"); + assertTrue(matches > 0); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() { + int matches = runTest("dog$", "is a dog man's best friend?"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect() { + int matches = runTest("\\bdog\\b", "a dog is friendly"); + assertTrue(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect2() { + int matches = runTest("\\bdog\\b", "dog is man's best friend"); + assertTrue(matches > 0); + } + + @Test + public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() { + int matches = runTest("\\bdog\\b", "snoop dogg is a rapper"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() { + int matches = runTest("\\bdog\\B", "snoop dogg is a rapper"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() { + int matches = runTest("\u00E9", "\u0065\u0301"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() { + int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() { + int matches = runTest("dog", "This is a Dog"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + int matches = runTest("(?i)dog", "This is a Dog"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() { + int matches = runTest("dog$ #check for word dog at end of text", "This is a dog"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() { + int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() { + int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(?s)(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text"); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text", Pattern.LITERAL); + assertFalse(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() { + int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertFalse(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() { + int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() { + int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertTrue(matches > 0); + } + + @Test + public void givenMatch_whenGetsIndices_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("This dog is mine"); + matcher.find(); + assertEquals(5, matcher.start()); + assertEquals(8, matcher.end()); + } + + @Test + public void whenStudyMethodsWork_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are friendly"); + assertTrue(matcher.lookingAt()); + assertFalse(matcher.matches()); + + } + + @Test + public void whenMatchesStudyMethodWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dog"); + assertTrue(matcher.matches()); + + } + + @Test + public void whenReplaceFirstWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceFirst("cat"); + assertEquals("cats are domestic animals, dogs are friendly", newStr); + + } + + @Test + public void whenReplaceAllWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceAll("cat"); + assertEquals("cats are domestic animals, cats are friendly", newStr); + + } + + public synchronized static int runTest(String regex, String text) { + pattern = Pattern.compile(regex); + matcher = pattern.matcher(text); + int matches = 0; + while (matcher.find()) + matches++; + return matches; + } + + public synchronized static int runTest(String regex, String text, int flags) { + pattern = Pattern.compile(regex, flags); + matcher = pattern.matcher(text); + int matches = 0; + while (matcher.find()) + matches++; + return matches; + } +} + diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java new file mode 100644 index 0000000000..23be2200d3 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java @@ -0,0 +1,57 @@ +package org.baeldung.core.exceptions; + +import org.apache.log4j.Logger; +import org.junit.Test; + +import java.io.*; + +public class FileNotFoundExceptionTest { + + private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class); + + private String fileName = Double.toString(Math.random()); + + @Test(expected = BusinessException.class) + public void raiseBusinessSpecificException() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + throw new BusinessException("BusinessException: necessary file was not present.", ex); + } + } + + @Test + public void createFile() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + try { + new File(fileName).createNewFile(); + readFailingFile(); + } catch (IOException ioe) { + throw new RuntimeException("BusinessException: even creation is not possible.", ioe); + } + } + } + + @Test + public void logError() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + LOG.error("Optional file " + fileName + " was not found.", ex); + } + } + + private void readFailingFile() throws IOException { + BufferedReader rd = new BufferedReader(new FileReader(new File(fileName))); + rd.readLine(); + // no need to close file + } + + private class BusinessException extends RuntimeException { + BusinessException(String string, FileNotFoundException ex) { + super(string, ex); + } + } +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java new file mode 100644 index 0000000000..75d96e5989 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java @@ -0,0 +1,33 @@ +package org.baeldung.equalshashcode.entities; + +import java.util.ArrayList; +import java.util.HashSet; + +import org.junit.Assert; +import org.junit.Test; + +public class ComplexClassTest { + + @Test + public void testEqualsAndHashcodes() { + + ArrayList strArrayList = new ArrayList(); + strArrayList.add("abc"); + strArrayList.add("def"); + ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45, 67)); + ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45, 67)); + + ArrayList strArrayListD = new ArrayList(); + strArrayListD.add("lmn"); + strArrayListD.add("pqr"); + ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45, 67)); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java new file mode 100644 index 0000000000..16f25ae021 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java @@ -0,0 +1,23 @@ +package org.baeldung.equalshashcode.entities; + +import org.junit.Assert; +import org.junit.Test; + +public class PrimitiveClassTest { + + @Test + public void testTwoEqualsObjects() { + + PrimitiveClass aObject = new PrimitiveClass(false, 2); + PrimitiveClass bObject = new PrimitiveClass(false, 2); + PrimitiveClass dObject = new PrimitiveClass(true, 2); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java new file mode 100644 index 0000000000..52d024a696 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java @@ -0,0 +1,26 @@ +package org.baeldung.equalshashcode.entities; + +import java.awt.Color; + +import org.junit.Assert; +import org.junit.Test; + +public class SquareClassTest { + + @Test + public void testEqualsAndHashcodes() { + + Square aObject = new Square(10, Color.BLUE); + Square bObject = new Square(10, Color.BLUE); + + Square dObject = new Square(20, Color.BLUE); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java index 4996a1f0a2..30b0111555 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java @@ -1,63 +1,65 @@ package org.baeldung.java.collections; +import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import java.util.*; import java.util.stream.*; +import static java.util.stream.Collectors.*; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.*; public class ArrayListTest { - List stringsToSearch; + private List stringsToSearch; @Before public void setUp() { - List xs = LongStream.range(0, 16) - .boxed() - .map(Long::toHexString) - .collect(Collectors.toList()); - stringsToSearch = new ArrayList<>(xs); - stringsToSearch.addAll(xs); + List list = LongStream.range(0, 16) + .boxed() + .map(Long::toHexString) + .collect(toCollection(ArrayList::new)); + stringsToSearch = new ArrayList<>(list); + stringsToSearch.addAll(list); } @Test public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() { - List xs = new ArrayList<>(); - assertTrue(xs.isEmpty()); + List list = new ArrayList<>(); + assertTrue(list.isEmpty()); } @Test public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { Collection numbers = - IntStream.range(0, 10).boxed().collect(Collectors.toSet()); + IntStream.range(0, 10).boxed().collect(toSet()); - List xs = new ArrayList<>(numbers); - assertEquals(10, xs.size()); - assertTrue(numbers.containsAll(xs)); + List list = new ArrayList<>(numbers); + assertEquals(10, list.size()); + assertTrue(numbers.containsAll(list)); } @Test public void givenElement_whenAddToArrayList_thenIsAdded() { - List xs = new ArrayList<>(); + List list = new ArrayList<>(); - xs.add(1L); - xs.add(2L); - xs.add(1, 3L); + list.add(1L); + list.add(2L); + list.add(1, 3L); - assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs)); + assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list)); } @Test public void givenCollection_whenAddToArrayList_thenIsAdded() { - List xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); - Collection ys = LongStream.range(4, 10).boxed().collect(Collectors.toList()); - xs.addAll(0, ys); + List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); + LongStream.range(4, 10).boxed() + .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); - assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs)); + assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list)); } @Test @@ -87,9 +89,9 @@ public class ArrayListTest { Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); List result = stringsToSearch - .stream() - .filter(matchingStrings::contains) - .collect(Collectors.toList()); + .stream() + .filter(matchingStrings::contains) + .collect(toCollection(ArrayList::new)); assertEquals(6, result.size()); } @@ -104,37 +106,33 @@ public class ArrayListTest { @Test public void givenIndex_whenRemove_thenCorrectElementRemoved() { - List xs = new ArrayList<>( - IntStream.range(0, 10).boxed().collect(Collectors.toList()) - ); - Collections.reverse(xs); + List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + Collections.reverse(list); - xs.remove(0); - assertThat(xs.get(0), equalTo(8)); + list.remove(0); + assertThat(list.get(0), equalTo(8)); - xs.remove(Integer.valueOf(0)); - assertFalse(xs.contains(0)); + list.remove(Integer.valueOf(0)); + assertFalse(list.contains(0)); } @Test public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() { - List xs = new ArrayList<>( - IntStream.range(0, 10).boxed().collect(Collectors.toList()) - ); - ListIterator it = xs.listIterator(xs.size()); - List result = new ArrayList<>(xs.size()); + List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + ListIterator it = list.listIterator(list.size()); + List result = new ArrayList<>(list.size()); while (it.hasPrevious()) { result.add(it.previous()); } - Collections.reverse(xs); - assertThat(result, equalTo(xs)); + Collections.reverse(list); + assertThat(result, equalTo(list)); } @Test public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() { Set matchingStrings - = new HashSet<>(Arrays.asList("a", "b", "c", "d", "e", "f")); + = Sets.newHashSet("a", "b", "c", "d", "e", "f"); Iterator it = stringsToSearch.iterator(); while (it.hasNext()) { diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java new file mode 100644 index 0000000000..83f1fb33b6 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java @@ -0,0 +1,90 @@ +package org.baeldung.java.md5; + +import static org.junit.Assert.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +import java.io.File; +import java.io.IOException; +import java.nio.*; +import static org.assertj.core.api.Assertions.assertThat; + + +public class JavaMD5Test { + + + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + + + @Test + public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(password.getBytes()); + byte[] digest = md.digest(); + String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myHash.equals(hash)).isTrue(); + } + + @Test + public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter + .printHexBinary(digest).toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + @Test + public void givenPassword_whenHashingUsingCommons_thenVerifying() { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + String md5Hex = DigestUtils + .md5Hex(password).toUpperCase(); + + assertThat(md5Hex.equals(hash)).isTrue(); + } + + + @Test + public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + HashCode hash = com.google.common.io.Files + .hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString() + .toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + +} diff --git a/core-java/src/test/resources/test_md5.txt b/core-java/src/test/resources/test_md5.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/core-java/src/test/resources/test_md5.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java deleted file mode 100644 index d593aac52d..0000000000 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.couchbase; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase"}) -public class IntegrationTestConfig { -} diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-intro/mvnw b/couchbase-sdk-intro/mvnw deleted file mode 100755 index a1ba1bf554..0000000000 --- a/couchbase-sdk-intro/mvnw +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/couchbase-sdk-intro/mvnw.cmd b/couchbase-sdk-intro/mvnw.cmd deleted file mode 100644 index 2b934e89dd..0000000000 --- a/couchbase-sdk-intro/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% \ No newline at end of file diff --git a/couchbase-sdk-intro/pom.xml b/couchbase-sdk-intro/pom.xml deleted file mode 100644 index 1c2ca5ee05..0000000000 --- a/couchbase-sdk-intro/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - com.baeldung - couchbase-sdk-intro - 0.1-SNAPSHOT - jar - couchbase-sdk-intro - Intro to the Couchbase SDK - - - - - com.couchbase.client - java-client - ${couchbase.client.version} - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 2.2.6 - - - diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-spring-service/mvnw b/couchbase-sdk-spring-service/mvnw deleted file mode 100755 index a1ba1bf554..0000000000 --- a/couchbase-sdk-spring-service/mvnw +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/couchbase-sdk-spring-service/mvnw.cmd b/couchbase-sdk-spring-service/mvnw.cmd deleted file mode 100644 index 2b934e89dd..0000000000 --- a/couchbase-sdk-spring-service/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% \ No newline at end of file diff --git a/couchbase-sdk-spring-service/pom.xml b/couchbase-sdk-spring-service/pom.xml deleted file mode 100644 index d344f8c756..0000000000 --- a/couchbase-sdk-spring-service/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - 4.0.0 - com.baeldung - couchbase-sdk-spring-service - 0.1-SNAPSHOT - jar - couchbase-sdk-spring-service - Intro to the Couchbase SDK - - - - - com.couchbase.client - java-client - ${couchbase.client.version} - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-context-support - ${spring-framework.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - org.springframework - spring-test - ${spring-framework.version} - test - - - junit - junit - ${junit.version} - test - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 2.2.6 - 4.2.4.RELEASE - 1.1.3 - 1.7.12 - 4.11 - 3.4 - - - diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java b/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java deleted file mode 100644 index 8210c10b3a..0000000000 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.couchbase.person; - -import org.springframework.stereotype.Service; - -import com.baeldung.couchbase.service.JsonDocumentConverter; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; - -@Service -public class FluentPersonDocumentConverter implements JsonDocumentConverter { - - @Override - public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); - return JsonDocument.create(p.getId(), content); - } - - @Override - public Person fromDocument(JsonDocument doc) { - JsonObject content = doc.content(); - return Person.Builder.newInstance() - .id(doc.id()) - .type("Person") - .name(content.getString("name")) - .homeTown(content.getString("homeTown")) - .build(); - } -} diff --git a/couchbase-sdk-spring-service/src/main/resources/logback.xml b/couchbase-sdk-spring-service/src/main/resources/logback.xml deleted file mode 100644 index efcc6fb4c7..0000000000 --- a/couchbase-sdk-spring-service/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - \ No newline at end of file diff --git a/couchbase-sdk/README.md b/couchbase-sdk/README.md new file mode 100644 index 0000000000..9cdcdea012 --- /dev/null +++ b/couchbase-sdk/README.md @@ -0,0 +1,50 @@ +## Couchbase SDK Tutorial Project + +### Relevant Articles: +- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk) +- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) +- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) + +### Overview +This Maven project contains the Java code for the Couchbase entities and Spring services +as described in the tutorials, as well as a unit/integration test +for each service implementation. + +### Working with the Code +The project was developed and tested using Java 7 and 8 in the Eclipse-based +Spring Source Toolkit (STS) and therefore should run fine in any +recent version of Eclipse or another IDE of your choice +that supports Java 7 or later. + +### Building the Project +You can also build the project using Maven outside of any IDE: +``` +mvn clean install +``` + +### Package Organization +Java classes for the intro tutorial are in the +org.baeldung.couchbase.intro package. + +Java classes for the Spring service tutorial are in the +org.baeldung.couchbase.spring package hierarchy. + +Java classes for the Asynchronous Couchbase tutorial are in the +org.baeldung.couchbase.async package hierarchy. + + +### Running the tests +The test classes for the Spring service tutorial are: +- org.baeldung.couchbase.spring.service.ClusterServiceTest +- org.baeldung.couchbase.spring.person.PersonCrudServiceTest + +The test classes for the Asynchronous Couchbase tutorial are in the +org.baeldung.couchbase.async package hierarchy: +- org.baeldung.couchbase.async.service.ClusterServiceTest +- org.baeldung.couchbase.async.person.PersonCrudServiceTest + +The test classes may be run as JUnit tests from your IDE +or using the Maven command line: +``` +mvn test +``` diff --git a/couchbase-sdk-async/mvnw b/couchbase-sdk/mvnw similarity index 100% rename from couchbase-sdk-async/mvnw rename to couchbase-sdk/mvnw diff --git a/couchbase-sdk-async/mvnw.cmd b/couchbase-sdk/mvnw.cmd similarity index 100% rename from couchbase-sdk-async/mvnw.cmd rename to couchbase-sdk/mvnw.cmd diff --git a/couchbase-sdk-async/pom.xml b/couchbase-sdk/pom.xml similarity index 95% rename from couchbase-sdk-async/pom.xml rename to couchbase-sdk/pom.xml index 9062ef8e15..4c277f4c85 100644 --- a/couchbase-sdk-async/pom.xml +++ b/couchbase-sdk/pom.xml @@ -3,11 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - couchbase-sdk-async + couchbase-sdk 0.1-SNAPSHOT jar - couchbase-sdk-async - Couchbase SDK Asynchronous Operations + couchbase-sdk + Couchbase SDK Tutorials diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java similarity index 70% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java index 4d2500197b..16e1876719 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async; public interface CouchbaseEntity { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java similarity index 94% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java index bf248c3999..32ed2ebbe4 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java @@ -1,6 +1,6 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; -import com.baeldung.couchbase.service.CouchbaseEntity; +import com.baeldung.couchbase.async.CouchbaseEntity; public class Person implements CouchbaseEntity { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java similarity index 77% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java index d5302bd6db..b2ef985725 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import javax.annotation.PostConstruct; @@ -6,8 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.AbstractCrudService; -import com.baeldung.couchbase.service.BucketService; +import com.baeldung.couchbase.async.service.AbstractCrudService; +import com.baeldung.couchbase.async.service.BucketService; @Service public class PersonCrudService extends AbstractCrudService { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java similarity index 88% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java index cfb20a2bfb..8646cf247a 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.JsonDocumentConverter; +import com.baeldung.couchbase.async.service.JsonDocumentConverter; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java index 53af1c4041..926cd7f4e8 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java index 08acf5deed..cbc03cbcda 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java similarity index 98% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java index ce95074015..861e2404e5 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.ArrayList; import java.util.List; @@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.baeldung.couchbase.async.CouchbaseEntity; import com.couchbase.client.core.BackpressureException; import com.couchbase.client.core.time.Delay; import com.couchbase.client.java.AsyncBucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java similarity index 69% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java index df9156d87d..28470be99f 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java similarity index 74% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java index 437ec00ff4..ee67405b12 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java similarity index 95% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index c8ff56269d..7ce75d21f5 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java similarity index 89% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java index e0f0831abb..5bd0e52214 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.List; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java similarity index 79% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java index 87331d2a17..85e14a87ce 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 2e40321272..459585d995 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import javax.annotation.PostConstruct; diff --git a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java similarity index 98% rename from couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java index 088f7af7b1..2cb9e1f4f7 100644 --- a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.examples; +package com.baeldung.couchbase.intro; import java.util.List; import java.util.UUID; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java similarity index 97% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java index 48b7a38780..0348ba1e5f 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; public class Person { diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java similarity index 88% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java index 0203bf30bb..de035f1d2c 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import java.util.List; import java.util.UUID; @@ -8,8 +8,9 @@ import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.CrudService; -import com.baeldung.couchbase.service.TutorialBucketService;import com.couchbase.client.java.Bucket; +import com.baeldung.couchbase.spring.service.CrudService; +import com.baeldung.couchbase.spring.service.TutorialBucketService; +import com.couchbase.client.java.Bucket; import com.couchbase.client.java.ReplicaMode; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java similarity index 88% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java index cfb20a2bfb..030c9fde27 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.JsonDocumentConverter; +import com.baeldung.couchbase.spring.service.JsonDocumentConverter; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java similarity index 93% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java index 53af1c4041..5ffe7acf24 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java similarity index 69% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java index c2562dd38e..97ff1e4fd5 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java similarity index 90% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java index 4713893899..a8543fbd91 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import java.util.List; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java similarity index 98% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java index 3c355d2a27..3499fa956e 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import java.util.ArrayList; import java.util.List; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java similarity index 82% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java index 20ee851b39..f683b9f562 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; public interface CrudService { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java similarity index 79% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java index 87331d2a17..cf4861fbeb 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java similarity index 93% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java index 903a568399..8a28deb1d6 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import javax.annotation.PostConstruct; diff --git a/couchbase-sdk-async/src/main/resources/application.properties b/couchbase-sdk/src/main/resources/application.properties similarity index 100% rename from couchbase-sdk-async/src/main/resources/application.properties rename to couchbase-sdk/src/main/resources/application.properties diff --git a/couchbase-sdk-async/src/main/resources/logback.xml b/couchbase-sdk/src/main/resources/logback.xml similarity index 100% rename from couchbase-sdk-async/src/main/resources/logback.xml rename to couchbase-sdk/src/main/resources/logback.xml diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java similarity index 74% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java index d1cc807f7a..3079fc928a 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.async; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class IntegrationTest { +public abstract class AsyncIntegrationTest { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java new file mode 100644 index 0000000000..6afdfe04bd --- /dev/null +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.couchbase.async; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages={"com.baeldung.couchbase.async"}) +public class AsyncIntegrationTestConfig { +} diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java similarity index 93% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java index 3da282492c..afc5bbd53b 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import static org.junit.Assert.*; @@ -13,12 +13,15 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.service.BucketService; +import com.baeldung.couchbase.async.AsyncIntegrationTest; +import com.baeldung.couchbase.async.person.Person; +import com.baeldung.couchbase.async.person.PersonCrudService; +import com.baeldung.couchbase.async.person.PersonDocumentConverter; +import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceTest extends IntegrationTest { +public class PersonCrudServiceTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java similarity index 73% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java index 7795f41c93..8ecb51a4b9 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import static org.junit.Assert.*; @@ -10,14 +10,15 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.IntegrationTestConfig; +import com.baeldung.couchbase.async.AsyncIntegrationTest; +import com.baeldung.couchbase.async.AsyncIntegrationTestConfig; +import com.baeldung.couchbase.async.service.ClusterService; import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends IntegrationTest { +public class ClusterServiceTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java similarity index 93% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java index d1cc807f7a..9c0b0a50c1 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.spring; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java similarity index 63% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java index d593aac52d..ac71911b9b 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java @@ -1,9 +1,9 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase"}) +@ComponentScan(basePackages={"com.baeldung.couchbase.spring"}) public class IntegrationTestConfig { } diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java similarity index 96% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java index e19e90769c..601b261f6e 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import static org.junit.Assert.*; @@ -8,7 +8,7 @@ import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.baeldung.couchbase.IntegrationTest; +import com.baeldung.couchbase.spring.IntegrationTest; public class PersonCrudServiceTest extends IntegrationTest { diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java similarity index 87% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java index 7795f41c93..d1968e1c04 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import static org.junit.Assert.*; @@ -10,8 +10,8 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.IntegrationTestConfig; +import com.baeldung.couchbase.spring.IntegrationTest; +import com.baeldung.couchbase.spring.IntegrationTestConfig; import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java deleted file mode 100644 index f8c85ab8b5..0000000000 --- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -import java.util.ArrayList; -import java.util.HashSet; - -public class ComplexClass { - - private ArrayList genericArrayList; - private HashSet integerHashSet; - - public ComplexClass(ArrayList genericArrayList, - HashSet integerHashSet) { - super(); - this.genericArrayList = genericArrayList; - this.integerHashSet = integerHashSet; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((genericArrayList == null) ? 0 : genericArrayList.hashCode()); - result = prime * result - + ((integerHashSet == null) ? 0 : integerHashSet.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof ComplexClass)) - return false; - ComplexClass other = (ComplexClass) obj; - if (genericArrayList == null) { - if (other.genericArrayList != null) - return false; - } else if (!genericArrayList.equals(other.genericArrayList)) - return false; - if (integerHashSet == null) { - if (other.integerHashSet != null) - return false; - } else if (!integerHashSet.equals(other.integerHashSet)) - return false; - return true; - } - - protected ArrayList getGenericArrayList() { - return genericArrayList; - } - - protected void setGenericArrayList(ArrayList genericArrayList) { - this.genericArrayList = genericArrayList; - } - - protected HashSet getIntegerHashSet() { - return integerHashSet; - } - - protected void setIntegerHashSet(HashSet integerHashSet) { - this.integerHashSet = integerHashSet; - } -} diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java deleted file mode 100644 index 6cd4af5fdb..0000000000 --- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -public class PrimitiveClass { - - private boolean primitiveBoolean; - private int primitiveInt; - - public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) { - super(); - this.primitiveBoolean = primitiveBoolean; - this.primitiveInt = primitiveInt; - } - - protected boolean isPrimitiveBoolean() { - return primitiveBoolean; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (primitiveBoolean ? 1231 : 1237); - result = prime * result + primitiveInt; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PrimitiveClass other = (PrimitiveClass) obj; - if (primitiveBoolean != other.primitiveBoolean) - return false; - if (primitiveInt != other.primitiveInt) - return false; - return true; - } - - protected void setPrimitiveBoolean(boolean primitiveBoolean) { - this.primitiveBoolean = primitiveBoolean; - } - - protected int getPrimitiveInt() { - return primitiveInt; - } - - protected void setPrimitiveInt(int primitiveInt) { - this.primitiveInt = primitiveInt; - } -} diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java deleted file mode 100644 index 61d20cbb05..0000000000 --- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -public class Rectangle extends Shape { - private double width; - private double length; - - public Rectangle(double width, double length) { - this.width = width; - this.length = length; - } - - @Override - public double area() { - // A = w * l - return width * length; - } - - @Override - public double perimeter() { - // P = 2(w + l) - return 2 * (width + length); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(length); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(width); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Rectangle other = (Rectangle) obj; - if (Double.doubleToLongBits(length) != Double - .doubleToLongBits(other.length)) - return false; - if (Double.doubleToLongBits(width) != Double - .doubleToLongBits(other.width)) - return false; - return true; - } - - protected double getWidth() { - return width; - } - - protected double getLength() { - return length; - } - -} \ No newline at end of file diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java deleted file mode 100644 index 0bebc1e380..0000000000 --- a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -import java.awt.Color; - -public class Square extends Rectangle { - - Color color; - - public Square(double width, Color color) { - super(width, width); - this.color = color; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((color == null) ? 0 : color.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Square other = (Square) obj; - if (color == null) { - if (other.color != null) - return false; - } else if (!color.equals(other.color)) - return false; - return true; - } - - protected Color getColor() { - return color; - } - - protected void setColor(Color color) { - this.color = color; - } - -} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java deleted file mode 100644 index 2cca44bb9e..0000000000 --- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -import java.util.ArrayList; -import java.util.HashSet; - -import org.junit.Assert; -import org.junit.Test; - -public class ComplexClassTest { - - @Test - public void testEqualsAndHashcodes() { - - ArrayList strArrayList = new ArrayList(); - strArrayList.add("abc"); - strArrayList.add("def"); - ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45,67)); - ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45,67)); - ComplexClass cObject = new ComplexClass(strArrayList, new HashSet(45,67)); - - ArrayList strArrayListD = new ArrayList(); - strArrayListD.add("lmn"); - strArrayListD.add("pqr"); - ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45,67)); - - // equals() - Assert.assertTrue(aObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject)); - Assert.assertTrue(bObject.equals(cObject)); - Assert.assertTrue(aObject.equals(cObject)); - // hashCode() - Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); - // non-equal objects are not equals() and have different hashCode() - Assert.assertFalse(aObject.equals(dObject)); - Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); - } - -} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java deleted file mode 100644 index 009753d1ae..0000000000 --- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -import org.junit.Assert; -import org.junit.Test; - -public class PrimitiveClassTest { - - @Test - public void testTwoEqualsObjects() { - - PrimitiveClass aObject = new PrimitiveClass(false, 2); - PrimitiveClass bObject = new PrimitiveClass(false, 2); - PrimitiveClass cObject = new PrimitiveClass(false, 2); - PrimitiveClass dObject = new PrimitiveClass(true, 2); - - // equals() - Assert.assertTrue(aObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject)); - Assert.assertTrue(bObject.equals(cObject)); - Assert.assertTrue(aObject.equals(cObject)); - // hashCode() - Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); - // non-equal objects are not equals() and have different hashCode() - Assert.assertFalse(aObject.equals(dObject)); - Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); - } - -} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java deleted file mode 100644 index 1290f57c6d..0000000000 --- a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.equalshashcode.entities; - -import java.awt.Color; - -import org.junit.Assert; -import org.junit.Test; - -public class SquareClassTest { - - @Test - public void testEqualsAndHashcodes() { - - Square aObject = new Square(10, Color.BLUE); - Square bObject = new Square(10, Color.BLUE); - Square cObject = new Square(10, Color.BLUE); - - Square dObject = new Square(20, Color.BLUE); - - // equals() - Assert.assertTrue(aObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); - Assert.assertTrue(aObject.equals(bObject)); - Assert.assertTrue(bObject.equals(cObject)); - Assert.assertTrue(aObject.equals(cObject)); - // hashCode() - Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); - // non-equal objects are not equals() and have different hashCode() - Assert.assertFalse(aObject.equals(dObject)); - Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); - } - -} diff --git a/feign-client/README.md b/feign-client/README.md new file mode 100644 index 0000000000..e6ade4d161 --- /dev/null +++ b/feign-client/README.md @@ -0,0 +1,5 @@ +## Feign Hypermedia Client ## + +This is the implementation of a [spring-hypermedia-api][1] client using Feign. + +[1]: https://github.com/eugenp/spring-hypermedia-api diff --git a/feign-client/pom.xml b/feign-client/pom.xml new file mode 100644 index 0000000000..af61883f1b --- /dev/null +++ b/feign-client/pom.xml @@ -0,0 +1,99 @@ + + + 4.0.0 + + com.baeldung.feign + feign-client + 1.0.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + io.github.openfeign + feign-core + 9.3.1 + + + io.github.openfeign + feign-okhttp + 9.3.1 + + + io.github.openfeign + feign-gson + 9.3.1 + + + io.github.openfeign + feign-slf4j + 9.3.1 + + + org.slf4j + slf4j-api + 1.7.21 + + + org.apache.logging.log4j + log4j-core + 2.6.2 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.6.2 + + + org.projectlombok + lombok + 1.16.10 + provided + + + junit + junit + 4.12 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + true + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java new file mode 100644 index 0000000000..9c0c359d88 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -0,0 +1,26 @@ +package com.baeldung.feign; + +import com.baeldung.feign.clients.BookClient; +import feign.Feign; +import feign.Logger; +import feign.gson.GsonDecoder; +import feign.gson.GsonEncoder; +import feign.okhttp.OkHttpClient; +import feign.slf4j.Slf4jLogger; +import lombok.Getter; + +@Getter +public class BookControllerFeignClientBuilder { + private BookClient bookClient = createClient(BookClient.class, + "http://localhost:8081/api/books"); + + private static T createClient(Class type, String uri) { + return Feign.builder() + .client(new OkHttpClient()) + .encoder(new GsonEncoder()) + .decoder(new GsonDecoder()) + .logger(new Slf4jLogger(type)) + .logLevel(Logger.Level.FULL) + .target(type, uri); + } +} diff --git a/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java b/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java new file mode 100644 index 0000000000..df20ef8f93 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java @@ -0,0 +1,21 @@ +package com.baeldung.feign.clients; + +import com.baeldung.feign.models.Book; +import com.baeldung.feign.models.BookResource; +import feign.Headers; +import feign.Param; +import feign.RequestLine; + +import java.util.List; + +public interface BookClient { + @RequestLine("GET /{isbn}") + BookResource findByIsbn(@Param("isbn") String isbn); + + @RequestLine("GET") + List findAll(); + + @RequestLine("POST") + @Headers("Content-Type: application/json") + void create(Book book); +} diff --git a/feign-client/src/main/java/com/baeldung/feign/models/Book.java b/feign-client/src/main/java/com/baeldung/feign/models/Book.java new file mode 100644 index 0000000000..cda4412e27 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/models/Book.java @@ -0,0 +1,18 @@ +package com.baeldung.feign.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class Book { + private String isbn; + private String author; + private String title; + private String synopsis; + private String language; +} diff --git a/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java b/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java new file mode 100644 index 0000000000..7902db9fe8 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java @@ -0,0 +1,14 @@ +package com.baeldung.feign.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class BookResource { + private Book book; +} diff --git a/feign-client/src/main/resources/log4j2.xml b/feign-client/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..659c5fda0e --- /dev/null +++ b/feign-client/src/main/resources/log4j2.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java new file mode 100644 index 0000000000..e7e058a336 --- /dev/null +++ b/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java @@ -0,0 +1,58 @@ +package com.baeldung.feign.clients; + +import com.baeldung.feign.BookControllerFeignClientBuilder; +import com.baeldung.feign.models.Book; +import com.baeldung.feign.models.BookResource; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@Slf4j +@RunWith(JUnit4.class) +public class BookClientTest { + private BookClient bookClient; + + @Before + public void setup() { + BookControllerFeignClientBuilder feignClientBuilder = new BookControllerFeignClientBuilder(); + bookClient = feignClientBuilder.getBookClient(); + } + + @Test + public void givenBookClient_shouldRunSuccessfully() throws Exception { + List books = bookClient.findAll().stream() + .map(BookResource::getBook) + .collect(Collectors.toList()); + assertTrue(books.size() > 2); + log.info("{}", books); + } + + @Test + public void givenBookClient_shouldFindOneBook() throws Exception { + Book book = bookClient.findByIsbn("0151072558").getBook(); + assertThat(book.getAuthor(), containsString("Orwell")); + log.info("{}", book); + } + + @Test + public void givenBookClient_shouldPostBook() throws Exception { + String isbn = UUID.randomUUID().toString(); + Book book = new Book(isbn, "Me", "It's me!", null, null); + bookClient.create(book); + + book = bookClient.findByIsbn(isbn).getBook(); + assertThat(book.getAuthor(), is("Me")); + log.info("{}", book); + } +} diff --git a/flyway-migration/.gitignore b/flyway-migration/.gitignore new file mode 100644 index 0000000000..abffe04ed2 --- /dev/null +++ b/flyway-migration/.gitignore @@ -0,0 +1,4 @@ +.classpath +.project +.settings +target/ \ No newline at end of file diff --git a/flyway-migration/README.MD b/flyway-migration/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/flyway-migration/README.MD @@ -0,0 +1 @@ + diff --git a/flyway-migration/db/migration/V1_0__create_employee_schema.sql b/flyway-migration/db/migration/V1_0__create_employee_schema.sql new file mode 100644 index 0000000000..09408faecb --- /dev/null +++ b/flyway-migration/db/migration/V1_0__create_employee_schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS `employee` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20), +`email` varchar(50), +`date_of_birth` timestamp + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; \ No newline at end of file diff --git a/flyway-migration/db/migration/V2_0__create_department_schema.sql b/flyway-migration/db/migration/V2_0__create_department_schema.sql new file mode 100644 index 0000000000..2b9d3364a5 --- /dev/null +++ b/flyway-migration/db/migration/V2_0__create_department_schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS `department` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20) + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; + +ALTER TABLE `employee` ADD `dept_id` int AFTER `email`; \ No newline at end of file diff --git a/flyway-migration/myFlywayConfig.properties b/flyway-migration/myFlywayConfig.properties new file mode 100644 index 0000000000..22f3afefd3 --- /dev/null +++ b/flyway-migration/myFlywayConfig.properties @@ -0,0 +1,5 @@ +flyway.user=root +flyway.password=mysql +flyway.schemas=app-db +flyway.url=jdbc:mysql://localhost:3306/ +flyway.locations=filesystem:db/migration \ No newline at end of file diff --git a/flyway-migration/pom.xml b/flyway-migration/pom.xml new file mode 100644 index 0000000000..6e9d683a0e --- /dev/null +++ b/flyway-migration/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + com.baeldung + flyway-migration + 1.0 + flyway-migration + A sample project to demonstrate Flyway migrations + + + mysql + mysql-connector-java + 6.0.3 + + + + + + org.flywaydb + flyway-maven-plugin + 4.0.3 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index 5b08f6cdec..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Performance of Gson and Jackson - -Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. diff --git a/gson-jackson-performance/pom.xml b/gson-jackson-performance/pom.xml deleted file mode 100644 index 1ea43bd7fa..0000000000 --- a/gson-jackson-performance/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - 4.0.0 - - com.baeldung - gson-jackson-performance - 0.0.1-SNAPSHOT - jar - - gson-jackson-performance - http://maven.apache.org - - - UTF-8 - - - - gson-jackson-performance - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - - - - - com.google.code.gson - gson - 2.5 - - - - com.fasterxml.jackson.core - jackson-databind - 2.7.1-1 - - - - junit - junit - 3.8.1 - test - - - - log4j - log4j - 1.2.17 - - - - - - - diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java deleted file mode 100644 index b69d306edf..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.AddressDetails; -import com.baeldung.pojo.complex.ContactDetails; -import com.baeldung.pojo.complex.CustomerAddressDetails; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -/** - * - * This class is responsible for generating data for complex type object - */ - -public class ComplexDataGeneration { - - public static CustomerPortfolioComplex generateData() { - List customerAddressDetailsList = new ArrayList(); - for (int i = 0; i < 600000; i++) { - CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails(); - customerAddressDetails.setAge(20); - customerAddressDetails.setFirstName(Utility.generateRandomName()); - customerAddressDetails.setLastName(Utility.generateRandomName()); - - List addressDetailsList = new ArrayList(); - customerAddressDetails.setAddressDetails(addressDetailsList); - - for (int j = 0; j < 2; j++) { - AddressDetails addressDetails = new AddressDetails(); - addressDetails.setZipcode(Utility.generateRandomZip()); - addressDetails.setAddress(Utility.generateRandomAddress()); - - List contactDetailsList = new ArrayList(); - addressDetails.setContactDetails(contactDetailsList); - - for (int k = 0; k < 2; k++) { - ContactDetails contactDetails = new ContactDetails(); - contactDetails.setLandline(Utility.generateRandomPhone()); - contactDetails.setMobile(Utility.generateRandomPhone()); - contactDetailsList.add(contactDetails); - contactDetails = null; - } - - addressDetailsList.add(addressDetails); - addressDetails = null; - contactDetailsList = null; - } - customerAddressDetailsList.add(customerAddressDetails); - customerAddressDetails = null; - - if (i % 6000 == 0) { - Runtime.getRuntime().gc(); - } - } - - CustomerPortfolioComplex customerPortfolioComplex = new CustomerPortfolioComplex(); - customerPortfolioComplex.setCustomerAddressDetailsList(customerAddressDetailsList); - customerAddressDetailsList = null; - return customerPortfolioComplex; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java deleted file mode 100644 index b97893e8f1..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Complex type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataGson { - - private static final Logger logger = Logger.getLogger(ComplexDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = gson.fromJson(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java deleted file mode 100644 index 07a210fb37..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.complex; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Complex type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataJackson { - - private static final Logger logger = Logger.getLogger(ComplexDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) - throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = mapper.readValue(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java deleted file mode 100644 index 1e186adc72..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.Customer; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -/** - * - * This class is responsible for generating data for simple type object - */ - -public class SimpleDataGeneration { - - public static CustomerPortfolioSimple generateData() { - List customerList = new ArrayList(); - for (int i = 0; i < 1; i++) { - Customer customer = new Customer(); - customer.setAge(20); - customer.setFirstName(Utility.generateRandomName()); - customer.setLastName(Utility.generateRandomName()); - - customerList.add(customer); - customer = null; - - } - - CustomerPortfolioSimple customerPortfolioSimple = new CustomerPortfolioSimple(); - customerPortfolioSimple.setCustomerLists(customerList); - customerList = null; - return customerPortfolioSimple; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java deleted file mode 100644 index b190313462..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Simple type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataGson { - - private static final Logger logger = Logger.getLogger(SimpleDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - String jsonStr = null; - int j = 5; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Gson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = gson.fromJson(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java deleted file mode 100644 index 9330333604..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.simple; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Simple type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataJackson { - - private static final Logger logger = Logger.getLogger(SimpleDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = mapper.readValue(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java deleted file mode 100644 index 8b0c402e47..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.data.utility; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.Random; - -public class Utility { - - public static String generateRandomName() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomAddress() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 30; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomZip() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomPhone() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 10; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String readFile(String fileName , Class clazz) throws IOException { - String dir = clazz.getResource("/").getFile(); - dir = dir + "/" + fileName; - - BufferedReader br = new BufferedReader(new FileReader(dir)); - try { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append(System.lineSeparator()); - line = br.readLine(); - } - return sb.toString(); - } finally { - br.close(); - } - } - - public static String bytesIntoMB(long bytes) { - long kilobyte = 1024; - long megabyte = kilobyte * 1024; - - if ((bytes >= 0) && (bytes < kilobyte)) { - return bytes + " B"; - - } else if ((bytes >= kilobyte) && (bytes < megabyte)) { - return (bytes / kilobyte) + " KB"; - - } else if ((bytes >= megabyte)) { - return (bytes / megabyte) + " MB"; - } - - return null; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java deleted file mode 100644 index 79725a97bd..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class AddressDetails { - - private String address; - - private String zipcode; - - private List contactDetails; - - public String getZipcode() { - return zipcode; - } - - public void setZipcode(String zipcode) { - this.zipcode = zipcode; - } - - public List getContactDetails() { - return contactDetails; - } - - public void setContactDetails(List contactDetails) { - this.contactDetails = contactDetails; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java deleted file mode 100644 index 164fe3f470..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.pojo.complex; - -public class ContactDetails { - - private String mobile; - - private String landline; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java deleted file mode 100644 index 9bc5951716..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -import com.baeldung.pojo.simple.Customer; - -public class CustomerAddressDetails extends Customer { - - private List addressDetails; - - public List getAddressDetails() { - return addressDetails; - } - - public void setAddressDetails(List addressDetails) { - this.addressDetails = addressDetails; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java deleted file mode 100644 index 13f9d240b8..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class CustomerPortfolioComplex { - - private List customerAddressDetailsList; - - public List getCustomerAddressDetailsList() { - return customerAddressDetailsList; - } - - public void setCustomerAddressDetailsList(List customerAddressDetailsList) { - this.customerAddressDetailsList = customerAddressDetailsList; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java deleted file mode 100644 index 3d5668f85a..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.pojo.simple; - - -public class Customer { - - private String firstName; - - private String lastName; - - private int age; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java deleted file mode 100644 index 7cb684813c..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.pojo.simple; - -import java.util.List; - -public class CustomerPortfolioSimple { - - private List customerLists; - - public List getCustomerLists() { - return customerLists; - } - - public void setCustomerLists(List customerLists) { - this.customerLists = customerLists; - } -} diff --git a/gson-jackson-performance/src/main/resources/log4j.properties b/gson-jackson-performance/src/main/resources/log4j.properties deleted file mode 100644 index 371cbc9048..0000000000 --- a/gson-jackson-performance/src/main/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Root logger option -log4j.rootLogger=DEBUG, file - -# Redirect log messages to console -# log4j.appender.stdout=org.apache.log4j.ConsoleAppender -# log4j.appender.stdout.Target=System.out -# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file, support file rolling. -log4j.appender.file=org.apache.log4j.RollingFileAppender -log4j.appender.file.File=log4j-application.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/gson/pom.xml b/gson/pom.xml index 4f331f6fd9..d864c289c2 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -19,7 +19,7 @@ com.google.guava guava - 18.0 + ${guava.version} commons-io diff --git a/guava18/pom.xml b/guava18/pom.xml index 6002b37d74..413e9c35b8 100644 --- a/guava18/pom.xml +++ b/guava18/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -14,12 +13,15 @@ guava 18.0 + junit junit 4.12 + test + diff --git a/guava19/pom.xml b/guava19/pom.xml index 13f3b471f1..61fbf38575 100644 --- a/guava19/pom.xml +++ b/guava19/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.baeldung @@ -10,20 +11,23 @@ com.google.guava guava - 19.0 + ${guava.version} + junit junit 4.12 + test org.hamcrest hamcrest-all 1.3 + test - + @@ -42,4 +46,8 @@ + + 19.0 + + \ No newline at end of file diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index aca069e300..6dd0c95026 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -115,6 +115,7 @@ jackson-databind ${jackson.version} + org.hibernate hibernate-validator @@ -221,8 +222,7 @@ 1.9.2.RELEASE - - 2.7.2 + 2.7.8 1.7.13 diff --git a/jackson/pom.xml b/jackson/pom.xml index 17b0ac507e..e795ad11a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -174,7 +174,7 @@ 5.1.38 - 2.7.2 + 2.7.8 1.7.13 diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml new file mode 100644 index 0000000000..a91c3b9b62 --- /dev/null +++ b/java-cassandra/pom.xml @@ -0,0 +1,105 @@ + + 4.0.0 + com.baeldung + cassandra-java-client + 1.0.0-SNAPSHOT + + cassandra-java-client + + + + + com.datastax.cassandra + cassandra-driver-core + ${cassandra-driver-core.version} + true + + + + + org.cassandraunit + cassandra-unit + 3.0.0.1 + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + junit + junit + ${junit.version} + test + + + + + java-cassandra + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + UTF-8 + + 19.0 + + + 1.7.21 + 1.1.7 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + + 3.5.1 + + + 3.1.0 + + + diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java new file mode 100644 index 0000000000..c67a2c2ddb --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java @@ -0,0 +1,44 @@ +package com.baeldung.cassandra.java.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.cassandra.java.client.domain.Book; +import com.baeldung.cassandra.java.client.repository.BookRepository; +import com.baeldung.cassandra.java.client.repository.KeyspaceRepository; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; + +public class CassandraClient { + private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class); + + public static void main(String args[]) { + CassandraConnector connector = new CassandraConnector(); + connector.connect("127.0.0.1", null); + Session session = connector.getSession(); + + KeyspaceRepository sr = new KeyspaceRepository(session); + sr.createKeyspace("library", "SimpleStrategy", 1); + sr.useKeyspace("library"); + + BookRepository br = new BookRepository(session); + br.createTable(); + br.alterTablebooks("publisher", "text"); + + br.createTableBooksByTitle(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + br.insertBookBatch(book); + + br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle())); + br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle())); + + br.deletebookByTitle("Effective Java"); + br.deleteTable("books"); + br.deleteTable("booksByTitle"); + + sr.deleteKeyspace("library"); + + connector.close(); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java new file mode 100644 index 0000000000..e035335ca0 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java @@ -0,0 +1,51 @@ +package com.baeldung.cassandra.java.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Cluster.Builder; +import com.datastax.driver.core.Host; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.Session; + +/** + * + * This is an implementation of a simple Java client. + * + */ +public class CassandraConnector { + private static final Logger LOG = LoggerFactory.getLogger(CassandraConnector.class); + + private Cluster cluster; + + private Session session; + + public void connect(final String node, final Integer port) { + + Builder b = Cluster.builder().addContactPoint(node); + + if (port != null) { + b.withPort(port); + } + cluster = b.build(); + + Metadata metadata = cluster.getMetadata(); + LOG.info("Cluster name: " + metadata.getClusterName()); + + for (Host host : metadata.getAllHosts()) { + LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack()); + } + + session = cluster.connect(); + } + + public Session getSession() { + return this.session; + } + + public void close() { + session.close(); + cluster.close(); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java new file mode 100644 index 0000000000..e6c7753eb3 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java @@ -0,0 +1,66 @@ +package com.baeldung.cassandra.java.client.domain; + +import java.util.UUID; + +public class Book { + + private UUID id; + + private String title; + + private String author; + + private String subject; + + private String publisher; + + Book() { + } + + public Book(UUID id, String title, String author, String subject) { + this.id = id; + this.title = title; + this.author = author; + this.subject = subject; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java new file mode 100644 index 0000000000..31e2969e01 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java @@ -0,0 +1,177 @@ +package com.baeldung.cassandra.java.client.repository; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.cassandra.java.client.domain.Book; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; + +public class BookRepository { + + private static final String TABLE_NAME = "books"; + + private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle"; + + private Session session; + + public BookRepository(Session session) { + this.session = session; + } + + /** + * Creates the books table. + */ + public void createTable() { + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME).append("(").append("id uuid PRIMARY KEY, ").append("title text,").append("author text,").append("subject text);"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Creates the books table. + */ + public void createTableBooksByTitle() { + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME_BY_TITLE).append("(").append("id uuid, ").append("title text,").append("PRIMARY KEY (title, id));"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Alters the table books and adds an extra column. + */ + public void alterTablebooks(String columnName, String columnType) { + StringBuilder sb = new StringBuilder("ALTER TABLE ").append(TABLE_NAME).append(" ADD ").append(columnName).append(" ").append(columnType).append(";"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a row in the table books. + * + * @param book + */ + public void insertbook(Book book) { + StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '") + .append(book.getSubject()).append("');"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a row in the table booksByTitle. + * @param book + */ + public void insertbookByTitle(Book book) { + StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a book into two identical tables using a batch query. + * + * @param book + */ + public void insertBookBatch(Book book) { + StringBuilder sb = new StringBuilder("BEGIN BATCH ") + .append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ") + .append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '") + .append(book.getSubject()).append("');") + .append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ") + .append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');") + .append("APPLY BATCH;"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Select book by id. + * + * @return + */ + public Book selectByTitle(String title) { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';"); + + final String query = sb.toString(); + + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book s = new Book(r.getUUID("id"), r.getString("title"), null, null); + books.add(s); + } + + return books.get(0); + } + + /** + * Select all books from books + * + * @return + */ + public List selectAll() { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); + + final String query = sb.toString(); + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book book = new Book(r.getUUID("id"), r.getString("title"), r.getString("author"), r.getString("subject")); + books.add(book); + } + return books; + } + + /** + * Select all books from booksByTitle + * @return + */ + public List selectAllBookByTitle() { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE); + + final String query = sb.toString(); + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book book = new Book(r.getUUID("id"), r.getString("title"), null, null); + books.add(book); + } + return books; + } + + /** + * Delete a book by title. + */ + public void deletebookByTitle(String title) { + StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Delete table. + * + * @param tableName the name of the table to delete. + */ + public void deleteTable(String tableName) { + StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(tableName); + + final String query = sb.toString(); + session.execute(query); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java new file mode 100644 index 0000000000..f15558f040 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.cassandra.java.client.repository; + +import com.datastax.driver.core.Session; + +/** + * Repository to handle the Cassandra schema. + * + */ +public class KeyspaceRepository { + private Session session; + + public KeyspaceRepository(Session session) { + this.session = session; + } + + /** + * Method used to create any keyspace - schema. + * + * @param schemaName the name of the schema. + * @param replicatioonStrategy the replication strategy. + * @param numberOfReplicas the number of replicas. + * + */ + public void createKeyspace(String keyspaceName, String replicatioonStrategy, int numberOfReplicas) { + StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ").append(keyspaceName).append(" WITH replication = {").append("'class':'").append(replicatioonStrategy).append("','replication_factor':").append(numberOfReplicas).append("};"); + + final String query = sb.toString(); + + session.execute(query); + } + + public void useKeyspace(String keyspace) { + session.execute("USE " + keyspace); + } + + /** + * Method used to delete the specified schema. + * It results in the immediate, irreversable removal of the keyspace, including all tables and data contained in the keyspace. + * + * @param schemaName the name of the keyspace to delete. + */ + public void deleteKeyspace(String keyspaceName) { + StringBuilder sb = new StringBuilder("DROP KEYSPACE ").append(keyspaceName); + + final String query = sb.toString(); + + session.execute(query); + } +} diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..62eae94c7c --- /dev/null +++ b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,174 @@ +package com.baeldung.cassandra.java.client.repository; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.cassandra.java.client.CassandraConnector; +import com.baeldung.cassandra.java.client.domain.Book; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.core.utils.UUIDs; + +public class BookRepositoryIntegrationTest { + + private KeyspaceRepository schemaRepository; + + private BookRepository bookRepository; + + private Session session; + + final String KEYSPACE_NAME = "testLibrary"; + final String BOOKS = "books"; + final String BOOKS_BY_TITLE = "booksByTitle"; + + @BeforeClass + public static void init() throws ConfigurationException, TTransportException, IOException, InterruptedException { + // Start an embedded Cassandra Server + EmbeddedCassandraServerHelper.startEmbeddedCassandra(20000L); + } + + @Before + public void connect() { + CassandraConnector client = new CassandraConnector(); + client.connect("127.0.0.1", 9142); + this.session = client.getSession(); + schemaRepository = new KeyspaceRepository(session); + schemaRepository.createKeyspace(KEYSPACE_NAME, "SimpleStrategy", 1); + schemaRepository.useKeyspace(KEYSPACE_NAME); + bookRepository = new BookRepository(session); + } + + @Test + public void whenCreatingATable_thenCreatedCorrectly() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + ResultSet result = session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + + // Collect all the column names in one list. + List columnNames = result.getColumnDefinitions().asList().stream().map(cl -> cl.getName()).collect(Collectors.toList()); + assertEquals(columnNames.size(), 4); + assertTrue(columnNames.contains("id")); + assertTrue(columnNames.contains("title")); + assertTrue(columnNames.contains("author")); + assertTrue(columnNames.contains("subject")); + } + + @Test + public void whenAlteringTable_thenAddedColumnExists() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + bookRepository.alterTablebooks("publisher", "text"); + + ResultSet result = session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + + boolean columnExists = result.getColumnDefinitions().asList().stream().anyMatch(cl -> cl.getName().equals("publisher")); + assertTrue(columnExists); + } + + @Test + public void whenAddingANewBook_thenBookExists() { + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + String title = "Effective Java"; + String author = "Joshua Bloch"; + Book book = new Book(UUIDs.timeBased(), title, author, "Programming"); + bookRepository.insertbookByTitle(book); + + Book savedBook = bookRepository.selectByTitle(title); + assertEquals(book.getTitle(), savedBook.getTitle()); + } + + @Test + public void whenAddingANewBookBatch_ThenBookAddedInAllTables() { + // Create table books + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + // Create table booksByTitle + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + String title = "Effective Java"; + String author = "Joshua Bloch"; + Book book = new Book(UUIDs.timeBased(), title, author, "Programming"); + bookRepository.insertBookBatch(book); + + List books = bookRepository.selectAll(); + + assertEquals(1, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + + List booksByTitle = bookRepository.selectAllBookByTitle(); + + assertEquals(1, booksByTitle.size()); + assertTrue(booksByTitle.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + } + + @Test + public void whenSelectingAll_thenReturnAllRecords() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + bookRepository.insertbook(book); + + book = new Book(UUIDs.timeBased(), "Clean Code", "Robert C. Martin", "Programming"); + bookRepository.insertbook(book); + + List books = bookRepository.selectAll(); + + assertEquals(2, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Clean Code"))); + } + + @Test + public void whenDeletingABookByTitle_thenBookIsDeleted() { + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + bookRepository.insertbookByTitle(book); + + book = new Book(UUIDs.timeBased(), "Clean Code", "Robert C. Martin", "Programming"); + bookRepository.insertbookByTitle(book); + + bookRepository.deletebookByTitle("Clean Code"); + + List books = bookRepository.selectAllBookByTitle(); + assertEquals(1, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + assertFalse(books.stream().anyMatch(b -> b.getTitle().equals("Clean Code"))); + + } + + @Test(expected = InvalidQueryException.class) + public void whenDeletingATable_thenUnconfiguredTable() { + bookRepository.createTable(); + bookRepository.deleteTable(BOOKS); + + session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + } + + @AfterClass + public static void cleanup() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9df46b3176 --- /dev/null +++ b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.cassandra.java.client.repository; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.baeldung.cassandra.java.client.CassandraConnector; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class KeyspaceRepositoryIntegrationTest { + + private KeyspaceRepository schemaRepository; + + private Session session; + + @BeforeClass + public static void init() throws ConfigurationException, TTransportException, IOException, InterruptedException { + // Start an embedded Cassandra Server + EmbeddedCassandraServerHelper.startEmbeddedCassandra(20000L); + } + + @Before + public void connect() { + CassandraConnector client = new CassandraConnector(); + client.connect("127.0.0.1", 9142); + this.session = client.getSession(); + schemaRepository = new KeyspaceRepository(session); + } + + @Test + public void whenCreatingAKeyspace_thenCreated() { + String keyspaceName = "testBaeldungKeyspace"; + schemaRepository.createKeyspace(keyspaceName, "SimpleStrategy", 1); + + // ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = 'testBaeldungKeyspace';"); + + ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces;"); + + // Check if the Keyspace exists in the returned keyspaces. + List matchedKeyspaces = result.all().stream().filter(r -> r.getString(0).equals(keyspaceName.toLowerCase())).map(r -> r.getString(0)).collect(Collectors.toList()); + assertEquals(matchedKeyspaces.size(), 1); + assertTrue(matchedKeyspaces.get(0).equals(keyspaceName.toLowerCase())); + } + + @Test + public void whenDeletingAKeyspace_thenDoesNotExist() { + String keyspaceName = "testBaeldungKeyspace"; + + // schemaRepository.createKeyspace(keyspaceName, "SimpleStrategy", 1); + schemaRepository.deleteKeyspace(keyspaceName); + + ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces;"); + boolean isKeyspaceCreated = result.all().stream().anyMatch(r -> r.getString(0).equals(keyspaceName.toLowerCase())); + assertFalse(isKeyspaceCreated); + } + + @AfterClass + public static void cleanup() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/log4j/pom.xml b/log4j/pom.xml index 76c05b36c1..ab384d4dd1 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -16,29 +16,25 @@ 1.2.17 - org.apache.logging.log4j log4j-api - 2.6 + 2.7 org.apache.logging.log4j log4j-core - 2.6 + 2.7 - - + com.lmax disruptor 3.3.4 - - ch.qos.logback logback-classic diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java new file mode 100644 index 0000000000..6ecc7b887a --- /dev/null +++ b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java @@ -0,0 +1,20 @@ +package com.baeldung.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml + */ +public class Slf4jExample { + private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class); + + public static void main(String[] args) { + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + + String variable = "Hello John"; + logger.debug("Printing variable value {} ", variable); + } +} diff --git a/mapstruct/bin/pom.xml b/mapstruct/bin/pom.xml deleted file mode 100644 index 8a28ae9511..0000000000 --- a/mapstruct/bin/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - mapstruct - mapstruct - com.baeldung - 1.0 - jar - - - 1.0.0.Final - - - - org.mapstruct - mapstruct-jdk8 - ${org.mapstruct.version} - - - junit - junit - 4.12 - test - - - - mapstruct - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - org.mapstruct - mapstruct-processor - ${org.mapstruct.version} - - - - - - - diff --git a/mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java b/mapstruct/src/main/java/com/baeldung/dto/DivisionDTO.java similarity index 94% rename from mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java rename to mapstruct/src/main/java/com/baeldung/dto/DivisionDTO.java index 01a5792176..37f8bd111b 100644 --- a/mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java +++ b/mapstruct/src/main/java/com/baeldung/dto/DivisionDTO.java @@ -1,4 +1,4 @@ -package org.baeldung.dto; +package com.baeldung.dto; public class DivisionDTO { diff --git a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java b/mapstruct/src/main/java/com/baeldung/dto/EmployeeDTO.java similarity index 97% rename from mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java rename to mapstruct/src/main/java/com/baeldung/dto/EmployeeDTO.java index 24d6950cab..5da3165683 100644 --- a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java +++ b/mapstruct/src/main/java/com/baeldung/dto/EmployeeDTO.java @@ -1,4 +1,4 @@ -package org.baeldung.dto; +package com.baeldung.dto; public class EmployeeDTO { diff --git a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java b/mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java similarity index 93% rename from mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java rename to mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java index 4c169461c8..ec8d80c4af 100644 --- a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java +++ b/mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java @@ -1,4 +1,4 @@ -package org.baeldung.dto; +package com.baeldung.dto; public class SimpleSource { diff --git a/mapstruct/src/main/java/org/baeldung/entity/Division.java b/mapstruct/src/main/java/com/baeldung/entity/Division.java similarity index 94% rename from mapstruct/src/main/java/org/baeldung/entity/Division.java rename to mapstruct/src/main/java/com/baeldung/entity/Division.java index 83b0916eb4..7b1416d6c5 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/Division.java +++ b/mapstruct/src/main/java/com/baeldung/entity/Division.java @@ -1,4 +1,4 @@ -package org.baeldung.entity; +package com.baeldung.entity; public class Division { diff --git a/mapstruct/src/main/java/org/baeldung/entity/Employee.java b/mapstruct/src/main/java/com/baeldung/entity/Employee.java similarity index 96% rename from mapstruct/src/main/java/org/baeldung/entity/Employee.java rename to mapstruct/src/main/java/com/baeldung/entity/Employee.java index 8c441813b6..04044f4dfe 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/Employee.java +++ b/mapstruct/src/main/java/com/baeldung/entity/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.entity; +package com.baeldung.entity; import java.util.Date; diff --git a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java b/mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java similarity index 93% rename from mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java rename to mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java index 9fdbd7f054..d9cba1c372 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java +++ b/mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java @@ -1,4 +1,4 @@ -package org.baeldung.entity; +package com.baeldung.entity; public class SimpleDestination { diff --git a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/EmployeeMapper.java similarity index 85% rename from mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java rename to mapstruct/src/main/java/com/baeldung/mapper/EmployeeMapper.java index 013c332e6e..8e00103d0e 100644 --- a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java +++ b/mapstruct/src/main/java/com/baeldung/mapper/EmployeeMapper.java @@ -1,15 +1,15 @@ -package org.baeldung.mapper; +package com.baeldung.mapper; -import java.util.List; - -import org.baeldung.dto.DivisionDTO; -import org.baeldung.dto.EmployeeDTO; -import org.baeldung.entity.Division; -import org.baeldung.entity.Employee; +import com.baeldung.dto.DivisionDTO; +import com.baeldung.dto.EmployeeDTO; +import com.baeldung.entity.Division; +import com.baeldung.entity.Employee; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; +import java.util.List; + @Mapper public interface EmployeeMapper { diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java similarity index 69% rename from mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java rename to mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java index 3e872e68a3..f3f2187c20 100644 --- a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java +++ b/mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java @@ -1,7 +1,7 @@ -package org.baeldung.mapper; +package com.baeldung.mapper; -import org.baeldung.dto.SimpleSource; -import org.baeldung.entity.SimpleDestination; +import com.baeldung.dto.SimpleSource; +import com.baeldung.entity.SimpleDestination; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") diff --git a/mapstruct/src/main/resources/applicationContext.xml b/mapstruct/src/main/resources/applicationContext.xml index 1e6649139c..22d8d1b769 100644 --- a/mapstruct/src/main/resources/applicationContext.xml +++ b/mapstruct/src/main/resources/applicationContext.xml @@ -10,6 +10,6 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> - + \ No newline at end of file diff --git a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java similarity index 96% rename from mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java rename to mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java index c5998f89ef..7da6c41dc1 100644 --- a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java +++ b/mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java @@ -1,6 +1,11 @@ -package org.baeldung.mapper; +package com.baeldung.mapper; -import static org.junit.Assert.assertEquals; +import com.baeldung.dto.DivisionDTO; +import com.baeldung.dto.EmployeeDTO; +import com.baeldung.entity.Division; +import com.baeldung.entity.Employee; +import org.junit.Test; +import org.mapstruct.factory.Mappers; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -8,12 +13,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import org.baeldung.dto.DivisionDTO; -import org.baeldung.dto.EmployeeDTO; -import org.baeldung.entity.Division; -import org.baeldung.entity.Employee; -import org.junit.Test; -import org.mapstruct.factory.Mappers; +import static org.junit.Assert.assertEquals; public class EmployeeMapperTest { diff --git a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java similarity index 93% rename from mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java rename to mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java index 226603b16a..a7addf33a7 100644 --- a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java +++ b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java @@ -1,9 +1,9 @@ -package org.baeldung.mapper; +package com.baeldung.mapper; import static org.junit.Assert.assertEquals; -import org.baeldung.dto.SimpleSource; -import org.baeldung.entity.SimpleDestination; +import com.baeldung.dto.SimpleSource; +import com.baeldung.entity.SimpleDestination; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/okhttp/pom.xml b/okhttp/pom.xml new file mode 100644 index 0000000000..ba5bcf9725 --- /dev/null +++ b/okhttp/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.baeldung.okhttp + okhttp + 0.0.1-SNAPSHOT + + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + + + 3.4.1 + + + 1.3 + 4.12 + + + + diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java new file mode 100644 index 0000000000..2a33a1febd --- /dev/null +++ b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java @@ -0,0 +1,26 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class DefaultContentTypeInterceptor implements Interceptor { + + private final String contentType; + + public DefaultContentTypeInterceptor(String contentType) { + this.contentType = contentType; + } + + public Response intercept(Interceptor.Chain chain) throws IOException { + + Request originalRequest = chain.request(); + Request requestWithUserAgent = originalRequest.newBuilder() + .header("Content-Type", contentType) + .build(); + + return chain.proceed(requestWithUserAgent); + } +} diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java new file mode 100644 index 0000000000..6a98f8d20a --- /dev/null +++ b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -0,0 +1,68 @@ +package org.baeldung.okhttp; + +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.*; + +import java.io.IOException; + +public class ProgressRequestWrapper extends RequestBody { + + protected RequestBody delegate; + protected ProgressListener listener; + + protected CountingSink countingSink; + + public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { + this.delegate = delegate; + this.listener = listener; + } + + @Override + public MediaType contentType() { + return delegate.contentType(); + } + + @Override + public long contentLength() throws IOException { + return delegate.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + + BufferedSink bufferedSink; + + countingSink = new CountingSink(sink); + bufferedSink = Okio.buffer(countingSink); + + delegate.writeTo(bufferedSink); + + bufferedSink.flush(); + } + + protected final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0; + + public CountingSink(Sink delegate) { + super(delegate); + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + + super.write(source, byteCount); + + bytesWritten += byteCount; + listener.onRequestProgress(bytesWritten, contentLength()); + } + + } + + public interface ProgressListener { + void onRequestProgress(long bytesWritten, long contentLength); + + } +} + diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java new file mode 100644 index 0000000000..32457fc11b --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -0,0 +1,81 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpFileUploadingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + + ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + + public void onRequestProgress(long bytesWritten, long contentLength) { + + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); + } + }; + + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(countingBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java new file mode 100644 index 0000000000..e8edff92df --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -0,0 +1,78 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpGetTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + urlBuilder.addQueryParameter("id", "1"); + + String url = urlBuilder.build().toString(); + + Request request = new Request.Builder() + .url(url) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + + call.enqueue(new Callback() { + + public void onResponse(Call call, Response response) throws IOException { + assertThat(response.code(), equalTo(200)); + } + + public void onFailure(Call call, IOException e) { + + } + }); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java new file mode 100644 index 0000000000..5b2e89eca8 --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -0,0 +1,48 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpHeaderTest { + + private static final String SAMPLE_URL = "http://www.github.com"; + + @Test + public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .addHeader("Content-Type", "application/json") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(new DefaultContentTypeInterceptor("application/json")) + .build(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java new file mode 100644 index 0000000000..829bafe8ef --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -0,0 +1,113 @@ +package org.baeldung.okhttp; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import okhttp3.Cache; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpMiscTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + //@Test + public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + //.connectTimeout(10, TimeUnit.SECONDS) + //.writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(1, TimeUnit.SECONDS) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + //@Test + public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException { + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + final int seconds = 1; + //final int seconds = 3; + + final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); + + // Schedule a job to cancel the call in 1 second. + executor.schedule(new Runnable() { + public void run() { + + System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); + } + }, seconds, TimeUnit.SECONDS); + + try { + + System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); + + } catch (IOException e) { + + System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); + } + } + + @Test + public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException { + + int cacheSize = 10 * 1024 * 1024; // 10 MiB + File cacheDirectory = new File("src/test/resources/cache"); + Cache cache = new Cache(cacheDirectory, cacheSize); + + OkHttpClient client = new OkHttpClient.Builder() + .cache(cache) + .build(); + + Request request = new Request.Builder() + .url("http://publicobject.com/helloworld.txt") + //.cacheControl(CacheControl.FORCE_NETWORK) + //.cacheControl(CacheControl.FORCE_CACHE) + .build(); + + Response response1 = client.newCall(request).execute(); + + String responseBody1 = response1.body().string(); + + System.out.println("Response 1 response: " + response1); + System.out.println("Response 1 cache response: " + response1.cacheResponse()); + System.out.println("Response 1 network response: " + response1.networkResponse()); + System.out.println("Response 1 responseBody: " + responseBody1); + + Response response2 = client.newCall(request).execute(); + + String responseBody2 = response2.body().string(); + + System.out.println("Response 2 response: " + response2); + System.out.println("Response 2 cache response: " + response2.cacheResponse()); + System.out.println("Response 2 network response: " + response2.networkResponse()); + System.out.println("Response 2 responseBody: " + responseBody2); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java new file mode 100644 index 0000000000..1ba2d517c5 --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -0,0 +1,109 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Credentials; +import okhttp3.FormBody; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpPostingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; + + @Test + public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody formBody = new FormBody.Builder() + .add("username", "test") + .add("password", "test") + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users") + .post(formBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException { + + String postBody = "test post"; + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(URL_SECURED_BY_BASIC_AUTHENTICATION) + .addHeader("Authorization", Credentials.basic("test", "test")) + .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + String json = "{\"id\":1,\"name\":\"John\"}"; + + RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/detail") + .post(body) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("username", "test") + .addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/multipart") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java new file mode 100644 index 0000000000..1582a5ff7f --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -0,0 +1,33 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpRedirectTest { + + @Test + public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException { + + OkHttpClient client = new OkHttpClient().newBuilder() + .followRedirects(false) + .build(); + + Request request = new Request.Builder() + .url("http://t.co/I5YYd9tddw") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(301)); + } +} diff --git a/okhttp/src/test/resources/test.txt b/okhttp/src/test/resources/test.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/okhttp/src/test/resources/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/patterns/pom.xml b/patterns/pom.xml new file mode 100644 index 0000000000..7c23b6f55d --- /dev/null +++ b/patterns/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + patterns + war + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.0.M1 + + + /front-controller + + + + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java new file mode 100644 index 0000000000..a8962f5108 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java @@ -0,0 +1,38 @@ +package com.baeldung.enterprise.patterns.front.controller; + +import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; +import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FrontControllerServlet extends HttpServlet { + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(getServletContext(), request, response); + command.process(); + } + + private FrontCommand getCommand(HttpServletRequest request) { + try { + Class type = Class.forName( + String.format( + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + request.getParameter("command") + ) + ); + return (FrontCommand) type + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + return new UnknownCommand(); + } + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java new file mode 100644 index 0000000000..12a008faeb --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java @@ -0,0 +1,32 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand { + protected ServletContext context; + protected HttpServletRequest request; + protected HttpServletResponse response; + + public void init( + ServletContext servletContext, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse + ) { + this.context = servletContext; + this.request = servletRequest; + this.response = servletResponse; + } + + public abstract void process() throws ServletException, IOException; + + protected void forward(String target) throws ServletException, IOException { + target = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = context.getRequestDispatcher(target); + dispatcher.forward(request, response); + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java new file mode 100644 index 0000000000..0c5bd64bbc --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java @@ -0,0 +1,21 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import com.baeldung.enterprise.patterns.front.controller.data.Book; +import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class SearchCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + Book book = new BookshelfImpl().getInstance() + .findByTitle(request.getParameter("title")); + if (book != null) { + request.setAttribute("book", book); + forward("book-found"); + } else { + forward("book-notfound"); + } + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java new file mode 100644 index 0000000000..90103c8f42 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java @@ -0,0 +1,11 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + forward("unknown"); + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..634e05c3a0 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public class Book { + private String author; + private String title; + private Double price; + + public Book() { + } + + public Book(String author, String title, Double price) { + this.author = author; + this.title = title; + this.price = price; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..524e000bd9 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,15 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public interface Bookshelf { + + default void init() { + add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + Bookshelf getInstance(); + + boolean add(E book); + + Book findByTitle(String title); +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java new file mode 100644 index 0000000000..3862418857 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java @@ -0,0 +1,24 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +import java.util.ArrayList; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + private static Bookshelf INSTANCE; + + @Override + public Bookshelf getInstance() { + if (INSTANCE == null) { + INSTANCE = new BookshelfImpl(); + INSTANCE.init(); + } + return INSTANCE; + } + + @Override + public Book findByTitle(String title) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) + .findFirst() + .orElse(null); + } +} diff --git a/patterns/src/main/resources/front controller.png b/patterns/src/main/resources/front controller.png new file mode 100644 index 0000000000..af22a38e37 Binary files /dev/null and b/patterns/src/main/resources/front controller.png differ diff --git a/patterns/src/main/resources/front controller.puml b/patterns/src/main/resources/front controller.puml new file mode 100644 index 0000000000..cbc2dc8bd9 --- /dev/null +++ b/patterns/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml +scale 1.5 +class Handler { +doGet +doPost +} + +abstract class AbstractCommand { +process +} +class ConcreteCommand1 { +process +} +class ConcreteCommand2 { +process +} + +Handler .right.> AbstractCommand +AbstractCommand <|-- ConcreteCommand1 +AbstractCommand <|-- ConcreteCommand2 + +@enduml \ No newline at end of file diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..42e08b4a46 --- /dev/null +++ b/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,12 @@ + + + + Bookshelf: Title found + + +

Our Bookshelf contains this title:

+

${book.getTitle()}

+

Author: ${book.getAuthor()}

+ + + diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..2f8ac01755 --- /dev/null +++ b/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -0,0 +1,10 @@ + + + + Bookshelf: Title not found + + +

Our Bookshelf doesn't contains this title:

+

${param.get("title")}

+ + diff --git a/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..b52b2de8d5 --- /dev/null +++ b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1,9 @@ + + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + diff --git a/patterns/src/main/webapp/WEB-INF/web.xml b/patterns/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..77113db09b --- /dev/null +++ b/patterns/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + front-controller + com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + + + front-controller + / + + diff --git a/play-framework/student-api/.gitignore b/play-framework/student-api/.gitignore new file mode 100644 index 0000000000..eb372fc719 --- /dev/null +++ b/play-framework/student-api/.gitignore @@ -0,0 +1,8 @@ +logs +target +/.idea +/.idea_modules +/.classpath +/.project +/.settings +/RUNNING_PID diff --git a/play-framework/student-api/LICENSE b/play-framework/student-api/LICENSE new file mode 100644 index 0000000000..4baedcb95f --- /dev/null +++ b/play-framework/student-api/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/student-api/README b/play-framework/student-api/README new file mode 100644 index 0000000000..f21d092edf --- /dev/null +++ b/play-framework/student-api/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/student-api/app/Filters.java b/play-framework/student-api/app/Filters.java new file mode 100644 index 0000000000..255de8ca93 --- /dev/null +++ b/play-framework/student-api/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/student-api/app/Module.java b/play-framework/student-api/app/Module.java new file mode 100644 index 0000000000..6e7d1766ef --- /dev/null +++ b/play-framework/student-api/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/student-api/app/controllers/AsyncController.java b/play-framework/student-api/app/controllers/AsyncController.java new file mode 100644 index 0000000000..92c84bb755 --- /dev/null +++ b/play-framework/student-api/app/controllers/AsyncController.java @@ -0,0 +1,64 @@ +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; + +/** + * This controller contains an action that demonstrates how to write + * simple asynchronous code in a controller. It uses a timer to + * 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. + */ +@Singleton +public class AsyncController extends Controller { + + private final ActorSystem actorSystem; + private final ExecutionContextExecutor exec; + + @Inject + public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor 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. + */ + public CompletionStage message() { + return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec); + } + + private CompletionStage getFutureMessage(long time, TimeUnit timeUnit) { + CompletableFuture future = new CompletableFuture<>(); + actorSystem.scheduler().scheduleOnce( + Duration.create(time, timeUnit), + () -> future.complete("Hi!"), + exec + ); + return future; + } + +} diff --git a/play-framework/student-api/app/controllers/CountController.java b/play-framework/student-api/app/controllers/CountController.java new file mode 100644 index 0000000000..02fcb15f8e --- /dev/null +++ b/play-framework/student-api/app/controllers/CountController.java @@ -0,0 +1,35 @@ +package controllers; + +import javax.inject.*; +import play.*; +import play.mvc.*; + +import services.Counter; + +/** + * This controller demonstrates how to use dependency injection to + * bind a component into a controller class. The class contains an + * action that shows an incrementing count to users. The {@link Counter} + * object is injected by the Guice dependency injection system. + */ +@Singleton +public class CountController extends Controller { + + private final Counter counter; + + @Inject + public CountController(Counter counter) { + this.counter = counter; + } + + /** + * An action that responds with the {@link Counter}'s current + * count. The result is plain text. This action is mapped to + * GET requests with a path of /count + * requests by an entry in the routes config file. + */ + public Result count() { + return ok(Integer.toString(counter.nextCount())); + } + +} diff --git a/play-framework/student-api/app/controllers/HomeController.java b/play-framework/student-api/app/controllers/HomeController.java new file mode 100644 index 0000000000..6a79856eb4 --- /dev/null +++ b/play-framework/student-api/app/controllers/HomeController.java @@ -0,0 +1,23 @@ +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() { + return ok(index.render("Your new application is ready.")); + } + +} diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java new file mode 100644 index 0000000000..8b759b9598 --- /dev/null +++ b/play-framework/student-api/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/student-api/app/filters/ExampleFilter.java new file mode 100644 index 0000000000..67a6a36cc3 --- /dev/null +++ b/play-framework/student-api/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/student-api/app/models/Student.java b/play-framework/student-api/app/models/Student.java new file mode 100644 index 0000000000..dc539767bd --- /dev/null +++ b/play-framework/student-api/app/models/Student.java @@ -0,0 +1,47 @@ +package models; +public class Student { + private String firstName; + private String lastName; + private int age; + private int id; + public Student(){} + public Student(String firstName, String lastName, int age) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + +} diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/student-api/app/models/StudentStore.java new file mode 100644 index 0000000000..add6a5dbd6 --- /dev/null +++ b/play-framework/student-api/app/models/StudentStore.java @@ -0,0 +1,46 @@ +package models; + +import java.util.HashMap; +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) { + instance = new StudentStore(); + } + return instance; + } + + public Student addStudent(Student student) { + int id = students.size(); + student.setId(id); + students.put(id, student); + return student; + } + + public Student getStudent(int id) { + return students.get(id); + } + + public Set getAllStudents() { + return new HashSet<>(students.values()); + } + + public Student updateStudent(Student student) { + int id = student.getId(); + if (students.containsKey(id)) { + students.put(id, student); + return student; + } + return null; + } + + public boolean deleteStudent(int id) { + 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/student-api/app/services/ApplicationTimer.java new file mode 100644 index 0000000000..a951562b1d --- /dev/null +++ b/play-framework/student-api/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/student-api/app/services/AtomicCounter.java b/play-framework/student-api/app/services/AtomicCounter.java new file mode 100644 index 0000000000..41f741cbf7 --- /dev/null +++ b/play-framework/student-api/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/student-api/app/services/Counter.java b/play-framework/student-api/app/services/Counter.java new file mode 100644 index 0000000000..dadad8b09d --- /dev/null +++ b/play-framework/student-api/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/student-api/app/util/Util.java b/play-framework/student-api/app/util/Util.java new file mode 100644 index 0000000000..a853a4cb43 --- /dev/null +++ b/play-framework/student-api/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/student-api/app/views/index.scala.html new file mode 100644 index 0000000000..4539f5a10b --- /dev/null +++ b/play-framework/student-api/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/student-api/app/views/main.scala.html b/play-framework/student-api/app/views/main.scala.html new file mode 100644 index 0000000000..9414f4be6e --- /dev/null +++ b/play-framework/student-api/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/student-api/bin/activator b/play-framework/student-api/bin/activator new file mode 100644 index 0000000000..a8b11d482f --- /dev/null +++ b/play-framework/student-api/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/student-api/build.sbt b/play-framework/student-api/build.sbt new file mode 100644 index 0000000000..0f5ea736f6 --- /dev/null +++ b/play-framework/student-api/build.sbt @@ -0,0 +1,13 @@ +name := """student-api""" + +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/student-api/conf/application.conf b/play-framework/student-api/conf/application.conf new file mode 100644 index 0000000000..489d3f9b3e --- /dev/null +++ b/play-framework/student-api/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/student-api/conf/logback.xml b/play-framework/student-api/conf/logback.xml new file mode 100644 index 0000000000..86ec12c0af --- /dev/null +++ b/play-framework/student-api/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/student-api/conf/routes b/play-framework/student-api/conf/routes new file mode 100644 index 0000000000..ab55792683 --- /dev/null +++ b/play-framework/student-api/conf/routes @@ -0,0 +1,12 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +GET / controllers.StudentController.listStudents() +POST /:id controllers.StudentController.retrieve(id:Int) +POST / controllers.StudentController.create() +PUT / controllers.StudentController.update() +DELETE /:id controllers.StudentController.delete(id:Int) + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/student-api/libexec/activator-launch-1.3.10.jar b/play-framework/student-api/libexec/activator-launch-1.3.10.jar new file mode 100644 index 0000000000..69050e7dec Binary files /dev/null and b/play-framework/student-api/libexec/activator-launch-1.3.10.jar differ diff --git a/play-framework/student-api/project/build.properties b/play-framework/student-api/project/build.properties new file mode 100644 index 0000000000..6d9fa6badb --- /dev/null +++ b/play-framework/student-api/project/build.properties @@ -0,0 +1,4 @@ +#Activator-generated Properties +#Wed Sep 07 12:29:40 EAT 2016 +template.uuid=c373963b-f5ad-433b-8e74-178e7ae25b1c +sbt.version=0.13.11 diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/student-api/project/plugins.sbt new file mode 100644 index 0000000000..51c5b2a35a --- /dev/null +++ b/play-framework/student-api/project/plugins.sbt @@ -0,0 +1,21 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.6") + +// 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.3") +addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7") +addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") +addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.2") + +// 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" % "1.0.0") diff --git a/play-framework/student-api/public/images/favicon.png b/play-framework/student-api/public/images/favicon.png new file mode 100644 index 0000000000..c7d92d2ae4 Binary files /dev/null and b/play-framework/student-api/public/images/favicon.png differ diff --git a/play-framework/student-api/public/javascripts/hello.js b/play-framework/student-api/public/javascripts/hello.js new file mode 100644 index 0000000000..02ee13c7ca --- /dev/null +++ b/play-framework/student-api/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/student-api/public/stylesheets/main.css similarity index 100% rename from couchbase-sdk-spring-service/src/main/resources/application.properties rename to play-framework/student-api/public/stylesheets/main.css diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java new file mode 100644 index 0000000000..1133978e9a --- /dev/null +++ b/play-framework/student-api/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/pom.xml b/pom.xml index daa92744ae..709c3e4e00 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -8,33 +9,40 @@ pom - + UTF-8 - + assertj apache-cxf - apache-fop + autovalue-tutorial + cdi core-java core-java-8 - couchbase-sdk-intro - couchbase-sdk-spring-service + couchbase-sdk + + dozer dependency-injection deltaspike + + patterns + feign-client gson - gson-jackson-performance guava guava18 guava19 + handling-spring-static-resources httpclient + immutables + jackson javaxval jjwt @@ -43,16 +51,24 @@ json json-path junit5 - mockito - mocks jee7schedule + + log4j + + mockito + mocks + mutation-testing + + orika + querydsl + rest-assured rest-testing resteasy - log4j + okhttp spring-all spring-akka @@ -63,7 +79,6 @@ spring-cucumber spring-data-cassandra spring-data-couchbase-2 - spring-data-couchbase-2b spring-data-elasticsearch spring-data-neo4j spring-data-mongodb @@ -74,12 +89,13 @@ spring-hibernate3 spring-hibernate4 spring-jpa - spring-jpa-jndi + spring-jms spring-katharsis spring-mockito spring-mvc-java spring-mvc-no-xml spring-mvc-xml + spring-mvc-tiles spring-openid spring-protobuf spring-quartz @@ -87,8 +103,8 @@ spring-rest spring-rest-angular spring-rest-docs - spring-cloud-config - spring-cloud-hystrix + spring-cloud + spring-cloud-data-flow spring-security-basic-auth spring-security-custom-permission @@ -106,17 +122,17 @@ spring-security-x509 spring-thymeleaf spring-zuul + spring-mvc-velocity + jsf xml lombok redis - webjars - mutation-testing - spring-mvc-velocity + wicket xstream - dozer - orika + java-cassandra + annotations diff --git a/rest-assured/pom.xml b/rest-assured/pom.xml index 47241b18bd..e2a2af9cd9 100644 --- a/rest-assured/pom.xml +++ b/rest-assured/pom.xml @@ -1,257 +1,226 @@ - 4.0.0 - com.baeldung - rest-assured - 1.0 - rest-assured - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - - javax.servlet - javax.servlet-api - 3.1-b06 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + rest-assured + 1.0 + rest-assured - - - javax.servlet - servlet-api - 2.5 - + + + javax.servlet + javax.servlet-api + 3.1-b06 + + + javax.servlet + servlet-api + 2.5 + + + org.eclipse.jetty + jetty-security + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlet + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlets + 9.2.0.M1 + + + org.eclipse.jetty + jetty-io + 9.2.0.M1 + + + org.eclipse.jetty + jetty-http + 9.2.0.M1 + + + org.eclipse.jetty + jetty-server + 9.2.0.M1 + + + org.eclipse.jetty + jetty-util + 9.2.0.M1 + - - - org.eclipse.jetty - jetty-security - 9.2.0.M1 - + + org.slf4j + slf4j-api + 1.7.21 + - - - org.eclipse.jetty - jetty-servlet - 9.2.0.M1 - + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-log4j12 + 1.7.21 + - - - org.eclipse.jetty - jetty-servlets - 9.2.0.M1 - + + commons-logging + commons-logging + 1.2 + - - - org.eclipse.jetty - jetty-io - 9.2.0.M1 - + + org.apache.httpcomponents + httpcore + 4.4.5 + - - - org.eclipse.jetty - jetty-http - 9.2.0.M1 - + + org.apache.commons + commons-lang3 + 3.4 + + + com.github.fge + uri-template + 0.9 + + + com.googlecode.libphonenumber + libphonenumber + 7.4.5 + - - - org.eclipse.jetty - jetty-server - 9.2.0.M1 - + + javax.mail + mail + 1.4.7 + - - - org.eclipse.jetty - jetty-util - 9.2.0.M1 - + + joda-time + joda-time + 2.9.4 + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - org.slf4j - slf4j-api - 1.7.21 - + + com.github.fge + msg-simple + 1.1 + - - - log4j - log4j - 1.2.17 - - - - org.slf4j - slf4j-log4j12 - 1.7.21 - + + com.github.fge + jackson-coreutils + 1.8 + - - - - commons-logging - commons-logging - 1.2 - + + com.google.guava + guava + ${guava.version} + + + com.github.fge + btf + 1.2 + - - org.apache.httpcomponents - httpcore - 4.4.5 - + + org.apache.httpcomponents + httpclient + 4.5.2 + - - - org.apache.commons - commons-lang3 - 3.4 - + + org.codehaus.groovy + groovy-all + 2.4.7 + - - - - com.github.fge - uri-template - 0.9 - + + com.github.tomakehurst + wiremock + 2.1.7 + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + json-schema-validator + 3.0.0 + + + com.github.fge + json-schema-validator + 2.2.6 + + + com.github.fge + json-schema-core + 1.2.5 + + + junit + junit + 4.3 + test + - - - com.googlecode.libphonenumber - libphonenumber - 7.4.5 - + + org.hamcrest + hamcrest-all + 1.3 + + + commons-collections + commons-collections + 3.2.2 + - - javax.mail - mail - 1.4.7 - + - - joda-time - joda-time - 2.9.4 - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 8 + 8 + + + + - - com.fasterxml.jackson.core - jackson-annotations - 2.8.0 - + + 2.8.3 + 19.0 + - - com.fasterxml.jackson.core - jackson-databind - 2.8.0 - - - - com.fasterxml.jackson.core - jackson-core - 2.8.0 - - - - com.github.fge - msg-simple - 1.1 - - - - com.github.fge - jackson-coreutils - 1.8 - - - - - - com.google.guava - guava - 18.0 - - - com.github.fge - btf - 1.2 - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - - org.codehaus.groovy - groovy-all - 2.4.7 - - - - com.github.tomakehurst - wiremock - 2.1.7 - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - json-schema-validator - 3.0.0 - - - com.github.fge - json-schema-validator - 2.2.6 - - - com.github.fge - json-schema-core - 1.2.5 - - - junit - junit - 4.3 - test - - - - org.hamcrest - hamcrest-all - 1.3 - - - - commons-collections - commons-collections - 3.2.2 - - - diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 652f2ab601..819e8de8a5 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -156,7 +156,7 @@ - 2.7.2 + 2.7.8 1.7.13 diff --git a/routing-in-play/.gitignore b/routing-in-play/.gitignore new file mode 100644 index 0000000000..eb372fc719 --- /dev/null +++ b/routing-in-play/.gitignore @@ -0,0 +1,8 @@ +logs +target +/.idea +/.idea_modules +/.classpath +/.project +/.settings +/RUNNING_PID diff --git a/routing-in-play/LICENSE b/routing-in-play/LICENSE new file mode 100644 index 0000000000..4baedcb95f --- /dev/null +++ b/routing-in-play/LICENSE @@ -0,0 +1,8 @@ +This software is licensed under the Apache 2 license, quoted below. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with +the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific +language governing permissions and limitations under the License. \ No newline at end of file diff --git a/routing-in-play/README b/routing-in-play/README new file mode 100644 index 0000000000..f21d092edf --- /dev/null +++ b/routing-in-play/README @@ -0,0 +1,49 @@ +This is your new Play application +================================= + +This file will be packaged with your application when using `activator dist`. + +There are several demonstration files available in this template. + +Controllers +=========== + +- HomeController.java: + + Shows how to handle simple HTTP requests. + +- AsyncController.java: + + Shows how to do asynchronous programming when handling a request. + +- CountController.java: + + Shows how to inject a component into a controller and use the component when + handling requests. + +Components +========== + +- Module.java: + + Shows how to use Guice to bind all the components needed by your application. + +- Counter.java: + + An example of a component that contains state, in this case a simple counter. + +- ApplicationTimer.java: + + An example of a component that starts when the application starts and stops + when the application stops. + +Filters +======= + +- Filters.java: + + Creates the list of HTTP filters used by your application. + +- ExampleFilter.java + + A simple filter that adds a header to every response. \ No newline at end of file diff --git a/routing-in-play/app/Filters.java b/routing-in-play/app/Filters.java new file mode 100644 index 0000000000..255de8ca93 --- /dev/null +++ b/routing-in-play/app/Filters.java @@ -0,0 +1,46 @@ +import javax.inject.*; +import play.*; +import play.mvc.EssentialFilter; +import play.http.HttpFilters; +import play.mvc.*; + +import filters.ExampleFilter; + +/** + * This class configures filters that run on every request. This + * class is queried by Play to get a list of filters. + * + * Play will automatically use filters from any class called + * Filters that is placed the root package. You can load filters + * from a different class by adding a `play.http.filters` setting to + * the application.conf configuration file. + */ +@Singleton +public class Filters implements HttpFilters { + + private final Environment env; + private final EssentialFilter exampleFilter; + + /** + * @param env Basic environment settings for the current application. + * @param exampleFilter A demonstration filter that adds a header to + */ + @Inject + public Filters(Environment env, ExampleFilter exampleFilter) { + this.env = env; + this.exampleFilter = exampleFilter; + } + + @Override + public EssentialFilter[] filters() { + // Use the example filter if we're running development mode. If + // we're running in production or test mode then don't use any + // filters at all. + if (env.mode().equals(Mode.DEV)) { + return new EssentialFilter[] { exampleFilter }; + } else { + return new EssentialFilter[] {}; + } + } + +} diff --git a/routing-in-play/app/Module.java b/routing-in-play/app/Module.java new file mode 100644 index 0000000000..6e7d1766ef --- /dev/null +++ b/routing-in-play/app/Module.java @@ -0,0 +1,31 @@ +import com.google.inject.AbstractModule; +import java.time.Clock; + +import services.ApplicationTimer; +import services.AtomicCounter; +import services.Counter; + +/** + * This class is a Guice module that tells Guice how to bind several + * different types. This Guice module is created when the Play + * application starts. + * + * Play will automatically use any class called `Module` that is in + * the root package. You can create modules in other locations by + * adding `play.modules.enabled` settings to the `application.conf` + * configuration file. + */ +public class Module extends AbstractModule { + + @Override + public void configure() { + // Use the system clock as the default implementation of Clock + bind(Clock.class).toInstance(Clock.systemDefaultZone()); + // Ask Guice to create an instance of ApplicationTimer when the + // application starts. + bind(ApplicationTimer.class).asEagerSingleton(); + // Set AtomicCounter as the implementation for Counter. + bind(Counter.class).to(AtomicCounter.class); + } + +} diff --git a/routing-in-play/app/controllers/HomeController.java b/routing-in-play/app/controllers/HomeController.java new file mode 100644 index 0000000000..6e340d594f --- /dev/null +++ b/routing-in-play/app/controllers/HomeController.java @@ -0,0 +1,33 @@ +package controllers; + +import play.mvc.*; + +import views.html.*; + +/** + * This controller contains an action to handle HTTP requests + * to the application's home page. + */ +public class HomeController extends Controller { + + /** + * An action that renders an HTML page with a welcome message. + * The configuration in the routes file means that + * this method will be called when the application receives a + * GET request with a path of /. + */ + public Result index(String author,int id) { + return ok("Routing in Play by:"+author+" ID:"+id); + } + public Result greet(String name,int age) { + return ok("Hello "+name+", you are "+age+" years old"); + } + public Result introduceMe(String data) { + String[] clientData=data.split(","); + return ok("Your name is "+clientData[0]+", you are "+clientData[1]+" years old"); + } + public Result squareMe(Long num) { + return ok(num+" Squared is "+(num*num)); + } + +} diff --git a/routing-in-play/app/filters/ExampleFilter.java b/routing-in-play/app/filters/ExampleFilter.java new file mode 100644 index 0000000000..67a6a36cc3 --- /dev/null +++ b/routing-in-play/app/filters/ExampleFilter.java @@ -0,0 +1,45 @@ +package filters; + +import akka.stream.Materializer; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Function; +import javax.inject.*; +import play.mvc.*; +import play.mvc.Http.RequestHeader; + + +/** + * This is a simple filter that adds a header to all requests. It's + * added to the application's list of filters by the + * {@link Filters} class. + */ +@Singleton +public class ExampleFilter extends Filter { + + private final Executor exec; + + /** + * @param mat This object is needed to handle streaming of requests + * and responses. + * @param exec This class is needed to execute code asynchronously. + * It is used below by the thenAsyncApply method. + */ + @Inject + public ExampleFilter(Materializer mat, Executor exec) { + super(mat); + this.exec = exec; + } + + @Override + public CompletionStage apply( + Function> next, + RequestHeader requestHeader) { + + return next.apply(requestHeader).thenApplyAsync( + result -> result.withHeader("X-ExampleFilter", "foo"), + exec + ); + } + +} diff --git a/routing-in-play/app/services/ApplicationTimer.java b/routing-in-play/app/services/ApplicationTimer.java new file mode 100644 index 0000000000..a951562b1d --- /dev/null +++ b/routing-in-play/app/services/ApplicationTimer.java @@ -0,0 +1,50 @@ +package services; + +import java.time.Clock; +import java.time.Instant; +import java.util.concurrent.CompletableFuture; +import javax.inject.*; +import play.Logger; +import play.inject.ApplicationLifecycle; + +/** + * This class demonstrates how to run code when the + * application starts and stops. It starts a timer when the + * application starts. When the application stops it prints out how + * long the application was running for. + * + * This class is registered for Guice dependency injection in the + * {@link Module} class. We want the class to start when the application + * starts, so it is registered as an "eager singleton". See the code + * in the {@link Module} class to see how this happens. + * + * This class needs to run code when the server stops. It uses the + * application's {@link ApplicationLifecycle} to register a stop hook. + */ +@Singleton +public class ApplicationTimer { + + private final Clock clock; + private final ApplicationLifecycle appLifecycle; + private final Instant start; + + @Inject + public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) { + this.clock = clock; + this.appLifecycle = appLifecycle; + // This code is called when the application starts. + start = clock.instant(); + Logger.info("ApplicationTimer demo: Starting application at " + start); + + // When the application starts, register a stop hook with the + // ApplicationLifecycle object. The code inside the stop hook will + // be run when the application stops. + appLifecycle.addStopHook(() -> { + Instant stop = clock.instant(); + Long runningTime = stop.getEpochSecond() - start.getEpochSecond(); + Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s."); + return CompletableFuture.completedFuture(null); + }); + } + +} diff --git a/routing-in-play/app/services/AtomicCounter.java b/routing-in-play/app/services/AtomicCounter.java new file mode 100644 index 0000000000..41f741cbf7 --- /dev/null +++ b/routing-in-play/app/services/AtomicCounter.java @@ -0,0 +1,26 @@ +package services; + +import java.util.concurrent.atomic.AtomicInteger; +import javax.inject.*; + +/** + * This class is a concrete implementation of the {@link Counter} trait. + * It is configured for Guice dependency injection in the {@link Module} + * class. + * + * This class has a {@link Singleton} annotation because we need to make + * sure we only use one counter per application. Without this + * annotation we would get a new instance every time a {@link Counter} is + * injected. + */ +@Singleton +public class AtomicCounter implements Counter { + + private final AtomicInteger atomicCounter = new AtomicInteger(); + + @Override + public int nextCount() { + return atomicCounter.getAndIncrement(); + } + +} diff --git a/routing-in-play/app/services/Counter.java b/routing-in-play/app/services/Counter.java new file mode 100644 index 0000000000..dadad8b09d --- /dev/null +++ b/routing-in-play/app/services/Counter.java @@ -0,0 +1,13 @@ +package services; + +/** + * This interface demonstrates how to create a component that is injected + * into a controller. The interface represents a counter that returns a + * incremented number each time it is called. + * + * The {@link Modules} class binds this interface to the + * {@link AtomicCounter} implementation. + */ +public interface Counter { + int nextCount(); +} diff --git a/routing-in-play/app/views/index.scala.html b/routing-in-play/app/views/index.scala.html new file mode 100644 index 0000000000..4539f5a10b --- /dev/null +++ b/routing-in-play/app/views/index.scala.html @@ -0,0 +1,20 @@ +@* + * This template takes a single argument, a String containing a + * message to display. + *@ +@(message: String) + +@* + * Call the `main` template with two arguments. The first + * argument is a `String` with the title of the page, the second + * argument is an `Html` object containing the body of the page. + *@ +@main("Welcome to Play") { + + @* + * Get an `Html` object by calling the built-in Play welcome + * template and passing a `String` message. + *@ + @play20.welcome(message, style = "Java") + +} diff --git a/routing-in-play/app/views/main.scala.html b/routing-in-play/app/views/main.scala.html new file mode 100644 index 0000000000..9414f4be6e --- /dev/null +++ b/routing-in-play/app/views/main.scala.html @@ -0,0 +1,23 @@ +@* + * This template is called from the `index` template. This template + * handles the rendering of the page header and body tags. It takes + * two arguments, a `String` for the title of the page and an `Html` + * object to insert into the body of the page. + *@ +@(title: String)(content: Html) + + + + + @* Here's where we render the page title `String`. *@ + @title + + + + + + @* And here's where we render the `Html` object containing + * the page content. *@ + @content + + diff --git a/routing-in-play/bin/activator b/routing-in-play/bin/activator new file mode 100644 index 0000000000..a8b11d482f --- /dev/null +++ b/routing-in-play/bin/activator @@ -0,0 +1,397 @@ +#!/usr/bin/env bash + +### ------------------------------- ### +### Helper methods for BASH scripts ### +### ------------------------------- ### + +realpath () { +( + TARGET_FILE="$1" + FIX_CYGPATH="$2" + + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + + COUNT=0 + while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ] + do + TARGET_FILE=$(readlink "$TARGET_FILE") + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + COUNT=$(($COUNT + 1)) + done + + # make sure we grab the actual windows path, instead of cygwin's path. + if [[ "x$FIX_CYGPATH" != "x" ]]; then + echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")" + else + echo "$(pwd -P)/$TARGET_FILE" + fi +) +} + + +# Uses uname to detect if we're in the odd cygwin environment. +is_cygwin() { + local os=$(uname -s) + case "$os" in + CYGWIN*) return 0 ;; + *) return 1 ;; + esac +} + +# TODO - Use nicer bash-isms here. +CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi) + + +# This can fix cygwin style /cygdrive paths so we get the +# windows style paths. +cygwinpath() { + local file="$1" + if [[ "$CYGWIN_FLAG" == "true" ]]; then + echo $(cygpath -w $file) + else + echo $file + fi +} + +# Make something URI friendly +make_url() { + url="$1" + local nospaces=${url// /%20} + if is_cygwin; then + echo "/${nospaces//\\//}" + else + echo "$nospaces" + fi +} + +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands +declare java_cmd=java +declare java_version +declare -r real_script_path="$(realpath "$0")" +declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")" +declare -r sbt_bin_dir="$(dirname "$real_script_path")" +declare -r app_version="1.3.10" + +declare -r script_name=activator +declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" ) +userhome="$HOME" +if is_cygwin; then + # cygwin sets home to something f-d up, set to real windows homedir + userhome="$USERPROFILE" +fi +declare -r activator_user_home_dir="${userhome}/.activator" +declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt" +declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt" + +echoerr () { + echo 1>&2 "$@" +} +vlog () { + [[ $verbose || $debug ]] && echoerr "$@" +} +dlog () { + [[ $debug ]] && echoerr "$@" +} + +jar_file () { + echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")" +} + +acquire_sbt_jar () { + sbt_jar="$(jar_file)" + + if [[ ! -f "$sbt_jar" ]]; then + echoerr "Could not find launcher jar: $sbt_jar" + exit 2 + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + [[ $verbose || $debug ]] && echo "# Executing command line:" && { + for arg; do + if printf "%s\n" "$arg" | grep -q ' '; then + printf "\"%s\"\n" "$arg" + else + printf "%s\n" "$arg" + fi + done + echo "" + } + + # THis used to be exec, but we loose the ability to re-hook stty then + # for cygwin... Maybe we should flag the feature here... + "$@" +} + +addJava () { + dlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + dlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +addResidual () { + dlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addDebugger () { + addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1" +} + +get_mem_opts () { + # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings. + # The reason is the Xms/Xmx, if they don't line up, cause errors. + if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then + echo "" + else + # a ham-fisted attempt to move some memory settings in concert + # so they need not be messed around with individually. + local mem=${1:-1024} + local codecache=$(( $mem / 8 )) + (( $codecache > 128 )) || codecache=128 + (( $codecache < 512 )) || codecache=512 + local class_metadata_size=$(( $codecache * 2 )) + local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize") + + echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m" + fi +} + +require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + echo "$opt requires <$type> argument" + exit 1 + fi +} + +is_function_defined() { + declare -f "$1" > /dev/null +} + +# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter +detect_terminal_for_ui() { + [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && { + addResidual "ui" + } + # SPECIAL TEST FOR MAC + [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && { + echo "Detected MAC OSX launched script...." + echo "Swapping to UI" + addResidual "ui" + } +} + +process_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v|-verbose) verbose=1 && shift ;; + -d|-debug) debug=1 && shift ;; + + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; + -batch) exec &1 | awk -F '"' '/version/ {print $2}') + vlog "[process_args] java_version = '$java_version'" +} + +# Detect that we have java installed. +checkJava() { + local required_version="$1" + # Now check to see if it's a good enough version + if [[ "$java_version" == "" ]]; then + echo + echo No java installations was detected. + echo Please go to http://www.java.com/getjava/ and download + echo + exit 1 + elif [[ ! "$java_version" > "$required_version" ]]; then + echo + echo The java installation you have is not up to date + echo $script_name requires at least version $required_version+, you have + echo version $java_version + echo + echo Please go to http://www.java.com/getjava/ and download + echo a valid Java Runtime and install before running $script_name. + echo + exit 1 + fi +} + + +run() { + # no jar? download it. + [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || { + # still no jar? uh-oh. + echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar" + exit 1 + } + + # process the combined args, then reset "$@" to the residuals + process_args "$@" + detect_terminal_for_ui + set -- "${residual_args[@]}" + argumentCount=$# + + # TODO - java check should be configurable... + checkJava "1.6" + + #If we're in cygwin, we should use the windows config, and terminal hacks + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty -icanon min 1 -echo > /dev/null 2>&1 + addJava "-Djline.terminal=jline.UnixTerminal" + addJava "-Dsbt.cygwin=true" + fi + + # run sbt + execRunner "$java_cmd" \ + "-Dactivator.home=$(make_url "$sbt_home")" \ + ${SBT_OPTS:-$default_sbt_opts} \ + $(get_mem_opts $sbt_mem) \ + ${JAVA_OPTS} \ + ${java_args[@]} \ + -jar "$sbt_jar" \ + "${sbt_commands[@]}" \ + "${residual_args[@]}" + + exit_code=$? + + # Clean up the terminal from cygwin hacks. + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty icanon echo > /dev/null 2>&1 + fi + exit $exit_code +} + + +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r sbt_opts_file=".sbtopts" +declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts" +declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt" + +usage() { + cat < path to global settings/plugins directory (default: ~/.sbt) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series) + -ivy path to local Ivy repository (default: ~/.ivy2) + -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem)) + -no-share use all local caches; no sharing + -no-global uses global caches, but does not use global ~/.sbt directory. + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + + # sbt version (default: from project/build.properties if present, else latest release) + -sbt-version use the specified version of sbt + -sbt-jar use the specified jar as the sbt launcher + -sbt-rc use an RC version of sbt + -sbt-snapshot use a snapshot version of sbt + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # jvm options and output control + JAVA_OPTS environment variable, if unset uses "$java_opts" + SBT_OPTS environment variable, if unset uses "$default_sbt_opts" + ACTIVATOR_OPTS Environment variable, if unset uses "" + .sbtopts if this file exists in the current directory, it is + prepended to the runner args + /etc/sbt/sbtopts if this file exists, it is prepended to the runner args + -Dkey=val pass -Dkey=val directly to the java runtime + -J-X pass option -X directly to the java runtime + (-J is stripped) + -S-X add -X to sbt's scalacOptions (-S is stripped) + +In the case of duplicated or conflicting options, the order above +shows precedence: JAVA_OPTS lowest, command line options highest. +EOM +} + + + +process_my_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) addJava "$noshare_opts" && shift ;; + -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -batch) exec ^&1') do ( + if %%~j==java set JAVAINSTALLED=1 + if %%~j==openjdk set JAVAINSTALLED=1 +) + +rem Detect the same thing about javac +if "%_JAVACCMD%"=="" ( + if not "%JAVA_HOME%"=="" ( + if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe" + ) +) +if "%_JAVACCMD%"=="" set _JAVACCMD=javac +for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do ( + if %%~j==javac set JAVACINSTALLED=1 +) + +rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style +set JAVAOK=true +if not defined JAVAINSTALLED set JAVAOK=false +if not defined JAVACINSTALLED set JAVAOK=false + +if "%JAVAOK%"=="false" ( + echo. + echo A Java JDK is not installed or can't be found. + if not "%JAVA_HOME%"=="" ( + echo JAVA_HOME = "%JAVA_HOME%" + ) + echo. + echo Please go to + echo http://www.oracle.com/technetwork/java/javase/downloads/index.html + echo and download a valid Java JDK and install before running Activator. + echo. + echo If you think this message is in error, please check + echo your environment variables to see if "java.exe" and "javac.exe" are + echo available via JAVA_HOME or PATH. + echo. + if defined DOUBLECLICKED pause + exit /B 1 +) + +rem Check what Java version is being used to determine what memory options to use +for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( + set JAVA_VERSION=%%g +) + +rem Strips away the " characters +set JAVA_VERSION=%JAVA_VERSION:"=% + +rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below +for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do ( + set MAJOR=%%v + set MINOR=%%w + set BUILD=%%x + + set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M + if "!MINOR!" LSS "8" ( + set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M + ) + + set MEM_OPTS=!META_SIZE! + ) + +rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. +set _JAVA_OPTS=%JAVA_OPTS% +if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% + +set DEBUG_OPTS= + +rem Loop through the arguments, building remaining args in args variable +set args= +:argsloop +if not "%~1"=="" ( + rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them. + rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack. + set arg1=%~1 + if "!arg1:~0,2!"=="-D" ( + set "args=%args% "%~1"="%~2"" + shift + shift + goto argsloop + ) + + if "%~1"=="-jvm-debug" ( + if not "%~2"=="" ( + rem This piece of magic somehow checks that an argument is a number + for /F "delims=0123456789" %%i in ("%~2") do ( + set var="%%i" + ) + if defined var ( + rem Not a number, assume no argument given and default to 9999 + set JPDA_PORT=9999 + ) else ( + rem Port was given, shift arguments + set JPDA_PORT=%~2 + shift + ) + ) else ( + set JPDA_PORT=9999 + ) + shift + + set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT! + goto argsloop + ) + rem else + set "args=%args% "%~1"" + shift + goto argsloop +) + +:run + +if "!args!"=="" ( + if defined DOUBLECLICKED ( + set CMDS="ui" + ) else set CMDS=!args! +) else set CMDS=!args! + +rem We add a / in front, so we get file:///C: instead of file://C: +rem Java considers the later a UNC path. +rem We also attempt a solid effort at making it URI friendly. +rem We don't even bother with UNC paths. +set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/! +set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20! + +rem Checks if the command contains spaces to know if it should be wrapped in quotes or not +set NON_SPACED_CMD=%_JAVACMD: =% +if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% +if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% + +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end + +@endlocal + +exit /B %ERROR_CODE% diff --git a/routing-in-play/build.sbt b/routing-in-play/build.sbt new file mode 100644 index 0000000000..083d071676 --- /dev/null +++ b/routing-in-play/build.sbt @@ -0,0 +1,13 @@ +name := """webapp""" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.11.7" + +libraryDependencies ++= Seq( + javaJdbc, + cache, + javaWs +) diff --git a/routing-in-play/conf/application.conf b/routing-in-play/conf/application.conf new file mode 100644 index 0000000000..489d3f9b3e --- /dev/null +++ b/routing-in-play/conf/application.conf @@ -0,0 +1,353 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile +# ~~~~~ +# Play uses HOCON as its configuration file format. HOCON has a number +# of advantages over other config formats, but there are two things that +# can be used when modifying settings. +# +# You can include other configuration files in this main application.conf file: +#include "extra-config.conf" +# +# You can declare variables and substitute for them: +#mykey = ${some.value} +# +# And if an environment variable exists when there is no other subsitution, then +# HOCON will fall back to substituting environment variable: +#mykey = ${JAVA_HOME} + +## Akka +# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration +# https://www.playframework.com/documentation/latest/JavaAkka#Configuration +# ~~~~~ +# Play uses Akka internally and exposes Akka Streams and actors in Websockets and +# other streaming HTTP responses. +akka { + # "akka.log-config-on-start" is extraordinarly useful because it log the complete + # configuration at INFO level, including defaults and overrides, so it s worth + # putting at the very top. + # + # Put the following in your conf/logback.xml file: + # + # + # + # And then uncomment this line to debug the configuration. + # + #log-config-on-start = true +} + +## Secret key +# http://www.playframework.com/documentation/latest/ApplicationSecret +# ~~~~~ +# The secret key is used to sign Play's session cookie. +# This must be changed for production, but we don't recommend you change it in this file. +play.crypto.secret = "changeme" + +## Modules +# https://www.playframework.com/documentation/latest/Modules +# ~~~~~ +# Control which modules are loaded when Play starts. Note that modules are +# the replacement for "GlobalSettings", which are deprecated in 2.5.x. +# Please see https://www.playframework.com/documentation/latest/GlobalSettings +# for more information. +# +# You can also extend Play functionality by using one of the publically available +# Play modules: https://playframework.com/documentation/latest/ModuleDirectory +play.modules { + # By default, Play will load any class called Module that is defined + # in the root package (the "app" directory), or you can define them + # explicitly below. + # If there are any built-in modules that you want to disable, you can list them here. + #enabled += my.application.Module + + # If there are any built-in modules that you want to disable, you can list them here. + #disabled += "" +} + +## IDE +# https://www.playframework.com/documentation/latest/IDE +# ~~~~~ +# Depending on your IDE, you can add a hyperlink for errors that will jump you +# directly to the code location in the IDE in dev mode. The following line makes +# use of the IntelliJ IDEA REST interface: +#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" + +## Internationalisation +# https://www.playframework.com/documentation/latest/JavaI18N +# https://www.playframework.com/documentation/latest/ScalaI18N +# ~~~~~ +# Play comes with its own i18n settings, which allow the user's preferred language +# to map through to internal messages, or allow the language to be stored in a cookie. +play.i18n { + # The application languages + langs = [ "en" ] + + # Whether the language cookie should be secure or not + #langCookieSecure = true + + # Whether the HTTP only attribute of the cookie should be set to true + #langCookieHttpOnly = true +} + +## Play HTTP settings +# ~~~~~ +play.http { + ## Router + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # Define the Router object to use for this application. + # This router will be looked up first when the application is starting up, + # so make sure this is the entry point. + # Furthermore, it's assumed your route file is named properly. + # So for an application router like `my.application.Router`, + # you may need to define a router file `conf/my.application.routes`. + # Default to Routes in the root package (aka "apps" folder) (and conf/routes) + #router = my.application.Router + + ## Action Creator + # https://www.playframework.com/documentation/latest/JavaActionCreator + # ~~~~~ + #actionCreator = null + + ## ErrorHandler + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # If null, will attempt to load a class called ErrorHandler in the root package, + #errorHandler = null + + ## Filters + # https://www.playframework.com/documentation/latest/ScalaHttpFilters + # https://www.playframework.com/documentation/latest/JavaHttpFilters + # ~~~~~ + # Filters run code on every request. They can be used to perform + # common logic for all your actions, e.g. adding common headers. + # Defaults to "Filters" in the root package (aka "apps" folder) + # Alternatively you can explicitly register a class here. + #filters = my.application.Filters + + ## Session & Flash + # https://www.playframework.com/documentation/latest/JavaSessionFlash + # https://www.playframework.com/documentation/latest/ScalaSessionFlash + # ~~~~~ + session { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + + # Sets the max-age field of the cookie to 5 minutes. + # NOTE: this only sets when the browser will discard the cookie. Play will consider any + # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, + # you need to put a timestamp in the session and check it at regular intervals to possibly expire it. + #maxAge = 300 + + # Sets the domain on the session cookie. + #domain = "example.com" + } + + flash { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + } +} + +## Netty Provider +# https://www.playframework.com/documentation/latest/SettingsNetty +# ~~~~~ +play.server.netty { + # Whether the Netty wire should be logged + #log.wire = true + + # If you run Play on Linux, you can use Netty's native socket transport + # for higher performance with less garbage. + #transport = "native" +} + +## WS (HTTP Client) +# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS +# ~~~~~ +# The HTTP client primarily used for REST APIs. The default client can be +# configured directly, but you can also create different client instances +# with customized settings. You must enable this by adding to build.sbt: +# +# libraryDependencies += ws // or javaWs if using java +# +play.ws { + # Sets HTTP requests not to follow 302 requests + #followRedirects = false + + # Sets the maximum number of open HTTP connections for the client. + #ahc.maxConnectionsTotal = 50 + + ## WS SSL + # https://www.playframework.com/documentation/latest/WsSSL + # ~~~~~ + ssl { + # Configuring HTTPS with Play WS does not require programming. You can + # set up both trustManager and keyManager for mutual authentication, and + # turn on JSSE debugging in development with a reload. + #debug.handshake = true + #trustManager = { + # stores = [ + # { type = "JKS", path = "exampletrust.jks" } + # ] + #} + } +} + +## Cache +# https://www.playframework.com/documentation/latest/JavaCache +# https://www.playframework.com/documentation/latest/ScalaCache +# ~~~~~ +# Play comes with an integrated cache API that can reduce the operational +# overhead of repeated requests. You must enable this by adding to build.sbt: +# +# libraryDependencies += cache +# +play.cache { + # If you want to bind several caches, you can bind the individually + #bindCaches = ["db-cache", "user-cache", "session-cache"] +} + +## Filters +# https://www.playframework.com/documentation/latest/Filters +# ~~~~~ +# There are a number of built-in filters that can be enabled and configured +# to give Play greater security. You must enable this by adding to build.sbt: +# +# libraryDependencies += filters +# +play.filters { + ## CORS filter configuration + # https://www.playframework.com/documentation/latest/CorsFilter + # ~~~~~ + # CORS is a protocol that allows web applications to make requests from the browser + # across different domains. + # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has + # dependencies on CORS settings. + cors { + # Filter paths by a whitelist of path prefixes + #pathPrefixes = ["/some/path", ...] + + # The allowed origins. If null, all origins are allowed. + #allowedOrigins = ["http://www.example.com"] + + # The allowed HTTP methods. If null, all methods are allowed + #allowedHttpMethods = ["GET", "POST"] + } + + ## CSRF Filter + # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter + # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter + # ~~~~~ + # Play supports multiple methods for verifying that a request is not a CSRF request. + # The primary mechanism is a CSRF token. This token gets placed either in the query string + # or body of every form submitted, and also gets placed in the users session. + # Play then verifies that both tokens are present and match. + csrf { + # Sets the cookie to be sent only over HTTPS + #cookie.secure = true + + # Defaults to CSRFErrorHandler in the root package. + #errorHandler = MyCSRFErrorHandler + } + + ## Security headers filter configuration + # https://www.playframework.com/documentation/latest/SecurityHeaders + # ~~~~~ + # Defines security headers that prevent XSS attacks. + # If enabled, then all options are set to the below configuration by default: + headers { + # The X-Frame-Options header. If null, the header is not set. + #frameOptions = "DENY" + + # The X-XSS-Protection header. If null, the header is not set. + #xssProtection = "1; mode=block" + + # The X-Content-Type-Options header. If null, the header is not set. + #contentTypeOptions = "nosniff" + + # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. + #permittedCrossDomainPolicies = "master-only" + + # The Content-Security-Policy header. If null, the header is not set. + #contentSecurityPolicy = "default-src 'self'" + } + + ## Allowed hosts filter configuration + # https://www.playframework.com/documentation/latest/AllowedHostsFilter + # ~~~~~ + # Play provides a filter that lets you configure which hosts can access your application. + # This is useful to prevent cache poisoning attacks. + hosts { + # Allow requests to example.com, its subdomains, and localhost:9000. + #allowed = [".example.com", "localhost:9000"] + } +} + +## Evolutions +# https://www.playframework.com/documentation/latest/Evolutions +# ~~~~~ +# Evolutions allows database scripts to be automatically run on startup in dev mode +# for database migrations. You must enable this by adding to build.sbt: +# +# libraryDependencies += evolutions +# +play.evolutions { + # You can disable evolutions for a specific datasource if necessary + #db.default.enabled = false +} + +## Database Connection Pool +# https://www.playframework.com/documentation/latest/SettingsJDBC +# ~~~~~ +# Play doesn't require a JDBC database to run, but you can easily enable one. +# +# libraryDependencies += jdbc +# +play.db { + # The combination of these two settings results in "db.default" as the + # default JDBC pool: + #config = "db" + #default = "default" + + # Play uses HikariCP as the default connection pool. You can override + # settings by changing the prototype: + prototype { + # Sets a fixed JDBC connection pool size of 50 + #hikaricp.minimumIdle = 50 + #hikaricp.maximumPoolSize = 50 + } +} + +## JDBC Datasource +# https://www.playframework.com/documentation/latest/JavaDatabase +# https://www.playframework.com/documentation/latest/ScalaDatabase +# ~~~~~ +# Once JDBC datasource is set up, you can work with several different +# database options: +# +# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick +# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA +# EBean: https://playframework.com/documentation/latest/JavaEbean +# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm +# +db { + # You can declare as many datasources as you want. + # By convention, the default datasource is named `default` + + # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database + #default.driver = org.h2.Driver + #default.url = "jdbc:h2:mem:play" + #default.username = sa + #default.password = "" + + # You can turn on SQL logging for any datasource + # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements + #default.logSql=true +} diff --git a/routing-in-play/conf/logback.xml b/routing-in-play/conf/logback.xml new file mode 100644 index 0000000000..86ec12c0af --- /dev/null +++ b/routing-in-play/conf/logback.xml @@ -0,0 +1,41 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/routing-in-play/conf/routes b/routing-in-play/conf/routes new file mode 100644 index 0000000000..f72d8a1a14 --- /dev/null +++ b/routing-in-play/conf/routes @@ -0,0 +1,7 @@ +GET / controllers.HomeController.index(author="Baeldung",id:Int?=1) +GET /:author controllers.HomeController.index(author,id:Int?=1) +GET /greet/:name/:age controllers.HomeController.greet(name,age:Integer) +GET /square/$num<[0-9]+> controllers.HomeController.squareMe(num:Long) +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) +GET /*data controllers.HomeController.introduceMe(data) diff --git a/routing-in-play/libexec/activator-launch-1.3.10.jar b/routing-in-play/libexec/activator-launch-1.3.10.jar new file mode 100644 index 0000000000..69050e7dec Binary files /dev/null and b/routing-in-play/libexec/activator-launch-1.3.10.jar differ diff --git a/routing-in-play/project/build.properties b/routing-in-play/project/build.properties new file mode 100644 index 0000000000..6d22e3f2d1 --- /dev/null +++ b/routing-in-play/project/build.properties @@ -0,0 +1,4 @@ +#Activator-generated Properties +#Fri Sep 30 14:25:10 EAT 2016 +template.uuid=26c759a5-daf0-4e02-bcfa-ac69725267c0 +sbt.version=0.13.11 diff --git a/routing-in-play/project/plugins.sbt b/routing-in-play/project/plugins.sbt new file mode 100644 index 0000000000..e8e7f602f7 --- /dev/null +++ b/routing-in-play/project/plugins.sbt @@ -0,0 +1,21 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.8") + +// Web plugins +addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.4") +addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.8") +addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.1") +addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") +addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.6") + +// Play enhancer - this automatically generates getters/setters for public fields +// and rewrites accessors of these fields to use the getters/setters. Remove this +// plugin if you prefer not to have this feature, or disable on a per project +// basis using disablePlugins(PlayEnhancer) in your build.sbt +addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0") + +// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using +// enablePlugins(PlayEbean). +// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.2") diff --git a/routing-in-play/public/images/favicon.png b/routing-in-play/public/images/favicon.png new file mode 100644 index 0000000000..c7d92d2ae4 Binary files /dev/null and b/routing-in-play/public/images/favicon.png differ diff --git a/routing-in-play/public/javascripts/hello.js b/routing-in-play/public/javascripts/hello.js new file mode 100644 index 0000000000..02ee13c7ca --- /dev/null +++ b/routing-in-play/public/javascripts/hello.js @@ -0,0 +1,3 @@ +if (window.console) { + console.log("Welcome to your Play application's JavaScript!"); +} diff --git a/routing-in-play/public/stylesheets/main.css b/routing-in-play/public/stylesheets/main.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/routing-in-play/test/ApplicationTest.java b/routing-in-play/test/ApplicationTest.java new file mode 100644 index 0000000000..3d7c4875aa --- /dev/null +++ b/routing-in-play/test/ApplicationTest.java @@ -0,0 +1,45 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.*; + +import play.mvc.*; +import play.test.*; +import play.data.DynamicForm; +import play.data.validation.ValidationError; +import play.data.validation.Constraints.RequiredValidator; +import play.i18n.Lang; +import play.libs.F; +import play.libs.F.*; +import play.twirl.api.Content; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + + +/** + * + * Simple (JUnit) tests that can call all parts of a play app. + * If you are interested in mocking a whole application, see the wiki for more details. + * + */ +public class ApplicationTest { + + @Test + public void simpleCheck() { + int a = 1 + 1; + assertEquals(2, a); + } + + @Test + public void renderTemplate() { + Content html = views.html.index.render("Your new application is ready."); + assertEquals("text/html", html.contentType()); + assertTrue(html.body().contains("Your new application is ready.")); + } + + +} diff --git a/routing-in-play/test/IntegrationTest.java b/routing-in-play/test/IntegrationTest.java new file mode 100644 index 0000000000..c53c71e124 --- /dev/null +++ b/routing-in-play/test/IntegrationTest.java @@ -0,0 +1,25 @@ +import org.junit.*; + +import play.mvc.*; +import play.test.*; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + +import static org.fluentlenium.core.filter.FilterConstructor.*; + +public class IntegrationTest { + + /** + * add your integration test here + * in this example we just check if the welcome page is being shown + */ + @Test + public void test() { + running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { + browser.goTo("http://localhost:3333"); + assertTrue(browser.pageSource().contains("Your new application is ready.")); + }); + } + +} diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java index 624e289812..aa5941c763 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java +++ b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java @@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId - 4.0.0 - com.baeldung - spring-all - 0.1-SNAPSHOT + + 4.0.0 + com.baeldung + spring-all + 0.1-SNAPSHOT - spring-all - war + spring-all + war - - org.springframework.boot - spring-boot-starter-parent - 1.3.6.RELEASE - + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + - - - com.fasterxml.jackson.core - jackson-databind - + + + com.fasterxml.jackson.core + jackson-databind + - + - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework - spring-orm - - - org.springframework - spring-context - + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-orm + + + org.springframework + spring-context + - + - - org.springframework - spring-aspects - + + org.springframework + spring-aspects + - + - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.javassist - javassist - - - mysql - mysql-connector-java - runtime - - - org.hsqldb - hsqldb - - - + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.javassist + javassist + + + mysql + mysql-connector-java + runtime + + + org.hsqldb + hsqldb + - - org.hibernate - hibernate-validator - + - + + org.hibernate + hibernate-validator + - - javax.servlet - javax.servlet-api - provided - + - - javax.servlet - jstl - runtime - + + javax.servlet + javax.servlet-api + provided + - + + javax.servlet + jstl + runtime + - - com.google.guava - guava - ${guava.version} - - - + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - - org.slf4j - jcl-over-slf4j - - - - org.slf4j - log4j-over-slf4j - + + com.google.guava + guava + ${guava.version} + - + - - org.springframework - spring-test - test - + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + - - junit - junit - test - + - - org.assertj - assertj-core - 3.5.1 - test - + + org.springframework + spring-test + test + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + junit + junit + test + - - org.mockito - mockito-core - test - + + org.assertj + assertj-core + 3.5.1 + test + - - org.easymock - easymock - 3.4 - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - + + org.mockito + mockito-core + test + - + + org.easymock + easymock + 3.4 + test + + + org.ehcache + ehcache + 3.1.3 + - + - - org.springframework - spring-framework-bom - ${org.springframework.version} - pom - import - + - - org.springframework - spring-core - ${org.springframework.version} - + - + + org.springframework + spring-framework-bom + ${org.springframework.version} + pom + import + - + + org.springframework + spring-core + ${org.springframework.version} + - - spring-all - - - src/main/resources - true - - + - + - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + spring-all + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-war-plugin - - false - - + - - org.apache.maven.plugins - maven-surefire-plugin - - - - - - - - - + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.apache.maven.plugins + maven-war-plugin + + false + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + + + + + + + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + - - - 4.3.1.RELEASE - 4.0.4.RELEASE - 3.20.0-GA - 1.2 + - - 4.3.11.Final - 5.1.38 + - - 1.7.13 - 1.1.3 + + + 4.3.1.RELEASE + 4.0.4.RELEASE + 3.20.0-GA + 1.2 - - 5.2.2.Final + + 4.3.11.Final + 5.1.38 - - 19.0 - 3.4 + + 1.7.13 + 1.1.3 - - 1.3 - 4.12 - 1.10.19 + + 5.2.2.Final - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + 4.4.1 + 4.5 - + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java index 38b5a5a3ec..02b8c3c159 100644 --- a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java +++ b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java @@ -72,5 +72,5 @@ public abstract class AbstractService { public String getAddress5(final Customer customer) { return customer.getAddress(); } - + } diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index 443635fb70..ec6cf19785 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -11,21 +11,21 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class StudentControllerConfig implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(WebConfig.class); - root.setServletContext(sc); + @Override + public void onStartup(ServletContext sc) throws ServletException { + AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.register(WebConfig.class); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + root.setServletContext(sc); - DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); - ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/test/*"); - } + DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); + appServlet.setLoadOnStartup(1); + appServlet.addMapping("/test/*"); + } } diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java index f55af69c88..251a1affa1 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -11,13 +11,13 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" }) +@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } - + @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); diff --git a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java index 95903bcc40..4b38b4dd34 100644 --- a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java +++ b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java @@ -7,15 +7,15 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; @Controller -public class RestController{ +public class RestController { - @GetMapping(value="/student/{studentId}") - public @ResponseBody Student getTestData(@PathVariable Integer studentId) { - Student student = new Student(); - student.setName("Peter"); - student.setId(studentId); + @GetMapping(value = "/student/{studentId}") + public @ResponseBody Student getTestData(@PathVariable Integer studentId) { + Student student = new Student(); + student.setName("Peter"); + student.setId(studentId); - return student; + return student; - } + } } diff --git a/spring-all/src/main/java/org/baeldung/controller/student/Student.java b/spring-all/src/main/java/org/baeldung/controller/student/Student.java index ee706d7028..5f49e5ceb9 100644 --- a/spring-all/src/main/java/org/baeldung/controller/student/Student.java +++ b/spring-all/src/main/java/org/baeldung/controller/student/Student.java @@ -1,33 +1,33 @@ package org.baeldung.controller.student; public class Student { - private String name; - - private int id; + private String name; - public String getName() { - return name; - } + private int id; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int getId() { - return id; - } + public void setName(String name) { + this.name = name; + } - public void setId(int id) { - this.id = id; - } - - @Override - public int hashCode(){ - return this.id; - } - - @Override - public boolean equals(Object obj){ - return this.name.equals(((Student)obj).getName()); - } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + return this.id; + } + + @Override + public boolean equals(Object obj) { + return this.name.equals(((Student) obj).getName()); + } } \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/ehcache/app/App.java b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java new file mode 100755 index 0000000000..99370186a3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java @@ -0,0 +1,24 @@ +package org.baeldung.ehcache.app; + +import org.baeldung.ehcache.calculator.SquaredCalculator; +import org.baeldung.ehcache.config.CacheHelper; + +public class App { + + public static void main(String[] args) { + + SquaredCalculator squaredCalculator = new SquaredCalculator(); + CacheHelper cacheHelper = new CacheHelper(); + + squaredCalculator.setCache(cacheHelper); + + calculate(squaredCalculator); + calculate(squaredCalculator); + } + + private static void calculate(SquaredCalculator squaredCalculator) { + for (int i = 10; i < 15; i++) { + System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } +} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java new file mode 100755 index 0000000000..25957539df --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java @@ -0,0 +1,24 @@ +package org.baeldung.ehcache.calculator; + +import org.baeldung.ehcache.config.CacheHelper; + +public class SquaredCalculator { + private CacheHelper cache; + + public int getSquareValueOfNumber(int input) { + if (cache.getSquareNumberCache().containsKey(input)) { + return cache.getSquareNumberCache().get(input); + } + + System.out.println("Calculating square value of " + input + " and caching result."); + + int squaredValue = (int) Math.pow(input, 2); + cache.getSquareNumberCache().put(input, squaredValue); + + return squaredValue; + } + + public void setCache(CacheHelper cache) { + this.cache = cache; + } +} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java new file mode 100755 index 0000000000..387a57880b --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java @@ -0,0 +1,25 @@ +package org.baeldung.ehcache.config; + +import org.ehcache.Cache; +import org.ehcache.CacheManager; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; + +public class CacheHelper { + + private CacheManager cacheManager; + private Cache squareNumberCache; + + public CacheHelper() { + cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))).build(); + cacheManager.init(); + + squareNumberCache = cacheManager.getCache("squaredNumber", Integer.class, Integer.class); + } + + public Cache getSquareNumberCache() { + return squareNumberCache; + } + +} diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java index f96184a8a3..97d7fe0ffa 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java @@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer { super(); } - @Bean public PropertyPlaceholderConfigurer propertyConfigurer() { final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer(); diff --git a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java index ae1c6157db..562069bc9a 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java +++ b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java @@ -2,14 +2,14 @@ package org.baeldung.scopes; public class HelloMessageGenerator { - private String message; + private String message; - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(final String message) { - this.message = message; - } + public void setMessage(final String message) { + this.message = message; + } } diff --git a/spring-all/src/main/java/org/baeldung/scopes/Person.java b/spring-all/src/main/java/org/baeldung/scopes/Person.java index e6139c31dd..b070007a5c 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/Person.java +++ b/spring-all/src/main/java/org/baeldung/scopes/Person.java @@ -1,27 +1,27 @@ package org.baeldung.scopes; public class Person { - private String name; - private int age; + private String name; + private int age; - public Person() { - } + public Person() { + } - public Person(final String name, final int age) { - this.name = name; - } + public Person(final String name, final int age) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - @Override - public String toString() { - return "Person [name=" + name + "]"; - } + @Override + public String toString() { + return "Person [name=" + name + "]"; + } } diff --git a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java index bf733b75f9..1e3d5f3b14 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java +++ b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java @@ -9,23 +9,23 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ScopesController { - public static final Logger LOG = Logger.getLogger(ScopesController.class); + public static final Logger LOG = Logger.getLogger(ScopesController.class); - @Resource(name = "requestMessage") - HelloMessageGenerator requestMessage; + @Resource(name = "requestMessage") + HelloMessageGenerator requestMessage; - @Resource(name = "sessionMessage") - HelloMessageGenerator sessionMessage; + @Resource(name = "sessionMessage") + HelloMessageGenerator sessionMessage; - @RequestMapping("/scopes") - public String getScopes(final Model model) { - LOG.info("Request Message:" + requestMessage.getMessage()); - LOG.info("Session Message" + sessionMessage.getMessage()); - requestMessage.setMessage("Good morning!"); - sessionMessage.setMessage("Good afternoon!"); - model.addAttribute("requestMessage", requestMessage.getMessage()); - model.addAttribute("sessionMessage", sessionMessage.getMessage()); - return "scopesExample"; - } + @RequestMapping("/scopes") + public String getScopes(final Model model) { + LOG.info("Request Message:" + requestMessage.getMessage()); + LOG.info("Session Message" + sessionMessage.getMessage()); + requestMessage.setMessage("Good morning!"); + sessionMessage.setMessage("Good afternoon!"); + model.addAttribute("requestMessage", requestMessage.getMessage()); + model.addAttribute("sessionMessage", sessionMessage.getMessage()); + return "scopesExample"; + } } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index 5a9b266388..a9bc298db3 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -16,42 +16,42 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver; @ComponentScan("org.baeldung.scopes") @EnableWebMvc public class ScopesConfig { - @Bean - public UrlBasedViewResolver setupViewResolver() { - final UrlBasedViewResolver resolver = new UrlBasedViewResolver(); - resolver.setPrefix("/WEB-INF/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } + @Bean + public UrlBasedViewResolver setupViewResolver() { + final UrlBasedViewResolver resolver = new UrlBasedViewResolver(); + resolver.setPrefix("/WEB-INF/view/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator requestMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator requestMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator sessionMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator sessionMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator globalSessionMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator globalSessionMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope("prototype") - public Person personPrototype() { - return new Person(); - } + @Bean + @Scope("prototype") + public Person personPrototype() { + return new Person(); + } - @Bean - @Scope("singleton") - public Person personSingleton() { - return new Person(); - } + @Bean + @Scope("singleton") + public Person personSingleton() { + return new Person(); + } } diff --git a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java index 4abd3cc813..ce34adf6c1 100644 --- a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java +++ b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java @@ -11,7 +11,6 @@ public class Foo { private static final AtomicInteger instanceCount = new AtomicInteger(0); - private final int instanceNum; public Foo() { diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java index 44f1767405..84bc3a8033 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java @@ -18,17 +18,16 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class ) +@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) public class ControllerAnnotationTest { - - private MockMvc mockMvc; + + private MockMvc mockMvc; @Autowired private WebApplicationContext wac; - + private Student selectedStudent; @Before @@ -43,9 +42,7 @@ public class ControllerAnnotationTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")) - .andReturn() - .getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); @@ -57,9 +54,7 @@ public class ControllerAnnotationTest { @Test public void testRestController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); @@ -72,9 +67,7 @@ public class ControllerAnnotationTest { @Test public void testRestAnnotatedController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java index f5e41cd5a2..47915b8ce9 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java @@ -19,7 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration({"classpath:test-mvc.xml"}) +@ContextConfiguration({ "classpath:test-mvc.xml" }) public class ControllerTest { private MockMvc mockMvc; @@ -41,9 +41,7 @@ public class ControllerTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")) - .andReturn() - .getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); @@ -55,9 +53,7 @@ public class ControllerTest { @Test public void testRestController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); @@ -70,9 +66,7 @@ public class ControllerTest { @Test public void testRestAnnotatedController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java index b1dd248c26..59b9e225ad 100644 --- a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java +++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java @@ -8,36 +8,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class ScopesTest { - private static final String NAME = "John Smith"; - private static final String NAME_OTHER = "Anna Jones"; + private static final String NAME = "John Smith"; + private static final String NAME_OTHER = "Anna Jones"; - @Test - public void testScopeSingleton() { - final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); + @Test + public void testScopeSingleton() { + final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); - final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); - final Person personSingletonB = (Person) applicationContext.getBean("personSingleton"); + final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); + final Person personSingletonB = (Person) applicationContext.getBean("personSingleton"); - personSingletonA.setName(NAME); - Assert.assertEquals(NAME, personSingletonB.getName()); + personSingletonA.setName(NAME); + Assert.assertEquals(NAME, personSingletonB.getName()); - ((AbstractApplicationContext) applicationContext).close(); - } + ((AbstractApplicationContext) applicationContext).close(); + } - @Test - public void testScopePrototype() { - final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); + @Test + public void testScopePrototype() { + final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); - final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); - final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype"); + final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); + final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype"); - personPrototypeA.setName(NAME); - personPrototypeB.setName(NAME_OTHER); + personPrototypeA.setName(NAME); + personPrototypeB.setName(NAME_OTHER); - Assert.assertEquals(NAME, personPrototypeA.getName()); - Assert.assertEquals(NAME_OTHER, personPrototypeB.getName()); + Assert.assertEquals(NAME, personPrototypeA.getName()); + Assert.assertEquals(NAME_OTHER, personPrototypeB.getName()); - ((AbstractApplicationContext) applicationContext).close(); - } + ((AbstractApplicationContext) applicationContext).close(); + } } diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java index aa3acb113f..5162a067d7 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java @@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception { - String result = this.mockMvc.perform(get("/test") - .accept(MediaType.ALL)) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Assert.assertEquals("login = john, query = invoices", result); } diff --git a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java index 04fabbc834..75d828c3d3 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java @@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception { - this.mockMvc.perform(get("/appointments") - .accept(MediaType.ALL)) - .andExpect(status().isOk()); + this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk()); verify(appointmentService); } diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java index 82caae15fe..3edf693a13 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; -@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class}) +@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class }) public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests { @Autowired diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java index 946b19d00d..8a8cec3f86 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java @@ -1,6 +1,5 @@ package org.baeldung.spring43.defaultmethods; - import javax.sql.DataSource; import org.springframework.context.annotation.Bean; diff --git a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java index b696760f68..ecf14f0d6c 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java @@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception { MockHttpSession session = new MockHttpSession(); - String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request") - .session(session) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request") - .session(session) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2); } @@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { MockHttpSession session1 = new MockHttpSession(); MockHttpSession session2 = new MockHttpSession(); - String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session") - .session(session2) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2); @@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { MockHttpSession session1 = new MockHttpSession(); MockHttpSession session2 = new MockHttpSession(); - String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application") - .session(session2) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2); diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java index 725a9b8406..18ff11a49c 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java @@ -3,9 +3,9 @@ package com.baeldung.autowire.sample; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { - public static void main(String[] args) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); - FooService fooService = ctx.getBean(FooService.class); - fooService.doStuff(); - } + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); + FooService fooService = ctx.getBean(FooService.class); + fooService.doStuff(); + } } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java index fb704453fc..e67a376d25 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java @@ -9,5 +9,5 @@ public class BarFormatter implements Formatter { public String format() { return "bar"; } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java index 73966e9e43..57f93a53d7 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java @@ -9,5 +9,5 @@ public class FooFormatter implements Formatter { public String format() { return "foo"; } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java index eccea4351a..c55d93da11 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java @@ -5,13 +5,13 @@ import org.springframework.stereotype.Component; @Component public class FooService { - + @Autowired @FormatterType("Foo") private Formatter formatter; - - public String doStuff(){ + + public String doStuff() { return formatter.format(); } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java index 83716d6e92..59d718050a 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java @@ -2,6 +2,6 @@ package com.baeldung.autowire.sample; public interface Formatter { - String format(); + String format(); } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java index 7ffc308c9a..f2961745b5 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java @@ -8,10 +8,10 @@ import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Qualifier; @Qualifier -@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER}) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface FormatterType { - + String value(); } diff --git a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java index 4607f527d9..50e89fcc55 100644 --- a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java +++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java @@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) public class FooServiceTest { - + @Autowired FooService fooService; - + @Test - public void whenFooFormatterType_thenReturnFoo(){ + public void whenFooFormatterType_thenReturnFoo() { Assert.assertEquals("foo", fooService.doStuff()); } } diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 1b4cc0a753..5281b9b2c0 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,7 +24,11 @@ 4.3.1.RELEASE - + + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot spring-boot-starter-web @@ -80,6 +84,17 @@ 3.1.7 test + + + org.webjars + bootstrap + 3.3.7-1 + + + org.webjars + jquery + 3.1.1 + diff --git a/webjars/src/main/java/com/baeldung/TestController.java b/spring-boot/src/main/java/com/baeldung/TestController.java similarity index 67% rename from webjars/src/main/java/com/baeldung/TestController.java rename to spring-boot/src/main/java/com/baeldung/TestController.java index 19a1c18c6b..0e28ca67f8 100644 --- a/webjars/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/webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java similarity index 63% rename from webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java rename to spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java index c14dc682af..35490131c6 100644 --- a/webjars/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/webjars/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html similarity index 54% rename from webjars/src/main/resources/templates/index.html rename to spring-boot/src/main/resources/templates/index.html index 046d21600a..2c4387ed10 100644 --- a/webjars/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 + diff --git a/webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java similarity index 90% rename from webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java index 284cda5d31..c43b13ea0b 100644 --- a/webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java @@ -11,8 +11,8 @@ import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration public class WebjarsdemoApplicationTests { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index e16791881e..c0fc1befd3 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -32,13 +32,10 @@ public class CommitIdTest { LOG.info(commitMessage); LOG.info(branch); - assertThat(commitMessage) - .isNotEqualTo("UNKNOWN"); + assertThat(commitMessage).isNotEqualTo("UNKNOWN"); - assertThat(branch) - .isNotEqualTo("UNKNOWN"); + assertThat(branch).isNotEqualTo("UNKNOWN"); - assertThat(commitId) - .isNotEqualTo("UNKNOWN"); + assertThat(commitId).isNotEqualTo("UNKNOWN"); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java index ac7bcd62a9..1255180e44 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java @@ -31,22 +31,15 @@ public class SpringBootApplicationTest { private WebApplicationContext webApplicationContext; private MockMvc mockMvc; - @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), - MediaType.APPLICATION_JSON.getSubtype(), - Charset.forName("utf8")); + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")). - andExpect(MockMvcResultMatchers.status().isOk()). - andExpect(MockMvcResultMatchers.content().contentType(contentType)). - andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java index d36a7906a3..f4ce158661 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java @@ -69,7 +69,6 @@ public class SpringBootMailTest { return wiserMessage.getMimeMessage().getSubject(); } - private SimpleMailMessage composeEmailMessage() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(userTo); diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java index c594610be2..ba0da968ad 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java @@ -30,8 +30,7 @@ public class DetailsServiceClientTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")) - .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-cloud-data-flow/README.MD b/spring-cloud-data-flow/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud-data-flow/README.MD @@ -0,0 +1 @@ + diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml new file mode 100644 index 0000000000..2ddb9d85a3 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + batch-job + 0.0.1-SNAPSHOT + jar + + batch-job + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-task-starter + 1.0.1.RELEASE + + + + org.springframework.boot + spring-boot-starter-batch + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java new file mode 100644 index 0000000000..f717f0f644 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.task.configuration.EnableTask; + +@EnableTask +@EnableBatchProcessing +@SpringBootApplication +public class BatchJobApplication { + + public static void main(String[] args) { + SpringApplication.run(BatchJobApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java new file mode 100644 index 0000000000..dc6a5e2827 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java @@ -0,0 +1,38 @@ +package org.baeldung.spring.cloud; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class JobConfiguration { + + private static final Log logger = LogFactory.getLog(JobConfiguration.class); + + @Autowired + public JobBuilderFactory jobBuilderFactory; + + @Autowired + public StepBuilderFactory stepBuilderFactory; + + @Bean + public Job job() { + return jobBuilderFactory.get("job").start(stepBuilderFactory.get("jobStep1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + logger.info("Job was run"); + return RepeatStatus.FINISHED; + } + }).build()).build(); + } +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java new file mode 100644 index 0000000000..5f18ec75c4 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BatchJobApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml new file mode 100644 index 0000000000..94c4106d6f --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + data-flow-server + 0.0.1-SNAPSHOT + jar + + data-flow-server + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-dataflow-server-local + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dataflow-dependencies + 1.0.0.BUILD-SNAPSHOT + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + diff --git a/spring-cloud-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java b/spring-cloud-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java new file mode 100644 index 0000000000..227c10b620 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.spring.cloud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.dataflow.server.EnableDataFlowServer; + +@EnableDataFlowServer +@SpringBootApplication +public class DataFlowServerApplication { + + public static void main(String[] args) { + SpringApplication.run(DataFlowServerApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java new file mode 100644 index 0000000000..f853e29244 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowServerApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml new file mode 100644 index 0000000000..a074fef88f --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + data-flow-shell + 0.0.1-SNAPSHOT + jar + + data-flow-shell + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-dataflow-shell + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dataflow-dependencies + 1.0.0.BUILD-SNAPSHOT + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + diff --git a/spring-cloud-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java b/spring-cloud-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java new file mode 100644 index 0000000000..36c421f5bf --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.spring.cloud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.dataflow.shell.EnableDataFlowShell; + +@EnableDataFlowShell +@SpringBootApplication +public class DataFlowShellApplication { + + public static void main(String[] args) { + SpringApplication.run(DataFlowShellApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java new file mode 100644 index 0000000000..7e2bc1cb37 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowShellApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml new file mode 100644 index 0000000000..8415d95373 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + log-sink + 0.0.1-SNAPSHOT + jar + + log-sink + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java b/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java new file mode 100644 index 0000000000..a2b9968539 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java @@ -0,0 +1,26 @@ +package org.baeldung.spring.cloud; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Sink; + +@EnableBinding(Sink.class) +@SpringBootApplication +public class LogSinkApplication { + + private static Logger logger = LoggerFactory.getLogger(LogSinkApplication.class); + + @StreamListener(Sink.INPUT) + public void loggerSink(String date) { + + logger.info("Received: " + date); + } + + public static void main(String[] args) { + SpringApplication.run(LogSinkApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java new file mode 100644 index 0000000000..9f88c7f632 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class LogSinkApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml new file mode 100644 index 0000000000..509c185d61 --- /dev/null +++ b/spring-cloud-data-flow/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + org.baeldung.spring.cloud + spring-cloud-data-flow + 0.0.1-SNAPSHOT + pom + + data-flow-server + data-flow-shell + time-source + time-processor + log-sink + batch-job + + diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml new file mode 100644 index 0000000000..bc2efe7754 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + time-processor + 0.0.1-SNAPSHOT + jar + + time-processor + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java b/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java new file mode 100644 index 0000000000..7a2763d436 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java @@ -0,0 +1,27 @@ +package org.baeldung.spring.cloud; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.integration.annotation.Transformer; + +@EnableBinding(Processor.class) +@SpringBootApplication +public class TimeProcessorApplication { + + @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) + public Object transform(Long timestamp) { + + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); + String date = dateFormat.format(timestamp); + return date; + } + + public static void main(String[] args) { + SpringApplication.run(TimeProcessorApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java new file mode 100644 index 0000000000..875346f9db --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeProcessorApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml new file mode 100644 index 0000000000..587b782227 --- /dev/null +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + time-source + 0.0.1-SNAPSHOT + jar + + time-source + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java b/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java new file mode 100644 index 0000000000..5bce39ebe0 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java @@ -0,0 +1,29 @@ +package org.baeldung.spring.cloud; + +import java.util.Date; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Source; +import org.springframework.context.annotation.Bean; +import org.springframework.integration.annotation.InboundChannelAdapter; +import org.springframework.integration.annotation.Poller; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.support.MessageBuilder; + +@EnableBinding(Source.class) +@SpringBootApplication +public class TimeSourceApplication { + + @Bean + @InboundChannelAdapter(value = Source.OUTPUT, poller = @Poller(fixedDelay = "10000", maxMessagesPerPoll = "1")) + public MessageSource timeMessageSource() { + + return () -> MessageBuilder.withPayload(new Date().getTime()).build(); + } + + public static void main(String[] args) { + SpringApplication.run(TimeSourceApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java new file mode 100644 index 0000000000..61fd8323d2 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeSourceApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java b/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java deleted file mode 100644 index 9496d4760d..0000000000 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.spring.cloud.hystrix.rest.producer; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -@RestController -public class RestProducerApplication implements GreetingController { - public static void main(String[] args) { - SpringApplication.run(RestProducerApplication.class, args); - } - - @Override - public String greeting(@PathVariable("username") String username) { - return String.format("Hello %s!\n", username); - } -} diff --git a/spring-cloud/README.md b/spring-cloud/README.md new file mode 100644 index 0000000000..3e8cd21b82 --- /dev/null +++ b/spring-cloud/README.md @@ -0,0 +1,18 @@ +## The Module Holds Sources for the Following Articles + +- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) + + Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. + + In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. + +- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) + + In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. + + Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. + +- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) + + diff --git a/spring-cloud-hystrix/pom.xml b/spring-cloud/pom.xml similarity index 82% rename from spring-cloud-hystrix/pom.xml rename to spring-cloud/pom.xml index 2768a4f05b..2349613def 100644 --- a/spring-cloud-hystrix/pom.xml +++ b/spring-cloud/pom.xml @@ -4,17 +4,17 @@ 4.0.0 com.baeldung.spring.cloud - spring-cloud-hystrix + spring-cloud 1.0.0-SNAPSHOT - spring-cloud-hystrix-rest-producer - spring-cloud-hystrix-rest-consumer - spring-cloud-hystrix-feign-rest-consumer + spring-cloud-config + spring-cloud-eureka + spring-cloud-hystrix + spring-cloud-bootstrap pom - Spring Cloud Hystrix - Spring Cloud Hystrix Demo + spring-cloud com.baeldung diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -0,0 +1 @@ + diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties b/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties new file mode 100644 index 0000000000..7f3df86c7e --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties @@ -0,0 +1,8 @@ +spring.application.name=discovery +server.port=8082 + +eureka.instance.hostname=localhost + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ +eureka.client.register-with-eureka=false +eureka.client.fetch-registry=false diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties new file mode 100644 index 0000000000..77faec8421 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties @@ -0,0 +1,10 @@ +spring.application.name=gateway +server.port=8080 + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ + +zuul.routes.resource.path=/resource/** +hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds: 5000 + diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties b/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties new file mode 100644 index 0000000000..4e6cf3817c --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties @@ -0,0 +1,8 @@ +spring.application.name=resource +server.port=8083 + +resource.returnString=hello cloud + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml new file mode 100644 index 0000000000..0cb217acfb --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + config + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-config-server + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java new file mode 100644 index 0000000000..ff6c093b8b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.integration.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableConfigServer +@EnableEurekaClient +public class ConfigApplication { + public static void main(String[] args) { + SpringApplication.run(ConfigApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties new file mode 100644 index 0000000000..6f614d0690 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8081 +spring.application.name=config + +spring.cloud.config.server.git.uri=file:///${user.home}/application-config + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml new file mode 100644 index 0000000000..ee7c589549 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + discovery + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka-server + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java new file mode 100644 index 0000000000..a21c65312f --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.integration.discovery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class DiscoveryApplication { + public static void main(String[] args) { + SpringApplication.run(DiscoveryApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..ca9d59c9ed --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties @@ -0,0 +1,2 @@ +spring.cloud.config.name=discovery +spring.cloud.config.uri=http://localhost:8081 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml new file mode 100644 index 0000000000..8e56d0fd35 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + gateway + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java new file mode 100644 index 0000000000..66e7c36f2a --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.integration.resource; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +@EnableEurekaClient +public class GatewayApplication { + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..9610d72675 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties @@ -0,0 +1,5 @@ +spring.cloud.config.name=gateway +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml new file mode 100644 index 0000000000..c14c277d7f --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + + + + config + discovery + gateway + resource + + + + spring-cloud-integration + 1.0.0-SNAPSHOT + pom + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/resource/pom.xml b/spring-cloud/spring-cloud-bootstrap/resource/pom.xml new file mode 100644 index 0000000000..78112fa3e0 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/resource/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + resource + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java new file mode 100644 index 0000000000..107a9d199f --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.cloud.integration.resource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@EnableEurekaClient +@RestController +public class ResourceApplication { + public static void main(String[] args) { + SpringApplication.run(ResourceApplication.class, args); + } + + @Value("${resource.returnString}") + private String returnString; + + @RequestMapping("/hello/cloud") + public String getString() { + return returnString; + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..3c88a0b520 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties @@ -0,0 +1,5 @@ +spring.cloud.config.name=resource +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud-config/client-config/config-client-development.properties b/spring-cloud/spring-cloud-config/client-config/config-client-development.properties similarity index 100% rename from spring-cloud-config/client-config/config-client-development.properties rename to spring-cloud/spring-cloud-config/client-config/config-client-development.properties diff --git a/spring-cloud-config/client-config/config-client-production.properties b/spring-cloud/spring-cloud-config/client-config/config-client-production.properties similarity index 100% rename from spring-cloud-config/client-config/config-client-production.properties rename to spring-cloud/spring-cloud-config/client-config/config-client-production.properties diff --git a/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml similarity index 100% rename from spring-cloud-config/client/pom.xml rename to spring-cloud/spring-cloud-config/client/pom.xml diff --git a/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java b/spring-cloud/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java similarity index 100% rename from spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java rename to spring-cloud/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java diff --git a/spring-cloud-config/client/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud-config/client/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties diff --git a/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java similarity index 100% rename from spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java rename to spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java diff --git a/spring-cloud-config/docker/Dockerfile b/spring-cloud/spring-cloud-config/docker/Dockerfile similarity index 100% rename from spring-cloud-config/docker/Dockerfile rename to spring-cloud/spring-cloud-config/docker/Dockerfile diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud/spring-cloud-config/docker/Dockerfile.client similarity index 100% rename from spring-cloud-config/docker/Dockerfile.client rename to spring-cloud/spring-cloud-config/docker/Dockerfile.client diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud/spring-cloud-config/docker/Dockerfile.server similarity index 100% rename from spring-cloud-config/docker/Dockerfile.server rename to spring-cloud/spring-cloud-config/docker/Dockerfile.server diff --git a/spring-cloud-config/docker/config-client-entrypoint.sh b/spring-cloud/spring-cloud-config/docker/config-client-entrypoint.sh similarity index 100% rename from spring-cloud-config/docker/config-client-entrypoint.sh rename to spring-cloud/spring-cloud-config/docker/config-client-entrypoint.sh diff --git a/spring-cloud-config/docker/docker-compose.scale.yml b/spring-cloud/spring-cloud-config/docker/docker-compose.scale.yml similarity index 100% rename from spring-cloud-config/docker/docker-compose.scale.yml rename to spring-cloud/spring-cloud-config/docker/docker-compose.scale.yml diff --git a/spring-cloud-config/docker/docker-compose.yml b/spring-cloud/spring-cloud-config/docker/docker-compose.yml similarity index 100% rename from spring-cloud-config/docker/docker-compose.yml rename to spring-cloud/spring-cloud-config/docker/docker-compose.yml diff --git a/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml similarity index 100% rename from spring-cloud-config/pom.xml rename to spring-cloud/spring-cloud-config/pom.xml diff --git a/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml similarity index 100% rename from spring-cloud-config/server/pom.xml rename to spring-cloud/spring-cloud-config/server/pom.xml diff --git a/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java b/spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java similarity index 100% rename from spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java rename to spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java diff --git a/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties similarity index 100% rename from spring-cloud-config/server/src/main/resources/application.properties rename to spring-cloud/spring-cloud-config/server/src/main/resources/application.properties diff --git a/spring-cloud-config/server/src/main/resources/config-server.jks b/spring-cloud/spring-cloud-config/server/src/main/resources/config-server.jks similarity index 100% rename from spring-cloud-config/server/src/main/resources/config-server.jks rename to spring-cloud/spring-cloud-config/server/src/main/resources/config-server.jks diff --git a/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java similarity index 100% rename from spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java rename to spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java diff --git a/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml similarity index 94% rename from spring-cloud-eureka/pom.xml rename to spring-cloud/spring-cloud-eureka/pom.xml index 86e0354070..f02bf7ad9c 100644 --- a/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -17,8 +17,8 @@ Spring Cloud Eureka Server and Sample Clients - com.baeldung - parent-modules + com.baeldung.spring.cloud + spring-cloud 1.0.0-SNAPSHOT .. diff --git a/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-client/pom.xml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml diff --git a/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java diff --git a/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java diff --git a/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml diff --git a/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml diff --git a/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java diff --git a/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java diff --git a/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml diff --git a/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html diff --git a/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-server/pom.xml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml diff --git a/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java diff --git a/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml similarity index 100% rename from spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml diff --git a/spring-cloud/spring-cloud-hystrix/README.MD b/spring-cloud/spring-cloud-hystrix/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/README.MD @@ -0,0 +1 @@ + diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml similarity index 91% rename from spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/pom.xml rename to spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index d2716e897e..8209dc8c67 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -3,12 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-cloud-hystrix-feign-rest-consumer + feign-rest-consumer 1.0.0-SNAPSHOT jar - Spring Cloud Hystrix Feign REST Consumer - Spring Cloud Hystrix Feign Sample Implementation + feign-rest-consumer com.baeldung.spring.cloud @@ -20,7 +19,7 @@ com.baeldung.spring.cloud - spring-cloud-hystrix-rest-producer + rest-producer 1.0.0-SNAPSHOT diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java rename to spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java new file mode 100644 index 0000000000..62dbbdd608 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class GreetingController { + @Autowired + private GreetingClient greetingClient; + + @RequestMapping("/get-greeting/{username}") + public String getGreeting(Model model, @PathVariable("username") String username) { + model.addAttribute("greeting", greetingClient.greeting(username)); + return "greeting-view"; + } +} diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java similarity index 52% rename from spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java rename to spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java index b97d84eaf2..2fc54216fe 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java @@ -1,32 +1,17 @@ package com.baeldung.spring.cloud.hystrix.rest.consumer; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; @SpringBootApplication @EnableCircuitBreaker @EnableHystrixDashboard @EnableFeignClients -@Controller public class RestConsumerFeignApplication { - @Autowired - private GreetingClient greetingClient; - public static void main(String[] args) { SpringApplication.run(RestConsumerFeignApplication.class, args); } - - @RequestMapping("/get-greeting/{username}") - public String getGreeting(Model model, @PathVariable("username") String username) { - model.addAttribute("greeting", greetingClient.greeting(username)); - return "greeting-view"; - } } diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/application.properties similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/resources/application.properties rename to spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/application.properties diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/templates/greeting-view.html similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-feign-rest-consumer/src/main/resources/templates/greeting-view.html rename to spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/templates/greeting-view.html diff --git a/spring-cloud/spring-cloud-hystrix/pom.xml b/spring-cloud/spring-cloud-hystrix/pom.xml new file mode 100644 index 0000000000..b992ce3846 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-hystrix + 1.0.0-SNAPSHOT + + rest-producer + rest-consumer + feign-rest-consumer + + pom + + spring-cloud-hystrix + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml similarity index 92% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/pom.xml rename to spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml index c9be67c302..649ca88eb3 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml @@ -3,12 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-cloud-hystrix-rest-consumer + rest-consumer 1.0.0-SNAPSHOT jar - Spring Cloud Hystrix REST Consumer - Spring Cloud Hystrix Sample Implementation + rest-consumer com.baeldung.spring.cloud diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java similarity index 53% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java rename to spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java index 9df745b1c6..112ad167f6 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java @@ -1,28 +1,16 @@ package com.baeldung.spring.cloud.hystrix.rest.consumer; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; -import org.springframework.cloud.netflix.hystrix.EnableHystrix; -import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -@SpringBootApplication -@EnableCircuitBreaker -@EnableHystrixDashboard @Controller -public class RestConsumerApplication { +public class GreetingController { @Autowired private GreetingService greetingService; - public static void main(String[] args) { - SpringApplication.run(RestConsumerApplication.class, args); - } - @RequestMapping("/get-greeting/{username}") public String getGreeting(Model model, @PathVariable("username") String username) { model.addAttribute("greeting", greetingService.getGreeting(username)); diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java similarity index 90% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java rename to spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java index d3d5e6e047..2502e292df 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java @@ -1,7 +1,6 @@ package com.baeldung.spring.cloud.hystrix.rest.consumer; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java new file mode 100644 index 0000000000..113949c754 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; +import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; + +@SpringBootApplication +@EnableCircuitBreaker +@EnableHystrixDashboard +public class RestConsumerApplication { + public static void main(String[] args) { + SpringApplication.run(RestConsumerApplication.class, args); + } +} diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/application.properties similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/resources/application.properties rename to spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/application.properties diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/templates/greeting-view.html similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-consumer/src/main/resources/templates/greeting-view.html rename to spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/templates/greeting-view.html diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml similarity index 85% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/pom.xml rename to spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml index 44e373c8ac..726d18d2c3 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml @@ -3,12 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-cloud-hystrix-rest-producer + rest-producer 1.0.0-SNAPSHOT jar - Spring Cloud Hystrix REST Producer - Spring Cloud Hystrix Sample REST Producer Implementation + rest-producer com.baeldung.spring.cloud diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java similarity index 84% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java rename to spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java index 81541b4f8f..e82220d27a 100644 --- a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java @@ -2,7 +2,6 @@ package com.baeldung.spring.cloud.hystrix.rest.producer; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; public interface GreetingController { @RequestMapping("/greeting/{username}") diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java new file mode 100644 index 0000000000..3541035ba5 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GreetingControllerImpl implements GreetingController { + @Override + public String greeting(@PathVariable("username") String username) { + return String.format("Hello %s!\n", username); + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java new file mode 100644 index 0000000000..206a6a2d03 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestProducerApplication { + public static void main(String[] args) { + SpringApplication.run(RestProducerApplication.class, args); + } +} diff --git a/spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/application.properties similarity index 100% rename from spring-cloud-hystrix/spring-cloud-hystrix-rest-producer/src/main/resources/application.properties rename to spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/application.properties diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index 60548dd6e3..820e7e8004 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -18,9 +18,9 @@ public class SpringDemoApplication extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringDemoApplication.class); } - + @Bean - public RestTemplate getRestTemplate(){ - return new RestTemplate(); + public RestTemplate getRestTemplate() { + return new RestTemplate(); } } diff --git a/spring-data-couchbase-2/README.md b/spring-data-couchbase-2/README.md index 3ed226fb33..2e56b25fef 100644 --- a/spring-data-couchbase-2/README.md +++ b/spring-data-couchbase-2/README.md @@ -3,6 +3,7 @@ ### Relevant Articles: - [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) - [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) +- [Multiple Buckets and Spatial View Queries in Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase-buckets-and-spatial-view-queries) ### Overview This Maven project contains the Java code for Spring Data Couchbase @@ -11,7 +12,7 @@ as described in the tutorials, as well as a unit/integration test for each service implementation. ### Working with the Code -The project was developed and tested using Java 7 nad 8 in the Eclipse-based +The project was developed and tested using Java 7 and 8 in the Eclipse-based Spring Source Toolkit (STS) and therefore should run fine in any recent version of Eclipse or another IDE of your choice that supports Java 7 or later. @@ -22,8 +23,15 @@ You can also build the project using Maven outside of any IDE: mvn clean install ``` +### Package Organization +Java classes for the first two tutorials listed above are in src/main/java in the package hierarchy +org.baeldung.spring.data.couchbase + +Java classes for the multiple-bucket tutorials are in src/main/java in the package hierarchy +org.baeldung.spring.data.couchbase2b + ### Running the tests -The following test classes are in src/test/java in the package +The test classes for the single-bucket tutorials are in src/test/java in the package org.baeldung.spring.data.couchbase.service: - PersonServiceTest (abstract) - PersonRepositoryTest (concrete) @@ -32,6 +40,12 @@ org.baeldung.spring.data.couchbase.service: - StudentRepositoryTest (concrete) - StudentTemplateServiceTest (concrete) +The concrete test classes for the multiple-bucket tutorial are in src/test/java in the package +org.baeldung.spring.data.couchbase2b.service: +- CampusRepositoryServiceImplTest +- PersonRepositoryServiceImplTest +- StudentRepositoryServiceImplTest + The concrete test classes may be run as JUnit tests from your IDE or using the Maven command line: ``` diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java similarity index 88% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java index 201b14cf0b..c357ab8596 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java @@ -19,22 +19,27 @@ public class Campus { @Field @NotNull private Point location; - + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Point getLocation() { return location; } + public void setLocation(Point location) { this.location = location; } @@ -42,13 +47,13 @@ public class Campus { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(name != null) { + if (name != null) { hash = hash * 31 + name.hashCode(); } - if(location != null) { + if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; @@ -56,30 +61,33 @@ public class Campus { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } - + @SuppressWarnings("unused") - private Campus() {} - + private Campus() { + } + public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } - + public static class Builder { private String id; private String name; private Point location; - + public static Builder newInstance() { return new Builder(); } - + public Campus build() { return new Campus(this); } @@ -93,7 +101,7 @@ public class Campus { this.name = name; return this; } - + public Builder location(Point location) { this.location = location; return this; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java index 9220e157ed..fd41427d20 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java @@ -24,7 +24,7 @@ public class Person { private DateTime created; @Field private DateTime updated; - + public Person(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; @@ -34,44 +34,53 @@ public class Person { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } - + @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } return hash; @@ -79,8 +88,10 @@ public class Person { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Person other = (Person) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java index 9c266c2c62..726ed2347e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java @@ -20,13 +20,13 @@ public class Student { private String id; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String firstName; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String lastName; @Field @Past @@ -38,8 +38,9 @@ public class Student { private DateTime updated; @Version private long version; - - public Student() {} + + public Student() { + } public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { this.id = id; @@ -51,36 +52,47 @@ public class Student { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getDateOfBirth() { return dateOfBirth; } + public void setDateOfBirth(DateTime dateOfBirth) { this.dateOfBirth = dateOfBirth; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } @@ -88,16 +100,16 @@ public class Student { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } - if(dateOfBirth != null) { + if (dateOfBirth != null) { hash = hash * 31 + dateOfBirth.hashCode(); } return hash; @@ -105,8 +117,10 @@ public class Student { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Student other = (Student) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index 66b672a4fd..751895502c 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository { private CouchbaseTemplate template; public List findByFirstNameStartsWith(String s) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName") - .startKey(s) - .stale(Stale.FALSE), - Student.class); + return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java index 14b77759e3..717feb858f 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java index 331ddc553d..9bbdeec642 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository, CustomStudentRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 90cc36780a..49548bdbfb 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("PersonRepositoryService") public class PersonRepositoryService implements PersonService { - + private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 45e9b90a19..8398847f65 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("PersonTemplateService") public class PersonTemplateService implements PersonService { - + private static final String DESIGN_DOC = "person"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Person findOne(String id) { - return template.findById(id, Person.class); + public Person findOne(String id) { + return template.findById(id, Person.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index 58304afc1c..65f5a6e78e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("StudentRepositoryService") public class StudentRepositoryService implements StudentService { - + private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java index c3808e0015..8d1292b5e4 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("StudentTemplateService") public class StudentTemplateService implements StudentService { - + private static final String DESIGN_DOC = "student"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Student findOne(String id) { - return template.findById(id, Student.class); + public Student findOne(String id) { + return template.findById(id, Student.class); } public List findAll() { diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java similarity index 72% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index 22b2fb2735..b1857222c5 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.Set; @@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository; public interface CampusRepository extends CrudRepository { - @View(designDocument="campus", viewName="byName") + @View(designDocument = "campus", viewName = "byName") Set findByName(String name); - @Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation") + @Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation") Set findByLocationNear(Point point, Distance distance); } diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java similarity index 85% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java index 14b77759e3..ef37106c6d 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.List; @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java similarity index 85% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java index 433964c872..0d790d2f39 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.List; @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java similarity index 85% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java index e82c14cb87..58f00dda25 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.Set; @@ -7,14 +7,14 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; public interface CampusService { - + Campus find(String id); Set findByName(String name); Set findByLocationNear(Point point, Distance distance); - + Set findAll(); - + void save(Campus campus); } diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java similarity index 77% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index d12e59ba1f..586f5f0dc1 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -1,37 +1,36 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase.repos.CampusRepository; +import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; import org.springframework.stereotype.Service; @Service -@Qualifier("CampusRepositoryService") -public class CampusRepositoryService implements CampusService { +public class CampusServiceImpl implements CampusService { private CampusRepository repo; + @Autowired public void setCampusRepository(CampusRepository repo) { this.repo = repo; } - + @Override public Campus find(String id) { return repo.findOne(id); } - + @Override public Set findByName(String name) { return repo.findByName(name); } - + @Override public Set findByLocationNear(Point point, Distance distance) { return repo.findByLocationNear(point, distance); @@ -41,7 +40,7 @@ public class CampusRepositoryService implements CampusService { public Set findAll() { Set campuses = new HashSet<>(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { campuses.add(it.next()); } return campuses; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java similarity index 87% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java index a823908b01..c2c96ffb9c 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java similarity index 79% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index 90cc36780a..fe0a9e48cd 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -1,21 +1,20 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.baeldung.spring.data.couchbase.model.Person; -import org.baeldung.spring.data.couchbase.repos.PersonRepository; +import org.baeldung.spring.data.couchbase2b.repos.PersonRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -@Qualifier("PersonRepositoryService") -public class PersonRepositoryService implements PersonService { - +public class PersonServiceImpl implements PersonService { + private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -28,7 +27,7 @@ public class PersonRepositoryService implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java similarity index 87% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java index f483ef0fb6..5b83b403bb 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java similarity index 80% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 58304afc1c..248d824081 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -1,21 +1,20 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.baeldung.spring.data.couchbase.model.Student; -import org.baeldung.spring.data.couchbase.repos.StudentRepository; +import org.baeldung.spring.data.couchbase2b.repos.StudentRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -@Qualifier("StudentRepositoryService") -public class StudentRepositoryService implements StudentService { - +public class StudentServiceImpl implements StudentService { + private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -28,7 +27,7 @@ public class StudentRepositoryService implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java similarity index 50% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java index c298ef0a61..0e2e8d5dd3 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java @@ -1,17 +1,11 @@ package org.baeldung.spring.data.couchbase; import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; -import org.springframework.data.couchbase.core.query.Consistency; -public class TestCouchbaseConfig extends MyCouchbaseConfig { +public class CustomTypeKeyCouchbaseConfig extends MyCouchbaseConfig { @Override public String typeKey() { return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE; } - - @Override - public Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; - } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java similarity index 94% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index 8e6b971dbf..a37e918101 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -12,9 +12,9 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String BUCKET_NAME = "baeldung"; public static final String BUCKET_PASSWORD = ""; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java new file mode 100644 index 0000000000..b4a372487e --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java @@ -0,0 +1,11 @@ +package org.baeldung.spring.data.couchbase; + +import org.springframework.data.couchbase.core.query.Consistency; + +public class ReadYourOwnWritesCouchbaseConfig extends MyCouchbaseConfig { + + @Override + public Consistency getDefaultConsistency() { + return Consistency.READ_YOUR_OWN_WRITES; + } +} diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java index 3fabf7a11e..c3bf9f2138 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java @@ -83,13 +83,6 @@ public abstract class PersonServiceTest extends IntegrationTest { assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - @Test - public void whenFindingByFirstNameJohn_thenReturnsOnePersonNamedJohn() { - final String expectedFirstName = john; - final List resultList = personService.findByFirstName(expectedFirstName); - assertTrue(resultList.size() == 1); - } - private boolean resultContains(List resultList, Person person) { boolean found = false; for (final Person p : resultList) { diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java index 79948cbedf..0bf2c5d673 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java @@ -30,27 +30,17 @@ public abstract class StudentServiceTest extends IntegrationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + StudentService studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); @@ -60,7 +50,7 @@ public abstract class StudentServiceTest extends IntegrationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -130,11 +120,11 @@ public abstract class StudentServiceTest extends IntegrationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java similarity index 83% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index 8eeda08455..fe32305feb 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package org.baeldung.spring.data.couchbase2b; import java.util.Arrays; import java.util.List; @@ -17,9 +17,9 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import com.couchbase.client.java.Bucket; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) -public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase2b" }) +public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String DEFAULT_BUCKET_NAME = "baeldung"; public static final String DEFAULT_BUCKET_PASSWORD = ""; @@ -38,27 +38,25 @@ public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { protected String getBucketPassword() { return DEFAULT_BUCKET_PASSWORD; } - + @Bean public Bucket campusBucket() throws Exception { return couchbaseCluster().openBucket("baeldung2", ""); } - - @Bean + + @Bean(name = "campusTemplate") public CouchbaseTemplate campusTemplate() throws Exception { - CouchbaseTemplate template = new CouchbaseTemplate( - couchbaseClusterInfo(), campusBucket(), - mappingCouchbaseConverter(), translationService()); + CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService()); template.setDefaultConsistency(getDefaultConsistency()); return template; } - + @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { baseMapping.mapEntity(Campus.class, campusTemplate()); } catch (Exception e) { - //custom Exception handling + // custom Exception handling } } diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java similarity index 68% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java index ce2daa92cd..cb671dc469 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package org.baeldung.spring.data.couchbase2b; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -7,7 +7,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MyCouchbaseConfig.class, IntegrationTestConfig.class }) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class IntegrationTest { +public abstract class MultiBucketIntegationTest { + } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java new file mode 100644 index 0000000000..94a95b06bb --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java @@ -0,0 +1,10 @@ +package org.baeldung.spring.data.couchbase2b; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = { "org.baeldung.spring.data.couchbase2b" }) +public class MultiBucketIntegrationTestConfig { + +} diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java similarity index 60% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java index 5a718f0807..d3982e1ecc 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java @@ -1,78 +1,47 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Set; import javax.annotation.PostConstruct; -import org.baeldung.spring.data.couchbase.IntegrationTest; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase.repos.CampusRepository; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusRepositoryServiceTest extends IntegrationTest { - +public class CampusServiceImplTest extends MultiBucketIntegationTest { + @Autowired - @Qualifier("CampusRepositoryService") - private CampusRepositoryService campusService; - + private CampusServiceImpl campusService; + @Autowired private CampusRepository campusRepo; - - private final Campus Brown = Campus.Builder.newInstance() - .id("campus:Brown") - .name("Brown") - .location(new Point(71.4025, 51.8268)) - .build(); - private final Campus Cornell = Campus.Builder.newInstance() - .id("campus:Cornell") - .name("Cornell") - .location(new Point(76.4833, 42.4459)) - .build(); - - private final Campus Columbia = Campus.Builder.newInstance() - .id("campus:Columbia") - .name("Columbia") - .location(new Point(73.9626, 40.8075)) - .build(); - - private final Campus Dartmouth = Campus.Builder.newInstance() - .id("campus:Dartmouth") - .name("Dartmouth") - .location(new Point(72.2887, 43.7044)) - .build(); + private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build(); - private final Campus Harvard = Campus.Builder.newInstance() - .id("campus:Harvard") - .name("Harvard") - .location(new Point(71.1167, 42.3770)) - .build(); + private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build(); - private final Campus Penn = Campus.Builder.newInstance() - .id("campus:Penn") - .name("Penn") - .location(new Point(75.1932, 39.9522)) - .build(); + private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build(); + + private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build(); + + private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build(); + + private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build(); + + private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build(); + + private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build(); - private final Campus Princeton = Campus.Builder.newInstance() - .id("campus:Princeton") - .name("Princeton") - .location(new Point(74.6514, 40.3340)) - .build(); - - private final Campus Yale = Campus.Builder.newInstance() - .id("campus:Yale") - .name("Yale") - .location(new Point(72.9223, 41.3163)) - .build(); - private final Point Boston = new Point(71.0589, 42.3601); private final Point NewYorkCity = new Point(74.0059, 40.7128); @@ -87,7 +56,7 @@ public class CampusRepositoryServiceTest extends IntegrationTest { campusRepo.save(Princeton); campusRepo.save(Yale); } - + @Test public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Exception { Set campuses = campusService.findByName(Harvard.getName()); @@ -96,14 +65,14 @@ public class CampusRepositoryServiceTest extends IntegrationTest { assertTrue(campuses.size() == 1); assertTrue(campuses.contains(Harvard)); } - + @Test public final void givenHarvardId_whenFind_thenReturnsHarvard() throws Exception { Campus actual = campusService.find(Harvard.getId()); assertNotNull(actual); assertEquals(Harvard, actual); } - + @Test public final void whenFindAll_thenReturnsAll() throws Exception { Set campuses = campusService.findAll(); @@ -124,7 +93,7 @@ public class CampusRepositoryServiceTest extends IntegrationTest { assertTrue(campuses.contains(Harvard)); assertFalse(campuses.contains(Columbia)); } - + @Test public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception { Set campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL)); diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java similarity index 54% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java index 84b6f75d56..e1a880d9da 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,14 +7,13 @@ import static org.junit.Assert.assertTrue; import java.util.List; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; import org.baeldung.spring.data.couchbase.model.Person; +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; @@ -22,37 +21,28 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonRepositoryServiceTest extends IntegrationTest { +public class PersonServiceImplTest extends MultiBucketIntegationTest { - private static final String typeField = "_class"; - private static final String john = "John"; - private static final String smith = "Smith"; - private static final String johnSmithId = "person:" + john + ":" + smith; - private static final Person johnSmith = new Person(johnSmithId, john, smith); - private static final JsonObject jsonJohnSmith = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", john) - .put("lastName", smith) - .put("created", DateTime.now().getMillis()); + static final String typeField = "_class"; + static final String john = "John"; + static final String smith = "Smith"; + static final String johnSmithId = "person:" + john + ":" + smith; + static final Person johnSmith = new Person(johnSmithId, john, smith); + static final JsonObject jsonJohnSmith = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); + + static final String foo = "Foo"; + static final String bar = "Bar"; + static final String foobarId = "person:" + foo + ":" + bar; + static final Person foobar = new Person(foobarId, foo, bar); + static final JsonObject jsonFooBar = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); - private static final String foo = "Foo"; - private static final String bar = "Bar"; - private static final String foobarId = "person:" + foo + ":" + bar; - private static final Person foobar = new Person(foobarId, foo, bar); - private static final JsonObject jsonFooBar = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", foo) - .put("lastName", bar) - .put("created", DateTime.now().getMillis()); - @Autowired - @Qualifier("PersonRepositoryService") - private PersonService personService; - + private PersonServiceImpl personService; + @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.DEFAULT_BUCKET_NAME, MyCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); + final Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); + final Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith)); bucket.upsert(JsonDocument.create(foobarId, jsonFooBar)); bucket.close(); @@ -61,7 +51,7 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingPersonByJohnSmithId_thenReturnsJohnSmith() { - Person actualPerson = personService.findOne(johnSmithId); + final Person actualPerson = personService.findOne(johnSmithId); assertNotNull(actualPerson); assertNotNull(actualPerson.getCreated()); assertEquals(johnSmith, actualPerson); @@ -69,7 +59,7 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingAllPersons_thenReturnsTwoOrMorePersonsIncludingJohnSmithAndFooBar() { - List resultList = personService.findAll(); + final List resultList = personService.findAll(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(resultContains(resultList, johnSmith)); @@ -79,8 +69,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingByFirstNameJohn_thenReturnsOnlyPersonsNamedJohn() { - String expectedFirstName = john; - List resultList = personService.findByFirstName(expectedFirstName); + final String expectedFirstName = john; + final List resultList = personService.findByFirstName(expectedFirstName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedFirstName(resultList, expectedFirstName)); @@ -88,17 +78,17 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingByLastNameSmith_thenReturnsOnlyPersonsNamedSmith() { - String expectedLastName = smith; - List resultList = personService.findByLastName(expectedLastName); + final String expectedLastName = smith; + final List resultList = personService.findByLastName(expectedLastName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Person person) { boolean found = false; - for(Person p : resultList) { - if(p.equals(person)) { + for (final Person p : resultList) { + if (p.equals(person)) { found = true; break; } @@ -108,8 +98,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Person p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (final Person p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -119,8 +109,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Person p : resultList) { - if(p.getLastName().equals(lastName)) { + for (final Person p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java similarity index 66% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java index 166f01d754..c503726377 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -9,14 +9,13 @@ import java.util.List; import javax.validation.ConstraintViolationException; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; import org.baeldung.spring.data.couchbase.model.Student; +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; @@ -24,41 +23,30 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentRepositoryServiceTest extends IntegrationTest { +public class StudentServiceImplTest extends MultiBucketIntegationTest { - private static final String typeField = "_class"; - private static final String joe = "Joe"; - private static final String college = "College"; - private static final String joeCollegeId = "student:" + joe + ":" + college; - private static final DateTime joeCollegeDob = DateTime.now().minusYears(21); - private static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - private static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final String typeField = "_class"; + static final String joe = "Joe"; + static final String college = "College"; + static final String joeCollegeId = "student:" + joe + ":" + college; + static final DateTime joeCollegeDob = DateTime.now().minusYears(21); + static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); - private static final String judy = "Judy"; - private static final String jetson = "Jetson"; - private static final String judyJetsonId = "student:" + judy + ":" + jetson; - private static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); - private static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - private static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final String judy = "Judy"; + static final String jetson = "Jetson"; + static final String judyJetsonId = "student:" + judy + ":" + jetson; + static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); + static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); @Autowired - @Qualifier("StudentRepositoryService") - private StudentService studentService; + StudentServiceImpl studentService; @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.DEFAULT_BUCKET_NAME, MyCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); + Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); + Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege)); bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson)); bucket.close(); @@ -79,7 +67,7 @@ public class StudentRepositoryServiceTest extends IntegrationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -89,7 +77,7 @@ public class StudentRepositoryServiceTest extends IntegrationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -137,8 +125,8 @@ public class StudentRepositoryServiceTest extends IntegrationTest { private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -148,8 +136,8 @@ public class StudentRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -159,8 +147,8 @@ public class StudentRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2b/README.md b/spring-data-couchbase-2b/README.md deleted file mode 100644 index 262962f58a..0000000000 --- a/spring-data-couchbase-2b/README.md +++ /dev/null @@ -1,36 +0,0 @@ -## Spring Data Couchbase Tutorial Project - -### Relevant Articles: -- [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) -- [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) - -### Overview -This Maven project contains the Java code for Spring Data Couchbase -entities, repositories, and repository-based services -as described in the tutorials, as well as a unit/integration test -for each service implementation. - -### Working with the Code -The project was developed and tested using Java 7 and 8 in the Eclipse-based -Spring Source Toolkit (STS) and therefore should run fine in any -recent version of Eclipse or another IDE of your choice -that supports Java 7 or later. - -### Building the Project -You can also build the project using Maven outside of any IDE: -``` -mvn clean install -``` - -### Running the tests -The following test classes are in src/test/java in the package -org.baeldung.spring.data.couchbase.service: -- CampusRepositoryServiceTest -- PersonRepositoryServiceTest -- StudentRepositoryServiceTest - -These may be run as JUnit tests from your IDE -or using the Maven command line: -``` -mvn test -``` diff --git a/spring-data-couchbase-2b/pom.xml b/spring-data-couchbase-2b/pom.xml deleted file mode 100644 index 7d58f78ce5..0000000000 --- a/spring-data-couchbase-2b/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - 4.0.0 - org.baeldung - spring-data-couchbase-2b - 0.1-SNAPSHOT - spring-data-couchbase-2b - jar - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-context-support - ${spring-framework.version} - - - org.springframework.data - spring-data-couchbase - ${spring-data-couchbase.version} - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - - joda-time - joda-time - ${joda-time.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - org.springframework - spring-test - ${spring-framework.version} - test - - - junit - junit - ${junit.version} - test - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 4.2.4.RELEASE - 2.1.1.RELEASE - 5.2.4.Final - 2.9.2 - 1.1.3 - 1.7.12 - 4.11 - - - - diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java deleted file mode 100644 index 9220e157ed..0000000000 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Person { - - @Id - private String id; - @Field - @NotNull - private String firstName; - @Field - @NotNull - private String lastName; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - - public Person(String id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - public DateTime getCreated() { - return created; - } - public void setCreated(DateTime created) { - this.created = created; - } - public DateTime getUpdated() { - return updated; - } - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if(id != null) { - hash = hash * 31 + id.hashCode(); - } - if(firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if(lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; - Person other = (Person) obj; - return this.hashCode() == other.hashCode(); - } -} diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java deleted file mode 100644 index 9c266c2c62..0000000000 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Student { - private static final String NAME_REGEX = "^[a-zA-Z .'-]+$"; - - @Id - private String id; - @Field - @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) - private String firstName; - @Field - @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) - private String lastName; - @Field - @Past - private DateTime dateOfBirth; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - @Version - private long version; - - public Student() {} - - public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - this.dateOfBirth = dateOfBirth; - } - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - public DateTime getDateOfBirth() { - return dateOfBirth; - } - public void setDateOfBirth(DateTime dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - public DateTime getCreated() { - return created; - } - public void setCreated(DateTime created) { - this.created = created; - } - public DateTime getUpdated() { - return updated; - } - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if(id != null) { - hash = hash * 31 + id.hashCode(); - } - if(firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if(lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - if(dateOfBirth != null) { - hash = hash * 31 + dateOfBirth.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; - Student other = (Student) obj; - return this.hashCode() == other.hashCode(); - } -} \ No newline at end of file diff --git a/spring-data-couchbase-2b/src/site/site.xml b/spring-data-couchbase-2b/src/site/site.xml deleted file mode 100644 index dda96feecd..0000000000 --- a/spring-data-couchbase-2b/src/site/site.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - Spring Sample: ${project.name} - index.html - - - - org.springframework.maven.skins - maven-spring-skin - 1.0.5 - - - - - - - - - - - - - diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java b/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java deleted file mode 100644 index 6f040c34db..0000000000 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.spring.data.couchbase; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.baeldung.spring.data.couchbase") -public class IntegrationTestConfig { -} diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java b/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java deleted file mode 100644 index c298ef0a61..0000000000 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.spring.data.couchbase; - -import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; -import org.springframework.data.couchbase.core.query.Consistency; - -public class TestCouchbaseConfig extends MyCouchbaseConfig { - - @Override - public String typeKey() { - return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE; - } - - @Override - public Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; - } -} diff --git a/spring-data-couchbase-2b/src/test/resources/logback.xml b/spring-data-couchbase-2b/src/test/resources/logback.xml deleted file mode 100644 index d9067fd1da..0000000000 --- a/spring-data-couchbase-2b/src/test/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 3a6e330564..084695c2f3 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -69,6 +69,17 @@ log4j-over-slf4j ${org.slf4j.version} + + + org.elasticsearch + elasticsearch + 2.3.5 + + + com.alibaba + fastjson + 1.2.13 + diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java new file mode 100644 index 0000000000..b8ad59e2e2 --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java @@ -0,0 +1,52 @@ +package com.baeldung.elasticsearch; + +import java.util.Date; + +public class Person { + + private int age; + + private String fullName; + + private Date dateOfBirth; + + public Person() { + + } + + public Person(int age, String fullName, Date dateOfBirth) { + super(); + this.age = age; + this.fullName = fullName; + this.dateOfBirth = dateOfBirth; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + @Override + public String toString() { + return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]"; + } +} diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java new file mode 100644 index 0000000000..4ab5d40788 --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -0,0 +1,101 @@ +package com.baeldung.elasticsearch; + +import static org.elasticsearch.node.NodeBuilder.*; +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.search.SearchType; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.node.Node; +import org.elasticsearch.search.SearchHit; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; + +public class ElasticSearchUnitTests { + private List listOfPersons = new ArrayList(); + String jsonString = null; + Client client = null; + + @Before + public void setUp() { + Person person1 = new Person(10, "John Doe", new Date()); + Person person2 = new Person(25, "Janette Doe", new Date()); + listOfPersons.add(person1); + listOfPersons.add(person2); + jsonString = JSON.toJSONString(listOfPersons); + Node node = nodeBuilder().clusterName("elasticsearch").client(true).node(); + client = node.client(); + } + + @Test + public void givenJsonString_whenJavaObject_thenIndexDocument() { + String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); + String index = response.getIndex(); + String type = response.getType(); + assertTrue(response.isCreated()); + assertEquals(index, "people"); + assertEquals(type, "Doe"); + } + + @Test + public void givenDocumentId_whenJavaObject_thenDeleteDocument() { + String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); + String id = response.getId(); + DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get(); + assertTrue(deleteResponse.isFound()); + } + + @Test + public void givenSearchRequest_whenMatchAll_thenReturnAllResults() { + SearchResponse response = client.prepareSearch().execute().actionGet(); + SearchHit[] searchHits = response.getHits().getHits(); + List results = new ArrayList(); + for (SearchHit hit : searchHits) { + String sourceAsString = hit.getSourceAsString(); + Person person = JSON.parseObject(sourceAsString, Person.class); + results.add(person); + } + } + + @Test + public void givenSearchParamters_thenReturnResults() { + boolean isExecutedSuccessfully = true; + SearchResponse response = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); + + SearchResponse response2 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); + + SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); + try { + response2.getHits(); + response3.getHits(); + List searchHits = Arrays.asList(response.getHits().getHits()); + final List results = new ArrayList(); + searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class))); + } catch (Exception e) { + isExecutedSuccessfully = false; + } + assertTrue(isExecutedSuccessfully); + } + + @Test + public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { + XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get(); + assertTrue(response.isCreated()); + } +} diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java index 06ad21647b..bb4b268ca7 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java @@ -140,7 +140,7 @@ public class GridFSIntegrationTest { assertNotNull(gridFSDBFiles); assertThat(gridFSDBFiles.size(), is(2)); } - + @Test public void givenMetadataAndFilesExist_whenFindingAllFilesOnQuery_thenFilesWithMetadataAreFoundOnQuery() { DBObject metaDataUser1 = new BasicDBObject(); diff --git a/spring-data-neo4j/README.md b/spring-data-neo4j/README.md index e62c69f8b9..0f13d9dbc9 100644 --- a/spring-data-neo4j/README.md +++ b/spring-data-neo4j/README.md @@ -1,7 +1,7 @@ ## Spring Data Neo4j ### Relevant Articles: -- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-tutorial) +- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro) ### Build the Project with Tests Running ``` diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index ac9a7260be..fb4fda1497 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; - -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver") - .setURI(URL); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 2b6394184d..81935b2293 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; - @EnableTransactionManagement -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -@Profile({"embedded", "test"}) +@Profile({ "embedded", "test" }) public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index e48dfaf276..029754c0fc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.Collection; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Movie { @@ -21,9 +21,11 @@ public class Movie { private int released; private String tagline; - @Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List roles; + @Relationship(type = "ACTED_IN", direction = Relationship.INCOMING) + private List roles; - public Movie() { } + public Movie() { + } public String getTitle() { return title; @@ -56,6 +58,5 @@ public class Movie { public void setRoles(List roles) { this.roles = roles; } - - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index d96dc07530..dc5a850f29 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.GraphId; @@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { @GraphId @@ -21,7 +20,8 @@ public class Person { @Relationship(type = "ACTED_IN") private List movies; - public Person() { } + public Person() { + } public String getName() { return name; @@ -46,5 +46,5 @@ public class Person { public void setMovies(List movies) { this.movies = movies; } - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 20512a10ad..40dabb054b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; @@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode; import java.util.Collection; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { @GraphId diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 850d2336ba..1bd605a7bc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository { Collection findByTitleContaining(@Param("title") String title); @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}") - List> graph(@Param("limit") int limit); + List> graph(@Param("limit") int limit); } - - diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index 4c287f99a4..f7f694c07f 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -4,8 +4,7 @@ import com.baeldung.spring.data.neo4j.domain.Person; import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.stereotype.Repository; - @Repository public interface PersonRepository extends GraphRepository { - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index 532cc79091..d760d19066 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -15,31 +15,31 @@ public class MovieService { MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels= new ArrayList>(); - int i=0; + List> nodes = new ArrayList>(); + List> rels = new ArrayList>(); + int i = 0; while (result.hasNext()) { Map row = result.next(); - nodes.add(map("title",row.get("movie"),"label","movie")); - int target=i; + nodes.add(map("title", row.get("movie"), "label", "movie")); + int target = i; i++; for (Object name : (Collection) row.get("cast")) { - Map actor = map("title", name,"label","actor"); + Map actor = map("title", name, "label", "actor"); int source = nodes.indexOf(actor); if (source == -1) { nodes.add(actor); source = i++; } - rels.add(map("source",source,"target",target)); + rels.add(map("source", source, "target", target)); } } return map("nodes", nodes, "links", rels); } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); - result.put(key1,value1); - result.put(key2,value2); + Map result = new HashMap(2); + result.put(key1, value1); + result.put(key2, value2); return result; } diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java index 8061b3c2a7..0e54208c31 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java @@ -82,8 +82,7 @@ public class MovieRepositoryTest { @DirtiesContext public void testFindAll() { System.out.println("findAll"); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertNotNull(result); assertEquals(1, result.size()); } @@ -93,8 +92,7 @@ public class MovieRepositoryTest { public void testFindByTitleContaining() { System.out.println("findByTitleContaining"); String title = "Italian"; - Collection result = - movieRepository.findByTitleContaining(title); + Collection result = movieRepository.findByTitleContaining(title); assertNotNull(result); assertEquals(1, result.size()); } @@ -126,8 +124,7 @@ public class MovieRepositoryTest { public void testDeleteAll() { System.out.println("deleteAll"); movieRepository.deleteAll(); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertEquals(0, result.size()); } } diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java index 9a42545d6c..4c55fc3179 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.redis.queue; - public interface MessagePublisher { void publish(final String message); diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index f4b3180a37..2a595305bd 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(final RedisTemplate redisTemplate, - final ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index f7f28aa9f1..5ae694a04f 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung @@ -15,7 +15,7 @@ org.springframework.boot spring-boot-starter-parent 1.3.3.RELEASE - + diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java index 6e8e62f52c..94eddc5b3e 100644 --- a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java +++ b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringDataRestApplication { - public static void main(String[] args) { - SpringApplication.run(SpringDataRestApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(SpringDataRestApplication.class, args); + } } diff --git a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java deleted file mode 100644 index ebbf0d49ab..0000000000 --- a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung; - -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.data.rest.core.annotation.RepositoryRestResource; - -import java.util.List; - -@RepositoryRestResource(collectionResourceRel = "users", path = "users") -public interface UserRepository extends PagingAndSortingRepository { - List findByName(@Param("name") String name); -} diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java new file mode 100644 index 0000000000..89ab848e81 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java @@ -0,0 +1,30 @@ +package com.baeldung.config; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener; +import org.springframework.validation.Validator; + +@Configuration +public class ValidatorEventRegister implements InitializingBean { + + @Autowired + ValidatingRepositoryEventListener validatingRepositoryEventListener; + + @Autowired + private Map validators; + + @Override + public void afterPropertiesSet() throws Exception { + List events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); + + for (Map.Entry entry : validators.entrySet()) { + events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); + } + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java new file mode 100644 index 0000000000..ee84738e7a --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java @@ -0,0 +1,25 @@ +package com.baeldung.exception.handlers; + +import java.util.stream.Collectors; + +import org.springframework.data.rest.core.RepositoryConstraintViolationException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice +public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler({ RepositoryConstraintViolationException.class }) + public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { + RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; + + String errors = nevEx.getErrors().getAllErrors().stream().map(p -> p.toString()).collect(Collectors.joining("\n")); + return new ResponseEntity(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); + } + +} \ No newline at end of file diff --git a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java similarity index 96% rename from spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java rename to spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java index a7a35a2573..4eb9773e36 100644 --- a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java new file mode 100644 index 0000000000..0b55ac89b6 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.repositories; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import com.baeldung.models.WebsiteUser; + +@RepositoryRestResource(collectionResourceRel = "users", path = "users") +public interface UserRepository extends CrudRepository { + +} diff --git a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java b/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java new file mode 100644 index 0000000000..0380332708 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java @@ -0,0 +1,33 @@ +package com.baeldung.validators; + +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; + +import com.baeldung.models.WebsiteUser; + +@Component("beforeCreateWebsiteUserValidator") +public class WebsiteUserValidator implements Validator { + + @Override + public boolean supports(Class clazz) { + return WebsiteUser.class.equals(clazz); + } + + @Override + public void validate(Object obj, Errors errors) { + + WebsiteUser user = (WebsiteUser) obj; + if (checkInputString(user.getName())) { + errors.rejectValue("name", "name.empty"); + } + + if (checkInputString(user.getEmail())) { + errors.rejectValue("email", "email.empty"); + } + } + + private boolean checkInputString(String input) { + return (input == null || input.trim().length() == 0); + } +} diff --git a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java b/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java new file mode 100644 index 0000000000..b185c6d5ab --- /dev/null +++ b/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java @@ -0,0 +1,100 @@ +package com.baeldung.validator; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +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.SpringApplicationConfiguration; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = SpringDataRestApplication.class) +@WebAppConfiguration +public class SpringDataRestValidatorTest { + public static final String URL = "http://localhost"; + + private MockMvc mockMvc; + + @Autowired + protected WebApplicationContext wac; + + @Before + public void setup() { + mockMvc = webAppContextSetup(wac).build(); + } + + @Test + public void whenStartingApplication_thenCorrectStatusCode() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); + }; + + @Test + public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().is2xxSuccessful()) + .andExpect(redirectedUrl("http://localhost/users/1")); + } + + @Test + public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + user.setEmail(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java index 9c4fd55fa4..64f12e82e9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java @@ -18,16 +18,16 @@ import javax.sql.DataSource; @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) public class InvalidResourceUsageExceptionTest { - @Autowired - private IFooService fooService; + @Autowired + private IFooService fooService; - @Autowired - private DataSource restDataSource; + @Autowired + private DataSource restDataSource; - @Test(expected = InvalidDataAccessResourceUsageException.class) - public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.execute("revoke select from tutorialuser"); + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("revoke select from tutorialuser"); try { fooService.findAll(); @@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest { } } - @Test(expected = BadSqlGrammarException.class) - public void whenIncorrectSql_thenBadSqlGrammarException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); - } + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java index b8b012c061..957207b7e6 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -4,78 +4,78 @@ import java.io.Serializable; public class Item implements Serializable { - private static final long serialVersionUID = 1L; - private Integer itemId; - private String itemName; - private String itemDescription; - private Integer itemPrice; + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; - // constructors - public Item() { + // constructors + public Item() { - } + } - public Item(final Integer itemId, final String itemName, final String itemDescription) { - super(); - this.itemId = itemId; - this.itemName = itemName; - this.itemDescription = itemDescription; - } + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Item other = (Item) obj; - if (itemId == null) { - if (other.itemId != null) - return false; - } else if (!itemId.equals(other.itemId)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } - public Integer getItemId() { - return itemId; - } + public Integer getItemId() { + return itemId; + } - public void setItemId(final Integer itemId) { - this.itemId = itemId; - } + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } - public String getItemName() { - return itemName; - } + public String getItemName() { + return itemName; + } - public void setItemName(final String itemName) { - this.itemName = itemName; - } + public void setItemName(final String itemName) { + this.itemName = itemName; + } - public String getItemDescription() { - return itemDescription; - } + public String getItemDescription() { + return itemDescription; + } - public Integer getItemPrice() { - return itemPrice; - } + public Integer getItemPrice() { + return itemPrice; + } - public void setItemPrice(final Integer itemPrice) { - this.itemPrice = itemPrice; - } + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } - public void setItemDescription(final String itemDescription) { - this.itemDescription = itemDescription; - } + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java index 57f32cfe50..ff9ccb017b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -5,16 +5,15 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - + @SuppressWarnings("deprecation") public static Session getHibernateSession() { - final SessionFactory sf = new Configuration() - .configure("criteria.cfg.xml").buildSessionFactory(); + final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory(); - // factory = new Configuration().configure().buildSessionFactory(); - final Session session = sf.openSession(); - return session; + // factory = new Configuration().configure().buildSessionFactory(); + final Session session = sf.openSession(); + return session; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 4db94f2ad7..83e3c2f9a5 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil; public class ApplicationView { - // default Constructor - public ApplicationView() { + // default Constructor + public ApplicationView() { - } + } - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + Transaction tx = null; - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.add(Restrictions.like("itemName", "%item One%")); + final List results = cr.list(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + tx = session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.gt("itemPrice", 1000)); + final List greaterThanItemsList = cr.list(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); + } + session.close(); + return greaterThanItems; + } - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.lt("itemPrice", 1000)); + final List lessThanItemsList = cr.list(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i).getItemName(); + } + session.close(); + return lessThanItems; + } - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.like("itemName", "%chair%")); + final List likeItemsList = cr.list(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i).getItemName(); + } + session.close(); + return likeItems; + } - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.ilike("itemName", "%Chair%")); + final List ilikeItemsList = cr.list(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i).getItemName(); + } + session.close(); + return ilikeItems; + } - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + // To get items having price more than 1000 + cr.add(Restrictions.between("itemPrice", 100, 200)); + final List betweenItemsList = cr.list(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i).getItemName(); + } + session.close(); + return betweenItems; + } - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + final List nullItemsList = cr.list(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i).getItemName(); + } + session.close(); + return nullDescItems; + } - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNotNull("itemDescription")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + cr.add(Restrictions.like("itemName", "chair%")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + cr.add(andExample); + final List andItemsList = cr.list(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i).getItemName(); + } + session.close(); + return andItems; + } - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); + cr.add(orExample); + final List orItemsList = cr.list(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i).getItemName(); + } + session.close(); + return orItems; + } - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()) - .list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.addOrder(Order.asc("itemName")); + cr.addOrder(Order.desc("itemPrice")).list(); + final List sortedItemsList = cr.list(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i).getItemName(); + } + session.close(); + return sortedItems; + } - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class) - .setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index ec8dc32200..f4a9b8a678 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -5,54 +5,54 @@ import java.io.Serializable; import java.sql.Date; @Entity -@Table (name = "USER_ORDER") -public class OrderDetail implements Serializable{ +@Table(name = "USER_ORDER") +public class OrderDetail implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="ORDER_ID") - private Long orderId; - - public OrderDetail(){ - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } + private static final long serialVersionUID = 1L; - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } + @Id + @GeneratedValue + @Column(name = "ORDER_ID") + private Long orderId; + + public OrderDetail() { + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } - - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 22b4fdc76c..2559d5f048 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -6,66 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserEager implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserEager() { - } + private static final long serialVersionUID = 1L; - public UserEager(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserEager other = (UserEager) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserEager() { + } - public Long getUserId() { - return userId; - } + public UserEager(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index 5038fb90ef..5852e74418 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -6,67 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserLazy implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserLazy() { - } + private static final long serialVersionUID = 1L; - public UserLazy(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserLazy other = (UserLazy) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserLazy() { + } - public Long getUserId() { - return userId; - } + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index bbd7729232..c7be96abb7 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - SessionFactory sf; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - - // fetching.cfg.xml is used for this example - return sf.openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + // two config files are there + // one with lazy loading enabled + // another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } public static Session getHibernateSession() { - return new Configuration() - .configure("fetching.cfg.xml") - .buildSessionFactory() - .openSession(); + return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java index bdd48d6aa6..d36a1e58cf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java @@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; -@NamedNativeQueries({ - @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), - @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) @Entity @Audited // @Proxy(lazy = false) public class Foo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); - public Foo() { - super(); - } + public Foo() { + super(); + } - public Foo(final String name) { - super(); - this.name = name; - } + public Foo(final String name) { + super(); + this.name = name; + } - // + // - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(final Bar bar) { - this.bar = bar; - } + public void setBar(final Bar bar) { + this.bar = bar; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - 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 int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java index 3bd8c5ee00..88186098cc 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java @@ -14,178 +14,170 @@ import com.baeldung.hibernate.criteria.view.ApplicationView; public class HibernateCriteriaTest { - final private ApplicationView av = new ApplicationView(); + final private ApplicationView av = new ApplicationView(); - @Test - public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); - } - - @Test - public void testLikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); - final String expectedLikeItems[] = new String[expectedLikeList.size()]; - for (int i = 0; i < expectedLikeList.size(); i++) { - expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLikeItems, av.likeCriteria()); - } + @Test + public void testPerformanceOfCriteria() { + assertTrue(av.checkIfCriteriaTimeLower()); + } - @Test - public void testILikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); - final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; - for (int i = 0; i < expectedChairCaseList.size(); i++) { - expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); + @Test + public void testLikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, av.likeCriteria()); + } - } + @Test + public void testILikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - @Test - public void testNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null") - .list(); - final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { - expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); - } + } - @Test - public void testIsNotNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNotNullDescItemsList = session - .createQuery("From Item where itemDescription is not null").list(); - final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { - expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); + @Test + public void testNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list(); + final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { + expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); + } - } + @Test + public void testIsNotNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list(); + final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { + expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); - @Test - public void testAverageProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item") - .list(); + } - final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; - for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { - expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); + @Test + public void testAverageProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list(); - } + final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; + for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { + expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); - @Test - public void testRowCountProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); - final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; - for (int i = 0; i < expectedCountProjItemsList.size(); i++) { - expectedCountProjItems[i] = expectedCountProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); - } + } - @Test - public void testOrCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedOrCritItemsList = session - .createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); - final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; - for (int i = 0; i < expectedOrCritItemsList.size(); i++) { - expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); - } + @Test + public void testRowCountProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); + final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; + for (int i = 0; i < expectedCountProjItemsList.size(); i++) { + expectedCountProjItems[i] = expectedCountProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); + } - @Test - public void testAndCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAndCritItemsList = session - .createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); - final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; - for (int i = 0; i < expectedAndCritItemsList.size(); i++) { - expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); - } + @Test + public void testOrCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); + final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; + for (int i = 0; i < expectedOrCritItemsList.size(); i++) { + expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); + } - @Test - public void testMultiCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedMultiCritItemsList = session - .createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); - final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; - for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { - expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); - } + @Test + public void testAndCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); + final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; + for (int i = 0; i < expectedAndCritItemsList.size(); i++) { + expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); + } - @Test - public void testSortCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedSortCritItemsList = session - .createQuery("From Item order by itemName asc, itemPrice desc").list(); - final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; - for (int i = 0; i < expectedSortCritItemsList.size(); i++) { - expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); - } + @Test + public void testMultiCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); + final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; + for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { + expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); + } - @Test - public void testGreaterThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); - final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; - for (int i = 0; i < expectedGreaterThanList.size(); i++) { - expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); - } + @Test + public void testSortCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list(); + final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; + for (int i = 0; i < expectedSortCritItemsList.size(); i++) { + expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); + } - @Test - public void testLessThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); - final String expectedLessThanItems[] = new String[expectedLessList.size()]; - for (int i = 0; i < expectedLessList.size(); i++) { - expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); - } + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); + } - @Test - public void betweenCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200") - .list(); - final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; - for (int i = 0; i < expectedBetweenList.size(); i++) { - expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); - } + @Test + public void testLessThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); + } + + @Test + public void betweenCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java index 8341df9fcb..99164efb7a 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure; public class HibernateCriteriaTestRunner { - public static void main(final String[] args) { - Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); - for (Failure failure : result.getFailures()) { - - } - } + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java index ab27a6ba82..2911fb4725 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -7,5 +7,5 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ HibernateCriteriaTest.class }) public class HibernateCriteriaTestSuite { - + } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index a650f8eb37..42245ca89e 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -13,31 +13,30 @@ import static org.junit.Assert.assertTrue; public class HibernateFetchingTest { + // this loads sample data in the database + @Before + public void addFecthingTestData() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } - //this loads sample data in the database - @Before - public void addFecthingTestData(){ - FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - } - - //testLazyFetching() tests the lazy loading - //Since it lazily loaded so orderDetalSetLazy won't - //be initialized - @Test - public void testLazyFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetLazy = fav.lazyLoaded(); - assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); - } - - //testEagerFetching() tests the eager loading - //Since it eagerly loaded so orderDetalSetLazy would - //be initialized - @Test - public void testEagerFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetEager = fav.eagerLoaded(); - assertTrue(Hibernate.isInitialized(orderDetalSetEager)); - } + // testLazyFetching() tests the lazy loading + // Since it lazily loaded so orderDetalSetLazy won't + // be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + // testEagerFetching() tests the eager loading + // Since it eagerly loaded so orderDetalSetLazy would + // be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java index aadaefbe44..2e729c5680 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java @@ -1,6 +1,5 @@ package com.baeldung.persistence.save; - import com.baeldung.persistence.model.Person; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -25,16 +24,9 @@ public class SaveMethodsTest { @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration() - .addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( - configuration.getProperties()).build(); + Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } @@ -44,7 +36,6 @@ public class SaveMethodsTest { session.beginTransaction(); } - @Test public void whenPersistTransient_thenSavedToDatabaseOnCommit() { @@ -244,7 +235,6 @@ public class SaveMethodsTest { assertNotNull(session.get(Person.class, person.getId())); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java index 238b228101..db64107405 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java @@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo; import com.baeldung.spring.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooStoredProceduresIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); @@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getFoosByNameExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getAllFoosExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo(randomAlphabetic(6))); // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity( - Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); @SuppressWarnings("unchecked") List allFoos = sqlQuery.list(); for (Foo foo : allFoos) { @@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo("NewFooName")); // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)") - .addEntity(Foo.class).setParameter("fooName", "NewFooName"); + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName = sqlQuery.list(); for (Foo foo : allFoosByName) { @@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest { } // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName") - .setParameter("fooName", "NewFooName"); + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName2 = namedQuery.list(); for (Foo foo : allFoosByName2) { diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml new file mode 100644 index 0000000000..8e83f82f38 --- /dev/null +++ b/spring-jms/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + com.baeldung + spring-jms + 0.0.1-SNAPSHOT + war + spring-jms + Introduction to Spring JMS + + + 4.3.2.RELEASE + 5.12.0 + 4.12 + + + + + + org.springframework + spring-jms + ${springframework.version} + + + + org.apache.activemq + activemq-all + ${activemq.version} + + + junit + junit + ${junit.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-jms + false + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + spring-jms + + diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java new file mode 100644 index 0000000000..ff4f262b38 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.jms; + +public class Employee { + private String name; + private Integer age; + + public Employee(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Integer getAge() { + return age; + } + + public String toString() { + return "Employee: name(" + name + "), age(" + age + ")"; + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java new file mode 100644 index 0000000000..927762f05b --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.jms; + +import org.springframework.jms.core.JmsTemplate; + +import javax.jms.Queue; +import java.util.HashMap; +import java.util.Map; + +public class SampleJmsMessageSender { + + private JmsTemplate jmsTemplate; + private Queue queue; + + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; + } + + public void setQueue(Queue queue) { + this.queue = queue; + } + + public void simpleSend() { + jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world")); + } + + public void sendMessage(final Employee employee) { + this.jmsTemplate.convertAndSend(employee); + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java new file mode 100644 index 0000000000..6d4bef5402 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.jms; + +import org.springframework.jms.core.JmsTemplate; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.Queue; +import javax.jms.TextMessage; +import java.util.Map; + +public class SampleListener implements MessageListener { + + private JmsTemplate jmsTemplate; + private Queue queue; + + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; + } + + public void setQueue(Queue queue) { + this.queue = queue; + } + + public void onMessage(Message message) { + if (message instanceof TextMessage) { + try { + + String msg = ((TextMessage) message).getText(); + } catch (JMSException ex) { + throw new RuntimeException(ex); + } + } + } + + public Employee receiveMessage() throws JMSException { + Map map = (Map) this.jmsTemplate.receiveAndConvert(); + return new Employee((String) map.get("name"), (Integer) map.get("age")); + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java new file mode 100644 index 0000000000..368a62841f --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.jms; + +import org.springframework.jms.support.converter.MessageConversionException; +import org.springframework.jms.support.converter.MessageConverter; + +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.Session; + +public class SampleMessageConverter implements MessageConverter { + + public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { + Employee employee = (Employee) object; + MapMessage message = session.createMapMessage(); + message.setString("name", employee.getName()); + message.setInt("age", employee.getAge()); + return message; + } + + public Object fromMessage(Message message) throws JMSException, MessageConversionException { + MapMessage mapMessage = (MapMessage) message; + return new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); + } + +} diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml new file mode 100644 index 0000000000..016b07e831 --- /dev/null +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -0,0 +1,18 @@ + + + + + + + + + + diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml new file mode 100644 index 0000000000..28bf848e59 --- /dev/null +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java new file mode 100644 index 0000000000..c0761939ad --- /dev/null +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.jms; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DefaultTextMessageSenderTest { + + private static SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @BeforeClass + public static void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java new file mode 100644 index 0000000000..c0761939ad --- /dev/null +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.jms; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DefaultTextMessageSenderTest { + + private static SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @BeforeClass + public static void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} diff --git a/spring-jpa-jndi/README.md b/spring-jpa-jndi/README.md deleted file mode 100644 index 6a99253545..0000000000 --- a/spring-jpa-jndi/README.md +++ /dev/null @@ -1,7 +0,0 @@ -========= - -## Spring JPA using JNDI Project - - -### Relevant Articles: -- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](http://www.baeldung.com/spring-jpa-fndi) \ No newline at end of file diff --git a/spring-jpa-jndi/pom.xml b/spring-jpa-jndi/pom.xml deleted file mode 100644 index f7042f2384..0000000000 --- a/spring-jpa-jndi/pom.xml +++ /dev/null @@ -1,145 +0,0 @@ - - 4.0.0 - - com.baeldung - spring-jpa-jndi - 0.1-SNAPSHOT - war - - spring-jpa-jndi - - - - - - - org.springframework - spring-orm - ${org.springframework.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - - - javax.servlet - jstl - ${javax.servlet.jstl.version} - - - javax.servlet - servlet-api - ${javax.servlet.servlet-api.version} - - - - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - xml-apis - xml-apis - 1.4.01 - - - org.javassist - javassist - ${javassist.version} - - - org.springframework.data - spring-data-jpa - ${spring-data-jpa.version} - - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - 2.2.5 - - - - - - spring-jpa-jndi - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - false - - - - - - - - - - 4.3.2.RELEASE - 3.20.0-GA - - - 1.2 - 2.5 - - - 4.3.11.Final - 1.8.2.RELEASE - 1.4.192 - - - 1.7.13 - 1.1.3 - - - 5.2.2.Final - - - 3.5.1 - 2.7 - 2.4 - - - - - \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java deleted file mode 100644 index 0133a36a14..0000000000 --- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -import org.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao { - - @PersistenceContext - private EntityManager entityManager; - - @SuppressWarnings("unchecked") - public List findAll() { - return entityManager.createQuery("from " + Foo.class.getName()).getResultList(); - } - -} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index d351fc54b8..0000000000 --- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ID") - private long id; - @Column(name = "NAME") - private String name; - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } -} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java deleted file mode 100644 index a3109f5042..0000000000 --- a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.persistence.service; - -import java.util.List; - -import org.baeldung.persistence.dao.FooDao; -import org.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService { - - @Autowired - private FooDao dao; - - public List findAll() { - return dao.findAll(); - } - -} diff --git a/spring-jpa-jndi/src/main/resources/logback.xml b/spring-jpa-jndi/src/main/resources/logback.xml deleted file mode 100644 index 1146dade63..0000000000 --- a/spring-jpa-jndi/src/main/resources/logback.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 5acdae7765..ebb9c5bc83 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -4,6 +4,7 @@ com.baeldung spring-jpa 0.1-SNAPSHOT + war spring-jpa @@ -21,6 +22,11 @@ spring-context ${org.springframework.version} + + org.springframework + spring-webmvc + ${org.springframework.version} + @@ -73,6 +79,18 @@ javax.el-api 2.2.5 + + + + javax.servlet + jstl + ${javax.servlet.jstl.version} + + + javax.servlet + servlet-api + ${javax.servlet.servlet-api.version} + @@ -147,6 +165,16 @@ 1.8 + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + org.apache.maven.plugins @@ -197,6 +225,10 @@ 5.1.38 1.10.2.RELEASE 1.4.192 + + + 1.2 + 2.5 1.7.13 @@ -224,6 +256,7 @@ 2.19.1 2.7 1.4.18 + 2.4 diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java similarity index 90% rename from spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java rename to spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java index 7ea731d9d4..7f28c958f1 100644 --- a/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java +++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java @@ -36,7 +36,7 @@ public class PersistenceJNDIConfig { } @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); @@ -46,12 +46,8 @@ public class PersistenceJNDIConfig { } @Bean - public DataSource dataSource() { - try { - return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url")); - } catch (NamingException e) { - throw new IllegalArgumentException("Error looking up JNDI datasource", e); - } + public DataSource dataSource() throws NamingException { + return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url")); } @Bean diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java b/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java similarity index 100% rename from spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java rename to spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java b/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java similarity index 100% rename from spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java rename to spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java new file mode 100644 index 0000000000..34913632d8 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.multiple.dao.user; + +import org.baeldung.persistence.multiple.model.user.Possession; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PossessionRepository extends JpaRepository { + +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java new file mode 100644 index 0000000000..97b5803d73 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java @@ -0,0 +1,86 @@ +package org.baeldung.persistence.multiple.model.user; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_jpa_user") +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java index 305568bad8..1c6399dc44 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java @@ -1,10 +1,13 @@ package org.baeldung.persistence.multiple.model.user; +import java.util.List; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @@ -22,6 +25,9 @@ public class User { private int age; + @OneToMany + List possessionList; + public User() { super(); } @@ -58,6 +64,14 @@ public class User { this.age = age; } + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + @Override public String toString() { final StringBuilder builder = new StringBuilder(); diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java b/spring-jpa/src/main/java/org/baeldung/web/MainController.java similarity index 100% rename from spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java rename to spring-jpa/src/main/java/org/baeldung/web/MainController.java diff --git a/spring-jpa-jndi/src/main/resources/context.xml b/spring-jpa/src/main/resources/context.xml similarity index 100% rename from spring-jpa-jndi/src/main/resources/context.xml rename to spring-jpa/src/main/resources/context.xml diff --git a/spring-jpa-jndi/src/main/resources/persistence-jndi.properties b/spring-jpa/src/main/resources/persistence-jndi.properties similarity index 100% rename from spring-jpa-jndi/src/main/resources/persistence-jndi.properties rename to spring-jpa/src/main/resources/persistence-jndi.properties diff --git a/spring-jpa-jndi/src/main/resources/server.xml b/spring-jpa/src/main/resources/server.xml similarity index 100% rename from spring-jpa-jndi/src/main/resources/server.xml rename to spring-jpa/src/main/resources/server.xml diff --git a/spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp similarity index 100% rename from spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp rename to spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java index 7e6b2722fa..f20af34057 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java @@ -1,14 +1,18 @@ package org.baeldung.persistence.service; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.util.Arrays; + import org.baeldung.config.ProductConfig; import org.baeldung.config.UserConfig; import org.baeldung.persistence.multiple.dao.product.ProductRepository; +import org.baeldung.persistence.multiple.dao.user.PossessionRepository; import org.baeldung.persistence.multiple.dao.user.UserRepository; import org.baeldung.persistence.multiple.model.product.Product; +import org.baeldung.persistence.multiple.model.user.Possession; import org.baeldung.persistence.multiple.model.user.User; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,15 +20,20 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) +@EnableTransactionManagement public class JpaMultipleDBIntegrationTest { @Autowired private UserRepository userRepository; + @Autowired + private PossessionRepository possessionRepository; + @Autowired private ProductRepository productRepository; @@ -37,9 +46,14 @@ public class JpaMultipleDBIntegrationTest { user.setName("John"); user.setEmail("john@test.com"); user.setAge(20); + Possession p = new Possession("sample"); + p = possessionRepository.save(p); + user.setPossessionList(Arrays.asList(p)); user = userRepository.save(user); - - assertNotNull(userRepository.findOne(user.getId())); + final User result = userRepository.findOne(user.getId()); + assertNotNull(result); + System.out.println(result.getPossessionList()); + assertTrue(result.getPossessionList().size() == 1); } @Test diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index f97f53b82c..907043b8ce 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest { final Foo foo = new Foo(randomAlphabetic(6)); fooService.create(foo); fooService.findOne(foo.getId()); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest { return nativeQuery.executeUpdate(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @Test public final void givenCacheableQueryIsExecuted_thenItIsCached() { new TransactionTemplate(platformTransactionManager).execute(status -> { - return entityManager.createQuery("select f from Foo f") - .setHint("org.hibernate.cacheable", true) - .getResultList(); + return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); assertThat(size, greaterThan(0)); } } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 67e4c6ae1d..58a92002c8 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -30,7 +30,7 @@ public class User { private String email; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JsonApiToMany @JsonApiIncludeByDefault private Set roles; diff --git a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java index 32be4c6a0a..94309cf1a6 100644 --- a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java +++ b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MocksApplication { - public static void main(String[] args) { - SpringApplication.run(MocksApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MocksApplication.class, args); + } } diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 098afffba4..8248343105 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -6,6 +6,7 @@ 0.1-SNAPSHOT spring-mvc-java war + @@ -34,16 +35,12 @@ spring-messaging ${org.springframework.version} + - - com.fasterxml.jackson.core - jackson-core - 2.7.3 - com.fasterxml.jackson.core jackson-databind - 2.7.3 + ${jackson.version} @@ -59,6 +56,7 @@ 1.2 runtime + org.springframework @@ -82,6 +80,11 @@ commons-fileupload 1.3.1 + + net.sourceforge.htmlunit + htmlunit + ${net.sourceforge.htmlunit} + @@ -95,18 +98,6 @@ ${thymeleaf.version} - - - com.fasterxml.jackson.core - jackson-core - 2.1.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.1.2 - - org.slf4j @@ -210,7 +201,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -244,18 +235,23 @@ 4.2.5.RELEASE 4.0.4.RELEASE 2.1.4.RELEASE + 2.7.8 + 4.3.11.Final 5.1.38 + 1.7.21 1.1.5 - + 5.2.2.Final + 19.0 3.4 + 1.3 4.12 @@ -263,6 +259,8 @@ 4.4.1 4.5 2.9.0 + 2.23 + 3.5.1 2.6 @@ -274,4 +272,5 @@ 1.8.7 - \ No newline at end of file + + diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java index c1f7f52215..76d53e132a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java @@ -2,14 +2,14 @@ package com.baeldung.model; public class Message { - private String from; - private String text; + private String from; + private String text; - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java index fc201ed016..9aad564b1e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java @@ -2,26 +2,26 @@ package com.baeldung.model; public class OutputMessage { - private String from; - private String text; - private String time; + private String from; + private String text; + private String time; - public OutputMessage(final String from, final String text, final String time) { + public OutputMessage(final String from, final String text, final String time) { - this.from = from; - this.text = text; - this.time = time; - } + this.from = from; + this.text = text; + this.time = time; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getTime() { - return time; - } + public String getTime() { + return time; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java index 6330041c60..5f3eb1312d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -10,15 +10,15 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { - @Override - public void configureMessageBroker(final MessageBrokerRegistry config) { - config.enableSimpleBroker("/topic"); - config.setApplicationDestinationPrefixes("/app"); - } + @Override + public void configureMessageBroker(final MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } - @Override - public void registerStompEndpoints(final StompEndpointRegistry registry) { - registry.addEndpoint("/chat").withSockJS(); - } + @Override + public void registerStompEndpoints(final StompEndpointRegistry registry) { + registry.addEndpoint("/chat").withSockJS(); + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java index 8dcfe68a84..e92abfdc47 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java @@ -22,59 +22,55 @@ import com.baeldung.model.Company; @Controller public class CompanyController { - Map companyMap = new HashMap<>(); + Map companyMap = new HashMap<>(); - @RequestMapping(value = "/company", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("companyHome", "company", new Company()); - } + @RequestMapping(value = "/company", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("companyHome", "company", new Company()); + } - @RequestMapping(value = "/company/{Id}", produces = { "application/json", - "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Company getCompanyById(@PathVariable final long Id) { - return companyMap.get(Id); - } + @RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Company getCompanyById(@PathVariable final long Id) { + return companyMap.get(Id); + } - @RequestMapping(value = "/addCompany", method = RequestMethod.POST) - public String submit(@ModelAttribute("company") final Company company, - final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", company.getName()); - model.addAttribute("id", company.getId()); + @RequestMapping(value = "/addCompany", method = RequestMethod.POST) + public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", company.getName()); + model.addAttribute("id", company.getId()); - companyMap.put(company.getId(), company); + companyMap.put(company.getId(), company); - return "companyView"; - } + return "companyView"; + } - @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getEmployeeDataFromCompany( - @MatrixVariable(pathVar = "employee") final Map matrixVars) { - return new ResponseEntity<>(matrixVars, HttpStatus.OK); - } + @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map matrixVars) { + return new ResponseEntity<>(matrixVars, HttpStatus.OK); + } - @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getCompanyName( - @MatrixVariable(value = "name", pathVar = "company") final String name) { - final Map result = new HashMap(); - result.put("name", name); - return new ResponseEntity<>(result, HttpStatus.OK); - } + @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) { + final Map result = new HashMap(); + result.put("name", name); + return new ResponseEntity<>(result, HttpStatus.OK); + } - @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - public Company getCompanyResponseBody() { - final Company company = new Company(2, "ABC"); - return company; - } + @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Company getCompanyResponseBody() { + final Company company = new Company(2, "ABC"); + return company; + } - @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCompanyResponseEntity() { - final Company company = new Company(3, "123"); - return new ResponseEntity(company, HttpStatus.OK); - } + @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getCompanyResponseEntity() { + final Company company = new Company(3, "123"); + return new ResponseEntity(company, HttpStatus.OK); + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index fd5fa6bc27..ef76059567 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -31,10 +31,8 @@ public class EmployeeController { return new ModelAndView("employeeHome", "employee", new Employee()); } - @RequestMapping(value = "/employee/{Id}", produces = {"application/json", "application/xml"}, method = RequestMethod.GET) - public - @ResponseBody - Employee getEmployeeById(@PathVariable final long Id) { + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java new file mode 100644 index 0000000000..111bf023f7 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java @@ -0,0 +1,24 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @RequestMapping(value = "/showForm", method = RequestMethod.GET) + public String showForm() { + return "message"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@RequestParam("message") final String message, final Model model) { + model.addAttribute("message", message); + return "message"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java index 8557b15492..7b2c6870df 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java similarity index 98% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java index 19bf4d0fac..0837100bfa 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopLoggingTest { +public class AopLoggingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java index 4ad5a3e1a6..c9ab2fb4bb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPerformanceTest { +public class AopPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java index c075db9fc6..cf9c83a93d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPublishingTest { +public class AopPublishingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java index 4d2df50d18..3b380315e8 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java @@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/com/baeldung/aop/beans.xml") -public class AopXmlConfigPerformanceTest { +public class AopXmlConfigPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java new file mode 100644 index 0000000000..7a23908fe5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; +import java.net.MalformedURLException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); + } + + // + + @Test + public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { + final String text = "Hello world!"; + HtmlPage page = webClient.getPage("http://localhost/message/showForm"); + System.out.println(page.asXml()); + + final HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + final HtmlForm form = page.getForms().get(0); + final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); + final HtmlPage newPage = submit.click(); + + final String receivedText = newPage.getHtmlElementById("received").getTextContent(); + + Assert.assertEquals(receivedText, text); + System.out.println(newPage.asXml()); + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient client = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java new file mode 100644 index 0000000000..6a7e961eb1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitTest { + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient webClient = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java new file mode 100644 index 0000000000..9919d7571d --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -0,0 +1,40 @@ +package com.baeldung.htmlunit; + +import java.util.List; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlAnchor; +import com.gargoylesoftware.htmlunit.html.HtmlHeading1; +import com.gargoylesoftware.htmlunit.html.HtmlHeading2; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitWebScraping { + + public static void main(final String[] args) throws Exception { + try (final WebClient webClient = new WebClient()) { + + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); + final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + + System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + + final HtmlPage postPage = latestPostLink.click(); + + final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); + System.out.println("Title: " + heading1.getTextContent()); + + final List headings2 = (List) postPage.getByXPath("//h2"); + + final StringBuilder sb = new StringBuilder(heading1.getTextContent()); + for (final HtmlHeading2 h2 : headings2) { + sb.append("\n").append(h2.getTextContent()); + } + + System.out.println(sb.toString()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java new file mode 100644 index 0000000000..17a68d67a5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.htmlunit; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class TestConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java index c1e79a2a63..86420a5fbd 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java @@ -23,7 +23,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTest { +public class EmployeeMvcIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java index 19806e0559..e84c20c973 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.web.controller; -import org.junit.Before; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -15,7 +15,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTestWithoutMockMvc { +public class EmployeeNoMvcIntegrationTest { @Autowired private EmployeeController employeeController; @@ -25,9 +25,10 @@ public class EmployeeTestWithoutMockMvc { employeeController.initEmployees(); } + // + @Test public void whenInitEmployees_thenVerifyValuesInitiation() { - Employee employee1 = employeeController.employeeMap.get(1L); Employee employee2 = employeeController.employeeMap.get(2L); Employee employee3 = employeeController.employeeMap.get(3L); diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index d1d1167369..db984eadfb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.web.controller; - import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import javax.servlet.ServletContext; @@ -25,7 +24,7 @@ import com.baeldung.spring.web.config.ApplicationConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = {ApplicationConfig.class}) +@ContextConfiguration(classes = { ApplicationConfig.class }) public class GreetControllerIntegrationTest { @Autowired @@ -35,7 +34,6 @@ public class GreetControllerIntegrationTest { private static final String CONTENT_TYPE = "application/json"; - @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); @@ -74,8 +72,8 @@ public class GreetControllerIntegrationTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java similarity index 77% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java index 0fd71a46dd..eacd256438 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java @@ -1,17 +1,19 @@ package com.baeldung.web.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -public class GreetControllerTest { +public class GreetControllerUnitTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json"; @@ -43,19 +45,17 @@ public class GreetControllerTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); } @Test public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) - .andExpect(jsonPath("$.message").value("Hello World!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); } } diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml new file mode 100644 index 0000000000..1a72549e70 --- /dev/null +++ b/spring-mvc-tiles/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + com.baeldung + spring-mvc-tiles + 0.0.1-SNAPSHOT + war + spring-mvc-tiles + Integrating Spring MVC with Apache Tiles + + + 4.3.2.RELEASE + 3.0.5 + + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.tiles + tiles-jsp + ${apachetiles.version} + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-mvc-tiles + false + + + + + spring-mvc-tiles + + diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java new file mode 100644 index 0000000000..d2e90a4f53 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java @@ -0,0 +1,47 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") +public class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java new file mode 100644 index 0000000000..1a348d1c26 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java @@ -0,0 +1,26 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class ApplicationController { + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java new file mode 100644 index 0000000000..79583dbe83 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java @@ -0,0 +1,22 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { ApplicationConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp new file mode 100644 index 0000000000..9936957c04 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

Tiles with Spring MVC Demo

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp new file mode 100644 index 0000000000..b501d4968e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

Welcome to Apache Tiles integration with Spring MVC

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp new file mode 100644 index 0000000000..209b1004de --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

Spring MVC configured to work with Apache Tiles

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp new file mode 100644 index 0000000000..2370ad4ab1 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
+ + +
+ +
+ +
+ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp new file mode 100644 index 0000000000..3849cc5230 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -0,0 +1,2 @@ + +
copyright © Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp new file mode 100644 index 0000000000..8a878c857d --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -0,0 +1,3 @@ +
+

Welcome to Spring MVC integration with Apache Tiles

+
\ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp new file mode 100644 index 0000000000..2c91eace85 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -0,0 +1,8 @@ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml new file mode 100644 index 0000000000..789fbd809a --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-tiles/src/main/webapp/static/css/app.css new file mode 100644 index 0000000000..9976e5406e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/static/css/app.css @@ -0,0 +1,36 @@ +.flex-container { + display: -webkit-flex; + display: flex; + -webkit-flex-flow: row wrap; + flex-flow: row wrap; + text-align: center; +} + +.flex-container > * { + padding: 15px; + -webkit-flex: 1 100%; + flex: 1 100%; +} + +.article { + text-align: left; +} + +header {background: black;color:white;} +footer {background: #aaa;color:white;} +.nav {background:#eee;} + +.nav ul { + list-style-type: none; + padding: 0; +} + +.nav ul a { + text-decoration: none; +} + +@media all and (min-width: 768px) { + .nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;} + .article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;} + footer {-webkit-order:3;order:3;} +} \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index 679a455f3f..10b54e345c 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -17,13 +17,12 @@ public class MainController { @Autowired private ITutorialsService tutService; - @RequestMapping(value ="/", method = RequestMethod.GET) + @RequestMapping(value = "/", method = RequestMethod.GET) public String welcomePage() { - return "index"; + return "index"; } - - - @RequestMapping(value ="/list", method = RequestMethod.GET) + + @RequestMapping(value = "/list", method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); @@ -37,6 +36,5 @@ public class MainController { public void setTutService(ITutorialsService tutService) { this.tutService = tutService; } - - + } \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java index 24059f2662..237b603590 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java @@ -6,5 +6,5 @@ import java.util.List; public interface ITutorialsService { - List listTutorials(); + List listTutorials(); } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java index f67cc0824f..9d48e130c8 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java @@ -10,9 +10,6 @@ import java.util.List; public class TutorialsService implements ITutorialsService { public List listTutorials() { - return Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); + return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")); } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java index ce8ce1919a..17388b52b0 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"}) +@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java index a9fb242755..1f90b0fc67 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java @@ -38,7 +38,6 @@ public class DataContentControllerTest { @Before public void setUp() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @@ -53,9 +52,9 @@ public class DataContentControllerTest { mockMvc.perform(get("/list")).andExpect(xpath("//table").exists()); mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists()); } - + @Test - public void whenCallingIndex_thenViewOK() throws Exception{ + public void whenCallingIndex_thenViewOK() throws Exception { mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0)); } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java index 8b84bcdd23..a75cd1291a 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java @@ -8,7 +8,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration public class TestConfig { - @Bean public ViewResolver viewResolver() { @@ -19,14 +18,12 @@ public class TestConfig { bean.setSuffix(".vm"); return bean; } - + @Bean public VelocityConfigurer velocityConfig() { VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setResourceLoaderPath("/"); return velocityConfigurer; } - - } diff --git a/spring-mvc-web-vs-initializer/.gitignore b/spring-mvc-web-vs-initializer/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-web-vs-initializer/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/README.MD b/spring-mvc-web-vs-initializer/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-mvc-web-vs-initializer/README.MD @@ -0,0 +1 @@ + diff --git a/spring-mvc-web-vs-initializer/pom.xml b/spring-mvc-web-vs-initializer/pom.xml new file mode 100644 index 0000000000..0d735e7188 --- /dev/null +++ b/spring-mvc-web-vs-initializer/pom.xml @@ -0,0 +1,201 @@ + + 4.0.0 + com.baeldung + spring-mvc-web-vs-initializer + 0.1-SNAPSHOT + + spring-mvc-web-vs-initializer + war + + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-context + + + + + + 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 + + + + + + org.springframework + spring-test + test + + + + junit + junit + test + + + + org.assertj + assertj-core + 3.5.1 + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.easymock + easymock + 3.4 + test + + + + + + + + + + org.springframework + spring-framework-bom + ${org.springframework.version} + pom + import + + + + org.springframework + spring-core + ${org.springframework.version} + + + + + + + + spring-mvc-web-vs-initializer + + + src/main/resources + true + + + + + + + + 4.3.1.RELEASE + 4.0.4.RELEASE + 3.20.0-GA + 1.2 + + + 4.3.11.Final + 5.1.38 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + + + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..21e33820ca --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java @@ -0,0 +1,26 @@ +package org.baeldung.config; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("org.baeldung.config"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("java-servlet", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/java-servlet/*"); + } + +} diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..d460113458 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,25 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.baeldung.controller.java") +public class MvcConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + + return viewResolver; + } + +} diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java new file mode 100644 index 0000000000..c979c88b34 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java @@ -0,0 +1,18 @@ +package org.baeldung.controller.java; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class JavaController { + + @RequestMapping(value = "/endpoint") + public ModelAndView handleRequestFromJavaConfiguredServlet() { + ModelAndView mv = new ModelAndView(); + mv.setViewName("from-java"); + + return mv; + } + +} \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java new file mode 100644 index 0000000000..bdefc1781c --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java @@ -0,0 +1,18 @@ +package org.baeldung.controller.xml; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class XmlController { + + @RequestMapping(value = "/endpoint") + public ModelAndView handleRequestFromXmlConfiguredServlet() { + ModelAndView mv = new ModelAndView(); + mv.setViewName("from-xml"); + + return mv; + } + +} \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml b/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp new file mode 100644 index 0000000000..e54d7520dc --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp @@ -0,0 +1,7 @@ + + + + +

Java

+ + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp new file mode 100644 index 0000000000..986010c183 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp @@ -0,0 +1,7 @@ + + + + +

XML

+ + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..9bebc263be --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + xml-servlet + + org.springframework.web.servlet.DispatcherServlet + + 1 + + contextConfigLocation + classpath*:mvc-configuration.xml + + + + + xml-servlet + /xml-servlet/* + + + diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java new file mode 100644 index 0000000000..99b5ef8c2f --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java @@ -0,0 +1,45 @@ +package org.baeldung.controller; + +import org.baeldung.config.MvcConfig; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +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(loader=AnnotationConfigWebContextLoader.class, classes = MvcConfig.class) +public class JavaServletTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void testJavaEndpoint() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/endpoint")) + .andReturn() + .getModelAndView(); + + // validate view name + Assert.assertSame(mv.getViewName(), "from-java"); + } + +} diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java new file mode 100644 index 0000000000..e7695e36c0 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java @@ -0,0 +1,44 @@ +package org.baeldung.controller; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.GenericXmlWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +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(loader=GenericXmlWebContextLoader.class, locations = "classpath*:mvc-configuration.xml") +public class XmlServletTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void testXmlEndpoint() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/endpoint")) + .andReturn() + .getModelAndView(); + + // validate view name + Assert.assertSame(mv.getViewName(), "from-xml"); + } + +} diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 9c65ccdadd..849699cfae 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung 0.1-SNAPSHOT @@ -99,16 +100,11 @@
- - com.fasterxml.jackson.core - jackson-core - 2.7.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.7.2 - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + @@ -165,6 +161,7 @@ 4.2.5.RELEASE + 2.7.8 1.7.13 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 76351b96f7..b5238b04d5 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index bee09b742a..f299c46dbc 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - @Bean - public MessageSource messageSource() { + @Bean + public MessageSource messageSource() { - final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); - ms.setBasenames("messages"); - return ms; - } + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - @Bean - public ResourceBundle getBeanResourceBundle() { + @Bean + public ResourceBundle getBeanResourceBundle() { - final Locale locale = Locale.getDefault(); - return new MessageSourceResourceBundle(messageSource(), locale); - } + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); - return bean; - } + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index aa25f47a2a..fa76933f8f 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee; @Controller public class EmployeeController { - Map employeeMap = new HashMap<>(); + Map employeeMap = new HashMap<>(); - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } - @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - employeeMap.put(employee.getId(), employee); - return "employeeView"; - } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index cc9d66d4d4..17f0801a6e 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -11,8 +11,7 @@ public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java index 614888ae42..c7f3adb594 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using ControllerClassNameHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using ControllerClassNameHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java index 6ed3d06ab7..a0be507125 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using BeanNameUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using BeanNameUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java index 39dabf86ed..71d9ad7845 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java @@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PersonController { - @Autowired - PersonValidator validator; + @Autowired + PersonValidator validator; - @RequestMapping(value = "/person", method = RequestMethod.GET) - public ModelAndView showForm(final Model model) { + @RequestMapping(value = "/person", method = RequestMethod.GET) + public ModelAndView showForm(final Model model) { - initData(model); - return new ModelAndView("personForm", "person", new Person()); - } + initData(model); + return new ModelAndView("personForm", "person", new Person()); + } - @RequestMapping(value = "/addPerson", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, - final ModelMap modelMap, final Model model) { + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) { - validator.validate(person, result); + validator.validate(person, result); - if (result.hasErrors()) { + if (result.hasErrors()) { - initData(model); - return "personForm"; - } + initData(model); + return "personForm"; + } - modelMap.addAttribute("person", person); + modelMap.addAttribute("person", person); - return "personView"; - } + return "personView"; + } - private void initData(final Model model) { + private void initData(final Model model) { - final List favouriteLanguageItem = new ArrayList(); - favouriteLanguageItem.add("Java"); - favouriteLanguageItem.add("C++"); - favouriteLanguageItem.add("Perl"); - model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); + final List favouriteLanguageItem = new ArrayList(); + favouriteLanguageItem.add("Java"); + favouriteLanguageItem.add("C++"); + favouriteLanguageItem.add("Perl"); + model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); - final List jobItem = new ArrayList(); - jobItem.add("Full time"); - jobItem.add("Part time"); - model.addAttribute("jobItem", jobItem); + final List jobItem = new ArrayList(); + jobItem.add("Full time"); + jobItem.add("Part time"); + model.addAttribute("jobItem", jobItem); - final Map countryItems = new LinkedHashMap(); - countryItems.put("US", "United Stated"); - countryItems.put("IT", "Italy"); - countryItems.put("UK", "United Kingdom"); - countryItems.put("FR", "Grance"); - model.addAttribute("countryItems", countryItems); + final Map countryItems = new LinkedHashMap(); + countryItems.put("US", "United Stated"); + countryItems.put("IT", "Italy"); + countryItems.put("UK", "United Kingdom"); + countryItems.put("FR", "Grance"); + model.addAttribute("countryItems", countryItems); - final List fruit = new ArrayList(); - fruit.add("Banana"); - fruit.add("Mango"); - fruit.add("Apple"); - model.addAttribute("fruit", fruit); + final List fruit = new ArrayList(); + fruit.add("Banana"); + fruit.add("Mango"); + fruit.add("Apple"); + model.addAttribute("fruit", fruit); - final List books = new ArrayList(); - books.add("The Great Gatsby"); - books.add("Nineteen Eighty-Four"); - books.add("The Lord of the Rings"); - model.addAttribute("books", books); - } + final List books = new ArrayList(); + books.add("The Great Gatsby"); + books.add("Nineteen Eighty-Four"); + books.add("The Lord of the Rings"); + model.addAttribute("books", books); + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java index 5459481674..2760fb8f89 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -11,8 +11,7 @@ public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); - model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java index 88e4f9ff4c..01638fbe76 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java @@ -7,146 +7,146 @@ import org.springframework.web.multipart.MultipartFile; public class Person { - private long id; + private long id; - private String name; - private String email; - private String dateOfBirth; + private String name; + private String email; + private String dateOfBirth; - @NotEmpty - private String password; - private String sex; - private String country; - private String book; - private String job; - private boolean receiveNewsletter; - private String[] hobbies; - private List favouriteLanguage; - private List fruit; - private String notes; - private MultipartFile file; + @NotEmpty + private String password; + private String sex; + private String country; + private String book; + private String job; + private boolean receiveNewsletter; + private String[] hobbies; + private List favouriteLanguage; + private List fruit; + private String notes; + private MultipartFile file; - public Person() { - super(); - } + public Person() { + super(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - 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; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(final String email) { - this.email = email; - } + public void setEmail(final String email) { + this.email = email; + } - public String getDateOfBirth() { - return dateOfBirth; - } + public String getDateOfBirth() { + return dateOfBirth; + } - public void setDateOfBirth(final String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } + public void setDateOfBirth(final String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(final String password) { - this.password = password; - } + public void setPassword(final String password) { + this.password = password; + } - public String getSex() { - return sex; - } + public String getSex() { + return sex; + } - public void setSex(final String sex) { - this.sex = sex; - } + public void setSex(final String sex) { + this.sex = sex; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(final String country) { - this.country = country; - } + public void setCountry(final String country) { + this.country = country; + } - public String getJob() { - return job; - } + public String getJob() { + return job; + } - public void setJob(final String job) { - this.job = job; - } + public void setJob(final String job) { + this.job = job; + } - public boolean isReceiveNewsletter() { - return receiveNewsletter; - } + public boolean isReceiveNewsletter() { + return receiveNewsletter; + } - public void setReceiveNewsletter(final boolean receiveNewsletter) { - this.receiveNewsletter = receiveNewsletter; - } + public void setReceiveNewsletter(final boolean receiveNewsletter) { + this.receiveNewsletter = receiveNewsletter; + } - public String[] getHobbies() { - return hobbies; - } + public String[] getHobbies() { + return hobbies; + } - public void setHobbies(final String[] hobbies) { - this.hobbies = hobbies; - } + public void setHobbies(final String[] hobbies) { + this.hobbies = hobbies; + } - public List getFavouriteLanguage() { - return favouriteLanguage; - } + public List getFavouriteLanguage() { + return favouriteLanguage; + } - public void setFavouriteLanguage(final List favouriteLanguage) { - this.favouriteLanguage = favouriteLanguage; - } + public void setFavouriteLanguage(final List favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } - public String getNotes() { - return notes; - } + public String getNotes() { + return notes; + } - public void setNotes(final String notes) { - this.notes = notes; - } + public void setNotes(final String notes) { + this.notes = notes; + } - public List getFruit() { - return fruit; - } + public List getFruit() { + return fruit; + } - public void setFruit(final List fruit) { - this.fruit = fruit; - } + public void setFruit(final List fruit) { + this.fruit = fruit; + } - public String getBook() { - return book; - } + public String getBook() { + return book; + } - public void setBook(final String book) { - this.book = book; - } + public void setBook(final String book) { + this.book = book; + } - public MultipartFile getFile() { - return file; - } + public MultipartFile getFile() { + return file; + } - public void setFile(final MultipartFile file) { - this.file = file; - } + public void setFile(final MultipartFile file) { + this.file = file; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java index 3a271f6545..f7625bacd9 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java @@ -9,14 +9,14 @@ import org.springframework.validation.Validator; @Component public class PersonValidator implements Validator { - @Override - public boolean supports(final Class calzz) { - return Person.class.isAssignableFrom(calzz); - } + @Override + public boolean supports(final Class calzz) { + return Person.class.isAssignableFrom(calzz); + } - @Override - public void validate(final Object obj, final Errors errors) { + @Override + public void validate(final Object obj, final Errors errors) { - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); - } + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); + } } \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java index e51e4ad43d..547ef78d84 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java @@ -10,7 +10,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SpringQuartzApp { public static void main(String[] args) { - new SpringApplicationBuilder(SpringQuartzApp.class) - .showBanner(false).run(args); + new SpringApplicationBuilder(SpringQuartzApp.class).showBanner(false).run(args); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index a944f8fe43..6601df6c94 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -45,8 +45,7 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) - throws SchedulerException, IOException { + public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); @@ -64,9 +63,7 @@ public class QrtzScheduler { @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class).storeDurably() - .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) - .withDescription("Invoke Sample Job service...").build(); + return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean @@ -75,10 +72,6 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) - .withDescription("Sample trigger") - .withSchedule( - simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) - .build(); + return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 9474272a3c..7c50f9a231 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -19,8 +19,7 @@ public class SampleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), - context.getFireTime()); + logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), context.getFireTime()); jobService.executeSampleJob(); diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java index 0e24238467..d3034ae7af 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java @@ -11,21 +11,17 @@ import org.springframework.scheduling.quartz.SpringBeanJobFactory; * Adds auto-wiring support to quartz jobs. * @see "https://gist.github.com/jelies/5085593" */ -public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory - implements ApplicationContextAware { +public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; - - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { beanFactory = applicationContext.getAutowireCapableBeanFactory(); } @Override - protected Object createJobInstance(final TriggerFiredBundle bundle) - throws Exception { + protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 331c9a644c..981ee9dabc 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -1,95 +1,102 @@ - - 4.0.0 - spring-rest-angular - spring-rest-angular - com.baeldung - 1.0 - war - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.data - spring-data-commons - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - - - org.springframework - spring-test - test - - - org.apache.commons - commons-lang3 - 3.3 - - - com.google.guava - guava - 19.0 - - - junit - junit - test - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - spring-mock-mvc - 3.0.0 - test - - - - angular-spring-rest-sample - + + 4.0.0 + spring-rest-angular + spring-rest-angular + com.baeldung + 1.0 + war - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + - - org.apache.maven.plugins - maven-war-plugin - - false - - + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + + + org.springframework + spring-test + test + + + org.apache.commons + commons-lang3 + 3.3 + + + com.google.guava + guava + ${guava.version} + + + junit + junit + test + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + spring-mock-mvc + 3.0.0 + test + + + + + angular-spring-rest-sample + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + + + + + 19.0 + - - diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index e28f7e7e33..18cb1dc72a 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -15,10 +15,7 @@ - - org.springframework.boot - spring-boot-starter-security - + org.springframework.boot spring-boot-starter-thymeleaf @@ -74,6 +71,11 @@ com.fasterxml.jackson.core jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.thoughtworks.xstream @@ -146,11 +148,19 @@ spring-test + + com.jayway.restassured + rest-assured + ${rest-assured.version} + + + com.google.protobuf protobuf-java 2.6.1 + com.esotericsoftware kryo @@ -172,7 +182,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -182,16 +191,14 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} - + **/*LiveTest.java @@ -206,7 +213,7 @@ true - jetty8x + tomcat8x embedded @@ -224,6 +231,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + @@ -231,10 +293,6 @@ 4.3.11.Final 5.1.39 - - - 2.7.2 - 5.2.2.Final @@ -260,7 +318,7 @@ 3.5.1 2.6 2.19.1 - 1.4.18 + 1.6.0 diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index d5cd6e1eae..d116148f09 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -15,6 +15,11 @@ import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +/* + * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml + * + */ + @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web" }) diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java index d640ac671d..aa694c08ed 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java @@ -8,9 +8,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class CompanyController { - @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) - public Company getCompanyRest() { - final Company company = new Company(1, "Xpto"); - return company; - } + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index 386c64bb09..dd1e3ca222 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -35,7 +35,6 @@ public class FooController { @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { - System.out.println(foo); return foo; } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java index cfde4b23b1..1cc3eae432 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java @@ -27,7 +27,13 @@ public class ItemController { } @RequestMapping("/date") - public Date getCurrentDate() { + public Date getCurrentDate() throws Exception { return new Date(); } + + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { + + Thread.sleep(seconds * 1000); + } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java index 7d62cc0c66..996f229128 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java index 1d4aff2ebf..458bdaf170 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java @@ -3,7 +3,8 @@ package org.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message") +@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message") public class ForbiddenException extends RuntimeException { + private static final long serialVersionUID = 6826605655586311552L; } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java index c7d0718140..3164d604ad 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java @@ -2,37 +2,37 @@ package org.baeldung.web.dto; public class Company { - private long id; - private String name; + private long id; + private String name; - public Company() { - super(); - } + public Company() { + super(); + } - public Company(final long id, final String name) { - this.id = id; - this.name = name; - } + public Company(final long id, final String name) { + this.id = id; + 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; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - @Override - public String toString() { - return "Company [id=" + id + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java index 61251ea33a..8ca96c38fc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java @@ -4,617 +4,594 @@ package org.baeldung.web.dto; public final class FooProtos { - private FooProtos() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface FooOrBuilder extends - // @@protoc_insertion_point(interface_extends:baeldung.Foo) - com.google.protobuf.MessageOrBuilder { - - /** - * required int64 id = 1; - */ - boolean hasId(); - /** - * required int64 id = 1; - */ - long getId(); - - /** - * required string name = 2; - */ - boolean hasName(); - /** - * required string name = 2; - */ - java.lang.String getName(); - /** - * required string name = 2; - */ - com.google.protobuf.ByteString - getNameBytes(); - } - /** - * Protobuf type {@code baeldung.Foo} - */ - public static final class Foo extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:baeldung.Foo) - FooOrBuilder { - // Use Foo.newBuilder() to construct. - private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final Foo defaultInstance; - public static Foo getDefaultInstance() { - return defaultInstance; + private FooProtos() { } - public Foo getDefaultInstanceForType() { - return defaultInstance; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { } - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Foo( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - bitField0_ |= 0x00000001; - id_ = input.readInt64(); - break; - } - case 18: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000002; - name_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + public interface FooOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Foo) + com.google.protobuf.MessageOrBuilder { + + /** + * required int64 id = 1; + */ + boolean hasId(); + + /** + * required int64 id = 1; + */ + long getId(); + + /** + * required string name = 2; + */ + boolean hasName(); + + /** + * required string name = 2; + */ + java.lang.String getName(); + + /** + * required string name = 2; + */ + com.google.protobuf.ByteString getNameBytes(); } - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public Foo parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Foo(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int ID_FIELD_NUMBER = 1; - private long id_; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - - public static final int NAME_FIELD_NUMBER = 2; - private java.lang.Object name_; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private void initFields() { - id_ = 0L; - name_ = ""; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (!hasId()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasName()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeInt64(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeBytes(2, getNameBytes()); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getNameBytes()); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } /** * Protobuf type {@code baeldung.Foo} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + public static final class Foo extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Foo) + FooOrBuilder { + // Use Foo.newBuilder() to construct. + private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); } - } - private static Builder create() { - return new Builder(); - } - public Builder clear() { - super.clear(); - id_ = 0L; - bitField0_ = (bitField0_ & ~0x00000001); - name_ = ""; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); - } - - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private Foo(boolean noInit) { + this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - return result; - } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + private static final Foo defaultInstance; + + public static Foo getDefaultInstance() { + return defaultInstance; } - result.id_ = id_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; + + public Foo getDefaultInstanceForType() { + return defaultInstance; } - result.name_ = name_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other); - } else { - super.mergeFrom(other); - return this; + private final com.google.protobuf.UnknownFieldSet unknownFields; + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; - if (other.hasId()) { - setId(other.getId()); + private Foo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + id_ = input.readInt64(); + break; + } + case 18: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000002; + name_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - if (other.hasName()) { - bitField0_ |= 0x00000002; - name_ = other.name_; - onChanged(); + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - public final boolean isInitialized() { - if (!hasId()) { - - return false; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); } - if (!hasName()) { - - return false; - } - return true; - } - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private long id_ ; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - /** - * required int64 id = 1; - */ - public Builder setId(long value) { - bitField0_ |= 0x00000001; - id_ = value; - onChanged(); - return this; - } - /** - * required int64 id = 1; - */ - public Builder clearId() { - bitField0_ = (bitField0_ & ~0x00000001); - id_ = 0L; - onChanged(); - return this; - } - - private java.lang.Object name_ = ""; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * required string name = 2; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000002); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - - // @@protoc_insertion_point(builder_scope:baeldung.Foo) - } - - static { - defaultInstance = new Foo(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:baeldung.Foo) - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_baeldung_Foo_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_baeldung_Foo_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + - "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + - ".dtoB\tFooProtos" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } + public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Foo(input, extensionRegistry); + } }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_baeldung_Foo_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_baeldung_Foo_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_baeldung_Foo_descriptor, - new java.lang.String[] { "Id", "Name", }); - } - // @@protoc_insertion_point(outer_class_scope) + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + id_ = 0L; + name_ = ""; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + if (!hasId()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt64(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getNameBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) + return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + @java.lang.Override + protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { + return Builder.create(); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + return newBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return newBuilder(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Foo} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Foo) + org.baeldung.web.dto.FooProtos.FooOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + id_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + } + + public org.baeldung.web.dto.FooProtos.Foo build() { + org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.baeldung.web.dto.FooProtos.Foo buildPartial() { + org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { + if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + return this; + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasName()) { + bitField0_ |= 0x00000002; + name_ = other.name_; + onChanged(); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasId()) { + + return false; + } + if (!hasName()) { + + return false; + } + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + /** + * required int64 id = 1; + */ + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + + /** + * required int64 id = 1; + */ + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * required string name = 2; + */ + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder setNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Foo) + } + + static { + defaultInstance = new Foo(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:baeldung.Foo) + } + + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor; + private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { + java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + ".dtoB\tFooProtos" }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", }); + } + + // @@protoc_insertion_point(outer_class_scope) } diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 5afc637ece..21136b62c6 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -8,7 +8,24 @@ - + + + + + + + + + + + diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index 01e7620c44..a439de8a05 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -8,7 +8,7 @@ Spring MVC Application - + contextClass org.springframework.web.context.support.AnnotationConfigWebApplicationContext @@ -18,7 +18,7 @@ contextConfigLocation org.baeldung.config - + org.springframework.web.context.ContextLoaderListener diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java index 1344d2d40e..c50e1b4f43 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java @@ -32,13 +32,11 @@ public class ExampleControllerTest { @Test public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception { - mockMvc.perform(get("/controller")) - .andExpect(status().isNotAcceptable()); + mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable()); } @Test public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception { - mockMvc.perform(get("/exception")) - .andExpect(status().isForbidden()); + mockMvc.perform(get("/exception")).andExpect(status().isForbidden()); } } diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java new file mode 100644 index 0000000000..3155b5cda9 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java @@ -0,0 +1,62 @@ +package org.baeldung.web.test; + +import static org.hamcrest.Matchers.equalTo; + +import org.junit.Test; + +import com.jayway.restassured.RestAssured; + +public class RequestMappingLiveTest { + private static String BASE_URI = "http://localhost:8082/spring-rest/ex/"; + + @Test + public void givenSimplePath_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos").then().assertThat().body(equalTo("Simple Get some Foos")); + } + + @Test + public void whenPostFoos_thenOk() { + RestAssured.given().accept("text/html").post(BASE_URI + "foos").then().assertThat().body(equalTo("Post some Foos")); + } + + @Test + public void givenOneHeader_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").header("key", "val").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header")); + } + + @Test + public void givenMultipleHeaders_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").headers("key1", "val1", "key2", "val2").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header")); + } + + @Test + public void givenAcceptHeader_whenGetFoos_thenOk() { + RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New")); + } + + @Test + public void givenPathVariable_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos/1").then().assertThat().body(equalTo("Get a specific Foo with id=1")); + } + + @Test + public void givenMultiplePathVariable_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos/1/bar/2").then().assertThat().body(equalTo("Get a specific Bar with id=2 from a Foo with id=1")); + } + + @Test + public void givenPathVariable_whenGetBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "bars/1").then().assertThat().body(equalTo("Get a specific Bar with id=1")); + } + + @Test + public void givenParams_whenGetBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "bars?id=100&second=something").then().assertThat().body(equalTo("Get a specific Bar with id=100")); + } + + @Test + public void whenGetFoosOrBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "advanced/foos").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars")); + RestAssured.given().accept("text/html").get(BASE_URI + "advanced/bars").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars")); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java similarity index 78% rename from spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java rename to spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java index 1536f14bc8..7f250653ab 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java @@ -3,9 +3,7 @@ package org.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import org.baeldung.config.converter.KryoHttpMessageConverter; import org.baeldung.web.dto.Foo; @@ -17,19 +15,15 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; -import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; -import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.client.RestTemplate; /** * Integration Test class. Tests methods hits the server's rest services. */ -public class SpringHttpMessageConvertersIntegrationTestsCase { +public class SpringHttpMessageConvertersLiveTest { - private static String BASE_URI = "http://localhost:8080/spring-rest/"; + private static String BASE_URI = "http://localhost:8082/spring-rest/"; /** * Without specifying Accept Header, uses the default response from the @@ -50,7 +44,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); @@ -67,7 +60,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @@ -83,7 +75,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { public void givenConsumingXml_whenWritingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final Foo resource = new Foo(4, "jason"); final HttpHeaders headers = new HttpHeaders(); @@ -129,20 +120,4 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { assertThat(resource, notNullValue()); } - // UTIL - - private List> getMessageConverters() { - final List> converters = new ArrayList>(); - - final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); - xmlConverter.setMarshaller(xstreamMarshaller); - xmlConverter.setUnmarshaller(xstreamMarshaller); - - converters.add(xmlConverter); - converters.add(new MappingJackson2HttpMessageConverter()); - - return converters; - } - } diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6f460f1751..b2854fe7c5 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -55,7 +55,12 @@ - + + org.springframework.boot + spring-boot-starter-test + test + + junit junit @@ -95,13 +100,54 @@ org.springframework.boot spring-boot-maven-plugin
+ + + maven-surefire-plugin + + ${unit-tests.skip} + + **/*LiveTest.java + + + + + + maven-failsafe-plugin + + + integration-test + + integration-test + + + ${live-tests.skip} + + **/*LiveTest.class + + + + + + + + + live + + false + false + + + + UTF-8 1.8 2.4.0 + false + true diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties index 0b40f62fa9..4433a53ac7 100644 --- a/spring-security-custom-permission/src/main/resources/application.properties +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8081 spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1 +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java index 80b1390083..7e92765dcd 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -3,35 +3,45 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import org.baeldung.Application; import org.baeldung.persistence.model.Foo; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.RestAssured; import com.jayway.restassured.authentication.FormAuthConfig; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest("server.port:8082") public class LiveTest { - private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8081/login", "username", "password"); + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/login", "username", "password"); @Test public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { - final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); assertEquals(403, response.getStatusCode()); } @Test public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { - final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); assertEquals(201, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @@ -40,14 +50,14 @@ public class LiveTest { @Test public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/2"); assertEquals(403, response.getStatusCode()); } @@ -55,7 +65,7 @@ public class LiveTest { @Test public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample"); assertEquals(500, response.getStatusCode()); assertTrue(response.asString().contains("method hasAuthority() not allowed")); } diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index 2baf88a62d..e6c77110b3 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -1,11 +1,5 @@ package org.baeldung.service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.baeldung.security.SecurityRole; @@ -17,9 +11,9 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -/** - * User Details Service - hard coded to two users for the example. - */ +import java.util.*; +import java.util.stream.Collectors; + @Service public class MyUserDetailsService implements UserDetailsService { @@ -28,24 +22,19 @@ public class MyUserDetailsService implements UserDetailsService { private final Map availableUsers = new HashMap(); public MyUserDetailsService() { - populateDemoUsers(); - } - // - @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { - throw new UsernameNotFoundException("Username not found"); - } else { - return availableUsers.get(username); + throw new UsernameNotFoundException(username); } + return user; } /** @@ -59,24 +48,11 @@ public class MyUserDetailsService implements UserDetailsService { availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } - /** - * Create a demo User. - * - * @param username - * Username - * @param password - * Password - * @param roles - * Role names user is assigned to - * @return User - */ private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = new ArrayList(); - for (final SecurityRole role : roles) { - authorities.add(new SimpleGrantedAuthority(role.toString())); - } + final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); + return new User(username, password, true, true, true, true, authorities); } } diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 854bbb70be..d3f4de9914 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -285,6 +285,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index f369e96ca9..0cec0dc5c3 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -45,7 +45,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java index 817e818b58..2a668f827a 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java @@ -33,7 +33,7 @@ public class ClientLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); + final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); assertThat(responseEntity.getStatusCode().value(), is(200)); } diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java index 44c5c0cbb1..c27e306c08 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java @@ -30,7 +30,7 @@ import org.springframework.web.client.RestTemplate; * */ public class RestClientLiveManualTest { - final String urlOverHttps = "http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"; + final String urlOverHttps = "http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"; // tests diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 67d9abbae5..616c2a7684 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:on } - } diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index bfb4a7223a..1880e12a74 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -278,6 +278,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE @@ -296,7 +351,7 @@ 1.1.3 - 2.7.2 + 2.7.8 5.2.2.Final diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java index 245d5d0a41..cbf6a12ff7 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java @@ -22,16 +22,16 @@ public class ClientNoSpringLiveTest { @Test public final void givenUsingCustomHttpRequestFactory_whenSecuredRestApiIsConsumed_then200OK() { - final HttpHost host = new HttpHost("localhost", 8080, "http"); + final HttpHost host = new HttpHost("localhost", 8082, "http"); final CredentialsProvider credentialsProvider = provider(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).useSystemProperties().build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client); final RestTemplate restTemplate = new RestTemplate(requestFactory); - // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + // credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); @@ -46,7 +46,7 @@ public class ClientNoSpringLiveTest { // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java index b40f9ef472..d673b2633b 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java @@ -23,7 +23,7 @@ public class ClientWithSpringLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java index 93c3af3876..83e888e793 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java @@ -29,7 +29,7 @@ public class RawClientLiveTest { final int timeout = 20; // seconds final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout).setSocketTimeout(timeout).build(); - final HttpGet getMethod = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"); + final HttpGet getMethod = new HttpGet("http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"); getMethod.setConfig(requestConfig); final int hardTimeout = 5; // seconds diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 77b11f1cb1..dff9f7ed4f 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -439,7 +439,7 @@ 3.6.2 - 2.7.2 + 2.7.8 1.4.01 diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java new file mode 100644 index 0000000000..3d727fc19f --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.spring; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.request.RequestContextListener; + +public class ListenerConfig implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } +} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index fa8bdddb4e..efdb2bc8d4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -1,6 +1,7 @@ package org.baeldung.spring; import org.baeldung.web.interceptor.LoggerInterceptor; +import org.baeldung.web.interceptor.SessionTimerInterceptor; import org.baeldung.web.interceptor.UserInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -38,9 +39,11 @@ public class WebConfig extends WebMvcConfigurerAdapter { registry.addViewController("/homepage.html"); } - @Override - public void addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - registry.addInterceptor(new UserInterceptor()); - } + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); + } + } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java new file mode 100644 index 0000000000..90199347b4 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -0,0 +1,53 @@ +package org.baeldung.web.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimerInterceptor extends HandlerInterceptorAdapter { + + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); + + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; + + @Autowired + private HttpSession session; + + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("Pre handle method - check handling start time"); + long startTime = System.currentTimeMillis(); + request.setAttribute("executionTime", startTime); + if (UserInterceptor.isUserLogged()) { + session = request.getSession(); + log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession().getLastAccessedTime()); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + request.logout(); + response.sendRedirect("/spring-security-rest-full/logout"); + } + } + return true; + } + + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView model) throws Exception { + log.info("Post handle method - check execution time of handling"); + long startTime = (Long) request.getAttribute("executionTime"); + log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java index 4ba12d0138..6b808d885e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java @@ -31,8 +31,7 @@ public class UserInterceptor extends HandlerInterceptorAdapter { * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle **/ @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) - throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception { if (model != null && !isRedirectView(model)) { if (isUserLogged()) { addToModelUserDetails(model); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 1b5f7cd894..13cb92a745 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -14,6 +14,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.core.JsonProcessingException; @@ -21,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration +@Transactional public class CsrfAbstractIntegrationTest { @Autowired diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java new file mode 100644 index 0000000000..916a849c63 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java @@ -0,0 +1,55 @@ +package org.baeldung.web.interceptor; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.http.HttpSession; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) +public class SessionTimerInterceptorTest { + + @Autowired + WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn().getRequest().getSession(); + Thread.sleep(51000); + mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); + } + +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java index 0b65311203..ff40c86906 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java @@ -23,8 +23,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -@ContextConfiguration(classes = {SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class}) -@WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class UserInterceptorTest { @Autowired @@ -46,8 +46,7 @@ public class UserInterceptorTest { */ @Test public void testInterceptors() throws Exception { - mockMvc.perform(get("/auth/admin")) - .andExpect(status().is2xxSuccessful()); + mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()); } } diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 6d492863b4..60f3ed41d1 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -109,7 +109,6 @@ - com.fasterxml.jackson.core jackson-databind @@ -117,7 +116,6 @@ - com.google.guava guava @@ -128,8 +126,8 @@ commons-lang3 ${commons-lang3.version} + - org.slf4j slf4j-api @@ -257,7 +255,7 @@ ${maven-surefire-plugin.version} - + **/*LiveTest.java @@ -289,6 +287,62 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + 4.2.5.RELEASE @@ -308,7 +362,7 @@ 3.0.1 1.1.0.Final 1.2 - 2.2.2 + 2.7.8 19.0 diff --git a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java index dc3a576b7b..0ef50f745a 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java @@ -17,14 +17,16 @@ import com.jayway.restassured.specification.RequestSpecification; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest"; // private FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "temporary", "temporary"); private String cookie; + private RequestSpecification givenAuth() { // return RestAssured.given().auth().form("user", "userPass", formConfig); - if (cookie == null) + if (cookie == null) { cookie = RestAssured.given().contentType("application/x-www-form-urlencoded").formParam("password", "userPass").formParam("username", "user").post(URL_PREFIX + "/login").getCookie("JSESSIONID"); + } return RestAssured.given().cookie("JSESSIONID", cookie); } diff --git a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java index 792b3e28ce..cf1516f8e1 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java @@ -8,7 +8,7 @@ import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; public class SwaggerLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest/api"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest/api"; @Test public void whenVerifySpringFoxIsWorking_thenOK() { diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 51e26fdfdd..a13f1de4c7 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,59 +5,69 @@ spring-thymeleaf 0.1-SNAPSHOT war - - 1.7 - - 4.1.8.RELEASE - 3.0.1 - + + 1.8 + + 4.3.3.RELEASE + 3.0.1 + 1.7.12 1.1.3 - - 2.1.4.RELEASE - - 1.1.0.Final - 5.1.2.Final - - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 - - - - - - org.springframework - spring-context - ${org.springframework-version} - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - ${org.springframework-version} - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - + + 3.0.1.RELEASE + + 1.1.0.Final + 5.1.2.Final + + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + + + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.springframework.security + spring-security-web + 4.1.3.RELEASE + + + org.springframework.security + spring-security-config + 4.1.3.RELEASE + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + org.slf4j slf4j-api @@ -80,55 +90,81 @@ log4j-over-slf4j ${org.slf4j.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-version} - provided - - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${org.hibernate-version} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-version} - ${java-version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + + + + org.springframework + spring-test + 4.1.3.RELEASE + test + + + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + + + + + junit + junit + 4.12 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + org.codehaus.cargo cargo-maven2-plugin @@ -148,6 +184,7 @@ - - + + + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java new file mode 100644 index 0000000000..956db4a0e5 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class InitSecurity extends AbstractSecurityWebApplicationInitializer { + + public InitSecurity() { + super(WebMVCSecurity.class); + + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java index 89ad7e601e..3104f45ab5 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java @@ -9,28 +9,28 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche */ public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { - public WebApp() { - super(); - } + public WebApp() { + super(); + } - @Override - protected Class[] getRootConfigClasses() { - return null; - } + @Override + protected Class[] getRootConfigClasses() { + return null; + } - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { WebMVCConfig.class }; - } + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }; + } - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } - @Override - protected void customizeRegistration(final Dynamic registration) { - super.customizeRegistration(registration); - } + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 51c60247a1..444b780673 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -1,18 +1,27 @@ package com.baeldung.thymeleaf.config; -import com.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.TemplateEngine; import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import com.baeldung.thymeleaf.formatter.NameFormatter; +import com.baeldung.thymeleaf.utils.ArrayUtil; + @Configuration @EnableWebMvc @@ -21,36 +30,76 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; * Java configuration file that is used for Spring MVC and Thymeleaf * configurations */ -public class WebMVCConfig extends WebMvcConfigurerAdapter { +public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { - @Bean - @Description("Thymeleaf Template Resolver") - public ServletContextTemplateResolver templateResolver() { - ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/views/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); + private ApplicationContext applicationContext; - return templateResolver; + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; } @Bean - @Description("Thymeleaf Template Engine") - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - - return templateEngine; + public ViewResolver htmlViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); + resolver.setContentType("text/html"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.html")); + return resolver; } - + @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + public ViewResolver javascriptViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver())); + resolver.setContentType("application/javascript"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.js")); + return resolver; + } + + @Bean + public ViewResolver plainViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(plainTemplateResolver())); + resolver.setContentType("text/plain"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.txt")); + return resolver; + } + + private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setTemplateResolver(templateResolver); + return engine; + } + + private ITemplateResolver htmlTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } + + private ITemplateResolver javascriptTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/js/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.JAVASCRIPT); + return resolver; + } + + private ITemplateResolver plainTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/txt/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.TEXT); + return resolver; + } @Bean @Description("Spring Message Resolver") diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java new file mode 100644 index 0000000000..37844a2976 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -0,0 +1,49 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) +public class WebMVCSecurity extends WebSecurityConfigurerAdapter { + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + public WebMVCSecurity() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER"); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .httpBasic() + ; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java new file mode 100644 index 0000000000..f30b9b2078 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java @@ -0,0 +1,33 @@ +package com.baeldung.thymeleaf.controller; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Controller to test expression utility objects: dates, + * + */ +@Controller +public class ExpressionUtilityObjectsController { + + @RequestMapping(value = "/objects", method = RequestMethod.GET) + public String getDates(Model model) { + model.addAttribute("date", new Date()); + model.addAttribute("calendar", Calendar.getInstance()); + model.addAttribute("num", Math.random() * 10); + model.addAttribute("string", "new text"); + model.addAttribute("emptyString", ""); + model.addAttribute("nullString", null); + model.addAttribute("array", new int[] { 1, 3, 4, 5 }); + model.addAttribute("set", new HashSet(Arrays.asList(1, 3, 8))); + return "objects.html"; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index a28d059acc..f1a394cac4 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -21,7 +21,7 @@ public class HomeController { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); model.addAttribute("serverTime", dateFormat.format(new Date())); - return "home"; + return "home.html"; } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java new file mode 100644 index 0000000000..9e3f14ac8e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java @@ -0,0 +1,33 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.thymeleaf.utils.StudentUtils; + +@Controller +public class InliningController { + + @RequestMapping(value = "/html", method = RequestMethod.GET) + public String getExampleHTML(Model model) { + model.addAttribute("title", "Baeldung"); + model.addAttribute("description", "Thymeleaf tutorial"); + return "inliningExample.html"; + } + + @RequestMapping(value = "/js", method = RequestMethod.GET) + public String getExampleJS(Model model) { + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentCheck.js"; + } + + @RequestMapping(value = "/plain", method = RequestMethod.GET) + public String getExamplePlain(Model model) { + model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName()); + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentsList.txt"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 912eb521f4..1f40046caa 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,11 +1,9 @@ package com.baeldung.thymeleaf.controller; -import java.util.ArrayList; import java.util.List; import javax.validation.Valid; -import com.baeldung.thymeleaf.model.Student; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -13,6 +11,9 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.thymeleaf.model.Student; +import com.baeldung.thymeleaf.utils.StudentUtils; + /** * Handles requests for the student model. * @@ -24,46 +25,26 @@ public class StudentController { public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { if (!errors.hasErrors()) { // get mock objects - List students = buildStudents(); + List students = StudentUtils.buildStudents(); // add current student students.add(student); model.addAttribute("students", students); } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html"); } @RequestMapping(value = "/addStudent", method = RequestMethod.GET) public String addStudent(Model model) { model.addAttribute("student", new Student()); - return "addStudent"; + return "addStudent.html"; } @RequestMapping(value = "/listStudents", method = RequestMethod.GET) public String listStudent(Model model) { - model.addAttribute("students", buildStudents()); + model.addAttribute("students", StudentUtils.buildStudents()); - return "listStudents"; + return "listStudents.html"; } - private List buildStudents() { - List students = new ArrayList(); - - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); - - students.add(student1); - - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); - - students.add(student2); - return students; - } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java index bce99f286c..202c04358a 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java @@ -12,49 +12,49 @@ import javax.validation.constraints.NotNull; */ public class Student implements Serializable { - private static final long serialVersionUID = -8582553475226281591L; + private static final long serialVersionUID = -8582553475226281591L; - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be at least 4 digits.") - private Integer id; + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") + private Integer id; - @NotNull(message = "Student name is required.") - private String name; + @NotNull(message = "Student name is required.") + private String name; - @NotNull(message = "Student gender is required.") - private Character gender; + @NotNull(message = "Student gender is required.") + private Character gender; - private Float percentage; + private Float percentage; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Character getGender() { - return gender; - } + public Character getGender() { + return gender; + } - public void setGender(Character gender) { - this.gender = gender; - } + public void setGender(Character gender) { + this.gender = gender; + } - public Float getPercentage() { - return percentage; - } + public Float getPercentage() { + return percentage; + } - public void setPercentage(Float percentage) { - this.percentage = percentage; - } + public void setPercentage(Float percentage) { + this.percentage = percentage; + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java new file mode 100644 index 0000000000..d85c70c1b7 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java @@ -0,0 +1,8 @@ +package com.baeldung.thymeleaf.utils; + +public class ArrayUtil { + + public static String[] array(String... args) { + return args; + } +} \ No newline at end of file diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java new file mode 100644 index 0000000000..f7ed254641 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.thymeleaf.model.Student; + +public class StudentUtils { + + private static List students = new ArrayList(); + + public static List buildStudents() { + if (students.isEmpty()){ + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + } + + return students; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js new file mode 100644 index 0000000000..625e0b37e5 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js @@ -0,0 +1,2 @@ +var count = [[${students.size()}]]; +alert("Number of students in group: " + count); diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt new file mode 100644 index 0000000000..b27796c6ab --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt @@ -0,0 +1,8 @@ +Dear [(${username})], + +This is the list of our students: +[# th:each="s : ${students}"] + - [(${s.name})]. ID: [(${s.id})] +[/] +Thanks, +The Baeldung University \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html new file mode 100644 index 0000000000..7674caa854 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html @@ -0,0 +1,12 @@ + + + + + + +
+ + +
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html new file mode 100644 index 0000000000..cd20746c3a --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html @@ -0,0 +1,12 @@ + + + + +Inlining example + + +

Title of tutorial: [[${title}]]

+

Description: [(${description})]

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html index c25de9eb17..a894e41e88 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -4,6 +4,15 @@ Student List + +

Student List

diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html new file mode 100644 index 0000000000..b2a23a7c0f --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html @@ -0,0 +1,47 @@ + + + + +Expression utility objects + + +

Date expression utility

+

+

+

+

+

+ +

Calendar expression utility

+

+

+

+

+

+ +

Numbers expression utility

+

+

+

+ +

+

+ +

+ +

Calendar expression utility

+

+

+

+

+

+

+ +

Aggregates expression utility

+

+

+

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java new file mode 100644 index 0000000000..f6a79b7570 --- /dev/null +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java @@ -0,0 +1,58 @@ +package com.baeldung.thymeleaf.controller; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class ExpressionUtilityObjectsControllerTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void testGetDates() throws Exception{ + mockMvc.perform(get("/objects").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("objects.html")); + } + +} diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java new file mode 100644 index 0000000000..3542571bbc --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -0,0 +1,78 @@ +package org.baeldung.security.csrf; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class CsrfEnabledIntegrationTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void addStudentWithoutCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden()); + } + + @Test + public void addStudentWithCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); + } + + @Test + public void htmlInliningTest() throws Exception { + mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); + } + + @Test + public void jsInliningTest() throws Exception { + mockMvc.perform(get("/js").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentCheck.js")); + } + + @Test + public void plainInliningTest() throws Exception { + mockMvc.perform(get("/plain").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentsList.txt")); + } + +} diff --git a/couchbase-sdk-async/.springBeans b/spring-userservice/.springBeans similarity index 100% rename from couchbase-sdk-async/.springBeans rename to spring-userservice/.springBeans diff --git a/spring-userservice/README.md b/spring-userservice/README.md new file mode 100644 index 0000000000..097afc5fc1 --- /dev/null +++ b/spring-userservice/README.md @@ -0,0 +1 @@ +spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml new file mode 100644 index 0000000000..93b01ee49c --- /dev/null +++ b/spring-userservice/pom.xml @@ -0,0 +1,320 @@ + + 4.0.0 + spring-userservice + spring-userservice + 0.0.1-SNAPSHOT + war + + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + org.hibernate + hibernate-ehcache + ${hibernate.version} + + + xml-apis + xml-apis + 1.4.01 + + + org.javassist + javassist + ${javassist.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + runtime + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + com.h2database + h2 + ${h2.version} + + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + 2.2.5 + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + + org.springframework.boot + spring-boot-test + 1.4.1.RELEASE + + + org.springframework.boot + spring-boot + 1.4.1.RELEASE + + + javax.servlet + javax.servlet-api + 3.1.0 + + + + + spring-userservice + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + + 4.1.3.RELEASE + 4.3.2.RELEASE + 3.20.0-GA + + + 5.2.2.Final + 5.1.38 + 1.10.2.RELEASE + 1.4.192 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + + + + + \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java new file mode 100644 index 0000000000..4a9e737a92 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.custom.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/"); + registry.addViewController("/index"); + registry.addViewController("/login"); + registry.addViewController("/register"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java new file mode 100644 index 0000000000..6be7053b78 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -0,0 +1,89 @@ +package org.baeldung.custom.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceDerbyJPAConfig { + + @Autowired + private Environment env; + + public PersistenceDerbyJPAConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public MyUserDAO myUserDAO() { + final MyUserDAO myUserDAO = new MyUserDAO(); + return myUserDAO; + } +} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java new file mode 100644 index 0000000000..44df02980f --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.custom.config; + +import org.baeldung.security.MyUserDetailsService; +import org.baeldung.user.service.MyUserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.authenticationProvider(authenticationProvider()); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/*").permitAll() + .and() + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .defaultSuccessUrl("/",true) + .failureUrl("/login?error=true") + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/"); + // @formatter:on + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(myUserDetailsService()); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public MyUserDetailsService myUserDetailsService() { + return new MyUserDetailsService(); + } + + @Bean + public MyUserService myUserService() { + return new MyUserService(); + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java new file mode 100644 index 0000000000..804d391641 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -0,0 +1,50 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_custom_user_service") +public class MyUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + public MyUser() { + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..fe97984af8 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,35 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service("userDetailsService") +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + MyUserDAO myUserDAO; + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final MyUser user = myUserDAO.findByUsername(username); + + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + username); + } + return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java new file mode 100644 index 0000000000..b1c96e72c0 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/UserController.java @@ -0,0 +1,52 @@ +package org.baeldung.security; + +import javax.annotation.Resource; + +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class UserController { + + @Resource + MyUserService myUserService; + + @RequestMapping(value = "/register", method = RequestMethod.POST) + public String registerUserAccount(final MyUserDto accountDto, final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + try { + myUserService.registerNewUserAccount(accountDto); + model.addAttribute("message", "Registration successful"); + return "index"; + } + catch(final Exception exc){ + model.addAttribute("message", "Registration failed"); + + return "index"; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHomepage(final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + return "index"; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String getRegister() { + return "register"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String getLogin() { + return "login"; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java new file mode 100644 index 0000000000..4cc9f61b4a --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -0,0 +1,46 @@ +package org.baeldung.user.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.MyUser; +import org.springframework.stereotype.Repository; + +@Repository +public class MyUserDAO { + + @PersistenceContext + private EntityManager entityManager; + + public MyUser findByUsername(final String username) { + final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); + query.setParameter("username", username); + final List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public MyUser save(final MyUser user) { + entityManager.persist(user); + return user; + } + + public void removeUserByUsername(String username) { + final Query query = entityManager.createQuery("delete from MyUser where username=:username"); + query.setParameter("username", username); + query.executeUpdate(); + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(final EntityManager entityManager) { + this.entityManager = entityManager; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java new file mode 100644 index 0000000000..1e05541998 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -0,0 +1,49 @@ +package org.baeldung.user.service; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.baeldung.web.MyUserDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class MyUserService { + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + MyUserDAO myUserDAO; + + public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { + if (usernameExists(accountDto.getUsername())) { + throw new Exception("There is an account with that username: " + accountDto.getUsername()); + } + final MyUser user = new MyUser(); + + user.setUsername(accountDto.getUsername()); + user.setPassword(passwordEncoder.encode(accountDto.getPassword())); + return myUserDAO.save(user); + } + + public MyUser getUserByUsername(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + return user; + } + + public void removeUserByUsername(String username){ + myUserDAO.removeUserByUsername(username); + } + + private boolean usernameExists(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + if (user != null) { + return true; + } + return false; + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java new file mode 100644 index 0000000000..c572208913 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java @@ -0,0 +1,29 @@ +package org.baeldung.web; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class MyUserDto { + @NotNull + @Size(min = 1) + private String username; + + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + +} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-userservice/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml new file mode 100644 index 0000000000..25d1d4d22f --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} + + + + + + + + + + + + + + + + + + + diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000000..0c89257cd2 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + +Welcome! + + + + + + + +Register +

+ +Login + +

+${message } +

+ +Hello, ${name }! +
+
+Logout +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..29431f426d --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,29 @@ +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + + +

Login

+ +
+ +
+ + + + + + + + + + + +
User:
Password:
+ + + Username or password invalid! + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp new file mode 100644 index 0000000000..e6e9d373a0 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Welcome! + + + + + +Register here:

+
+Username:
+Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b526774179 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + Spring MVC Application + + + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + index.jsp + + + \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..6e1cd67e06 --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java @@ -0,0 +1,85 @@ +package org.baeldung.userservice; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; + + @Autowired + MyUserService myUserService; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Test + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + myUserService.registerNewUserAccount(userDTO); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + + } catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } finally { + myUserService.removeUserByUsername(USERNAME); + } + } + + @Test (expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + try { + myUserService.registerNewUserAccount(userDTO); + } + catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + } + finally { + myUserService.removeUserByUsername(USERNAME); + } + } + +} diff --git a/webjars/pom.xml b/webjars/pom.xml deleted file mode 100644 index 80e4f0a42a..0000000000 --- a/webjars/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - - com.baeldung - webjarsdemo - 0.0.1-SNAPSHOT - jar - - webjarsdemo - Demo project for webjars using Spring Boot - - - org.springframework.boot - spring-boot-starter-parent - 1.3.5.RELEASE - - - - - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.webjars - bootstrap - 3.3.4 - - - org.webjars - jquery - 2.1.4 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/wicket/README.md b/wicket/README.md new file mode 100644 index 0000000000..614446e7ba --- /dev/null +++ b/wicket/README.md @@ -0,0 +1,4 @@ + +From the same directory where pom.xml is, execute the following command to run the project: + +mvn jetty:run diff --git a/wicket/pom.xml b/wicket/pom.xml new file mode 100644 index 0000000000..929f723c2c --- /dev/null +++ b/wicket/pom.xml @@ -0,0 +1,106 @@ + + + + 4.0.0 + com.baeldung.wicket.examples + wicket-intro + war + 1.0-SNAPSHOT + WicketIntro + + 7.4.0 + 9.2.13.v20150730 + 2.5 + 4.12 + 3.5.1 + 2.6 + UTF-8 + + + + + org.apache.wicket + wicket-core + ${wicket.version} + + + + + junit + junit + ${junit.version} + test + + + + + org.eclipse.jetty.aggregate + jetty-all + ${jetty9.version} + test + + + + + + false + src/main/resources + + + false + src/main/java + + ** + + + **/*.java + + + + + + false + src/test/resources + + + false + src/test/java + + ** + + + **/*.java + + + + + + true + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + UTF-8 + true + true + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty9.version} + + + + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html new file mode 100644 index 0000000000..497e98e01a --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html @@ -0,0 +1,52 @@ + + + + +Wicket Intro Examples + + + +
+
+
+

Wicket Introduction Examples:

+ + Hello World! +
+
+ Cafes +
+
+
+
+ + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java new file mode 100644 index 0000000000..ceb0836467 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java @@ -0,0 +1,9 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.markup.html.WebPage; + +public class HelloWorld extends WebPage { + + private static final long serialVersionUID = 1L; + +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java new file mode 100644 index 0000000000..079280adce --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.protocol.http.WebApplication; + +import com.baeldung.wicket.examples.cafeaddress.CafeAddress; + +public class HelloWorldApplication extends WebApplication { + /** + * @see org.apache.wicket.Application#getHomePage() + */ + @Override + public Class getHomePage() { + return HelloWorld.class; + } + + /** + * @see org.apache.wicket.Application#init() + */ + @Override + public void init() { + super.init(); + mountPage("/examples/helloworld", HelloWorld.class); + mountPage("/examples/cafes", CafeAddress.class); + } +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html new file mode 100644 index 0000000000..c5ada2323d --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html @@ -0,0 +1,15 @@ + + + + +Cafes + + +
+ +

+ Address: address +

+
+ + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java new file mode 100644 index 0000000000..86820393c7 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java @@ -0,0 +1,67 @@ +package com.baeldung.wicket.examples.cafeaddress; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class CafeAddress extends WebPage { + private String selectedCafe; + private Address address; + private Map cafeNamesAndAddresses = new HashMap<>(); + + public CafeAddress(final PageParameters parameters) { + super(parameters); + initCafes(); + + ArrayList cafeNames = new ArrayList<>(cafeNamesAndAddresses.keySet()); + selectedCafe = cafeNames.get(0); + address = new Address(cafeNamesAndAddresses.get(selectedCafe).getAddress()); + + final Label addressLabel = new Label("address", new PropertyModel(this.address, "address")); + addressLabel.setOutputMarkupId(true); + + final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<>(this, "selectedCafe"), cafeNames); + cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + String name = (String) cafeDropdown.getDefaultModel().getObject(); + address.setAddress(cafeNamesAndAddresses.get(name).getAddress()); + target.add(addressLabel); + } + }); + + add(addressLabel); + add(cafeDropdown); + + } + + private void initCafes() { + this.cafeNamesAndAddresses.put("Linda's Cafe", new Address("35 Bower St.")); + this.cafeNamesAndAddresses.put("Old Tree", new Address("2 Edgware Rd.")); + } + + class Address implements Serializable { + private String sAddress = ""; + + public Address(String address) { + this.sAddress = address; + } + + String getAddress() { + return this.sAddress; + } + + void setAddress(String address) { + this.sAddress = address; + } + } +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html new file mode 100644 index 0000000000..c56d07fc10 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html @@ -0,0 +1,5 @@ + + + + + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java new file mode 100644 index 0000000000..6dc7295798 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java @@ -0,0 +1,10 @@ +package com.baeldung.wicket.examples.helloworld; + +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.basic.Label; + +public class HelloWorld extends WebPage { + public HelloWorld() { + add(new Label("hello", "Hello World!")); + } +} diff --git a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java new file mode 100644 index 0000000000..7015ffd255 --- /dev/null +++ b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java @@ -0,0 +1,23 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.util.tester.WicketTester; +import org.junit.Before; +import org.junit.Test; + +public class TestHomePage { + private WicketTester tester; + + @Before + public void setUp() { + tester = new WicketTester(new HelloWorldApplication()); + } + + @Test + public void whenPageInvoked_thanRenderedOK() { + //start and render the test page + tester.startPage(HelloWorld.class); + + //assert rendered page class + tester.assertRenderedPage(HelloWorld.class); + } +} diff --git a/wicket/src/main/webapp/WEB-INF/web.xml b/wicket/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..8fc1b1aa95 --- /dev/null +++ b/wicket/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,32 @@ + + + + CafeAddress + + + + + wicket.examples + org.apache.wicket.protocol.http.WicketFilter + + applicationClassName + com.baeldung.wicket.examples.HelloWorldApplication + + + + + wicket.examples + /* + + \ No newline at end of file