Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
64d13813a4
@ -1,17 +1,12 @@
|
|||||||
package com.baeldung.cxf.jaxrs.implementation;
|
package com.baeldung.cxf.jaxrs.implementation;
|
||||||
|
|
||||||
|
import javax.ws.rs.*;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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")
|
@Path("baeldung")
|
||||||
@Produces("text/xml")
|
@Produces("text/xml")
|
||||||
public class Baeldung {
|
public class Baeldung {
|
||||||
@ -51,14 +46,13 @@ public class Baeldung {
|
|||||||
@Path("courses/{courseOrder}")
|
@Path("courses/{courseOrder}")
|
||||||
public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) {
|
public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) {
|
||||||
Course existingCourse = courses.get(courseOrder);
|
Course existingCourse = courses.get(courseOrder);
|
||||||
Response response;
|
|
||||||
if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) {
|
if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) {
|
||||||
courses.put(courseOrder, course);
|
courses.put(courseOrder, course);
|
||||||
response = Response.ok().build();
|
return Response.ok().build();
|
||||||
} else {
|
|
||||||
response = Response.notModified().build();
|
|
||||||
}
|
}
|
||||||
return response;
|
|
||||||
|
return Response.notModified().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Path("courses/{courseOrder}/students")
|
@Path("courses/{courseOrder}/students")
|
||||||
|
@ -1,17 +1,11 @@
|
|||||||
package com.baeldung.cxf.jaxrs.implementation;
|
package com.baeldung.cxf.jaxrs.implementation;
|
||||||
|
|
||||||
|
import javax.ws.rs.*;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.xml.bind.annotation.XmlRootElement;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
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")
|
@XmlRootElement(name = "Course")
|
||||||
public class Course {
|
public class Course {
|
||||||
private int id;
|
private int id;
|
||||||
@ -51,7 +45,7 @@ public class Course {
|
|||||||
@POST
|
@POST
|
||||||
public Response postStudent(Student student) {
|
public Response postStudent(Student student) {
|
||||||
if (students == null) {
|
if (students == null) {
|
||||||
students = new ArrayList<Student>();
|
students = new ArrayList<>();
|
||||||
}
|
}
|
||||||
students.add(student);
|
students.add(student);
|
||||||
return Response.ok(student).build();
|
return Response.ok(student).build();
|
||||||
|
@ -1,18 +1,5 @@
|
|||||||
package com.baeldung.cxf.jaxrs.implementation;
|
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.HttpResponse;
|
||||||
import org.apache.http.client.methods.HttpDelete;
|
import org.apache.http.client.methods.HttpDelete;
|
||||||
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.client.methods.HttpPost;
|
||||||
@ -20,6 +7,17 @@ import org.apache.http.client.methods.HttpPut;
|
|||||||
import org.apache.http.entity.InputStreamEntity;
|
import org.apache.http.entity.InputStreamEntity;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import javax.xml.bind.JAXB;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class ServiceTest {
|
public class ServiceTest {
|
||||||
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
|
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
|
||||||
@ -80,14 +78,12 @@ public class ServiceTest {
|
|||||||
private Course getCourse(int courseOrder) throws IOException {
|
private Course getCourse(int courseOrder) throws IOException {
|
||||||
URL url = new URL(BASE_URL + courseOrder);
|
URL url = new URL(BASE_URL + courseOrder);
|
||||||
InputStream input = url.openStream();
|
InputStream input = url.openStream();
|
||||||
Course course = JAXB.unmarshal(new InputStreamReader(input), Course.class);
|
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
|
||||||
return course;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
|
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
|
||||||
URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
|
URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
|
||||||
InputStream input = url.openStream();
|
InputStream input = url.openStream();
|
||||||
Student student = JAXB.unmarshal(new InputStreamReader(input), Student.class);
|
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
|
||||||
return student;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@ -9,11 +8,18 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>19.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-guava</artifactId>
|
||||||
|
<version>3.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
@ -26,11 +32,7 @@
|
|||||||
<version>3.5.1</version>
|
<version>3.5.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-guava</artifactId>
|
|
||||||
<version>3.0.0</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -46,4 +48,9 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<guava.version>19.0</guava.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -15,7 +15,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>2.4</version>
|
<version>2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -102,22 +102,20 @@ public class FileOperationsTest {
|
|||||||
StringBuilder data = new StringBuilder();
|
StringBuilder data = new StringBuilder();
|
||||||
Stream<String> lines = Files.lines(path);
|
Stream<String> lines = Files.lines(path);
|
||||||
lines.forEach(line -> data.append(line).append("\n"));
|
lines.forEach(line -> data.append(line).append("\n"));
|
||||||
|
lines.close();
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.toString().trim());
|
Assert.assertEquals(expectedData, data.toString().trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
|
|
||||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
|
||||||
StringBuilder resultStringBuilder = new StringBuilder();
|
StringBuilder resultStringBuilder = new StringBuilder();
|
||||||
|
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||||
String line;
|
String line;
|
||||||
while ((line = bufferedReader.readLine()) != null) {
|
while ((line = bufferedReader.readLine()) != null) {
|
||||||
resultStringBuilder.append(line);
|
resultStringBuilder.append(line).append("\n");
|
||||||
resultStringBuilder.append("\n");
|
|
||||||
}
|
}
|
||||||
bufferedReader.close();
|
}
|
||||||
inputStreamReader.close();
|
|
||||||
inputStream.close();
|
|
||||||
return resultStringBuilder.toString();
|
return resultStringBuilder.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,47 +1,41 @@
|
|||||||
package com.baeldung.util;
|
package com.baeldung.util;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.LocalTime;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.GregorianCalendar;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.*;
|
||||||
|
import java.time.temporal.ChronoField;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class CurrentDateTimeTest {
|
public class CurrentDateTimeTest {
|
||||||
|
|
||||||
|
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentDate() {
|
public void shouldReturnCurrentDate() {
|
||||||
|
|
||||||
final LocalDate now = LocalDate.now();
|
final LocalDate now = LocalDate.now(clock);
|
||||||
final Calendar calendar = GregorianCalendar.getInstance();
|
|
||||||
|
|
||||||
assertEquals("10-10-2010".length(), now.toString().length());
|
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||||
assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH));
|
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
|
||||||
assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1);
|
assertEquals(2016, now.get(ChronoField.YEAR));
|
||||||
assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentTime() {
|
public void shouldReturnCurrentTime() {
|
||||||
|
|
||||||
final LocalTime now = LocalTime.now();
|
final LocalTime now = LocalTime.now(clock);
|
||||||
final Calendar calendar = GregorianCalendar.getInstance();
|
|
||||||
|
|
||||||
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY));
|
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||||
assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR));
|
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE));
|
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentTimestamp() {
|
public void shouldReturnCurrentTimestamp() {
|
||||||
|
|
||||||
final Instant now = Instant.now();
|
final Instant now = Instant.now(clock);
|
||||||
final Calendar calendar = GregorianCalendar.getInstance();
|
|
||||||
|
|
||||||
assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
|
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -174,7 +174,7 @@
|
|||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.7.2</jackson.version>
|
<jackson.version>2.7.8</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
@ -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;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<SelectionKey> selectedKeys = selector.selectedKeys();
|
||||||
|
Iterator<SelectionKey> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
1
core-java/src/test/resources/test_md5.txt
Normal file
1
core-java/src/test/resources/test_md5.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
hello world
|
@ -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.
|
|
@ -1,72 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>gson-jackson-performance</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<name>gson-jackson-performance</name>
|
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<finalName>gson-jackson-performance</finalName>
|
|
||||||
<resources>
|
|
||||||
<resource>
|
|
||||||
<directory>src/main/resources</directory>
|
|
||||||
<filtering>true</filtering>
|
|
||||||
</resource>
|
|
||||||
</resources>
|
|
||||||
|
|
||||||
<plugins>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<source>1.8</source>
|
|
||||||
<target>1.8</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
</plugins>
|
|
||||||
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.code.gson</groupId>
|
|
||||||
<artifactId>gson</artifactId>
|
|
||||||
<version>2.5</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
|
||||||
<artifactId>jackson-databind</artifactId>
|
|
||||||
<version>2.7.1-1</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<version>3.8.1</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>log4j</groupId>
|
|
||||||
<artifactId>log4j</artifactId>
|
|
||||||
<version>1.2.17</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
</project>
|
|
@ -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<CustomerAddressDetails> customerAddressDetailsList = new ArrayList<CustomerAddressDetails>();
|
|
||||||
for (int i = 0; i < 600000; i++) {
|
|
||||||
CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails();
|
|
||||||
customerAddressDetails.setAge(20);
|
|
||||||
customerAddressDetails.setFirstName(Utility.generateRandomName());
|
|
||||||
customerAddressDetails.setLastName(Utility.generateRandomName());
|
|
||||||
|
|
||||||
List<AddressDetails> addressDetailsList = new ArrayList<AddressDetails>();
|
|
||||||
customerAddressDetails.setAddressDetails(addressDetailsList);
|
|
||||||
|
|
||||||
for (int j = 0; j < 2; j++) {
|
|
||||||
AddressDetails addressDetails = new AddressDetails();
|
|
||||||
addressDetails.setZipcode(Utility.generateRandomZip());
|
|
||||||
addressDetails.setAddress(Utility.generateRandomAddress());
|
|
||||||
|
|
||||||
List<ContactDetails> contactDetailsList = new ArrayList<ContactDetails>();
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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();
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
@ -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<Customer> customerList = new ArrayList<Customer>();
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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> contactDetails;
|
|
||||||
|
|
||||||
public String getZipcode() {
|
|
||||||
return zipcode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setZipcode(String zipcode) {
|
|
||||||
this.zipcode = zipcode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<ContactDetails> getContactDetails() {
|
|
||||||
return contactDetails;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setContactDetails(List<ContactDetails> contactDetails) {
|
|
||||||
this.contactDetails = contactDetails;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAddress() {
|
|
||||||
return address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddress(String address) {
|
|
||||||
this.address = address;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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> addressDetails;
|
|
||||||
|
|
||||||
public List<AddressDetails> getAddressDetails() {
|
|
||||||
return addressDetails;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddressDetails(List<AddressDetails> addressDetails) {
|
|
||||||
this.addressDetails = addressDetails;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,17 +0,0 @@
|
|||||||
package com.baeldung.pojo.complex;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class CustomerPortfolioComplex {
|
|
||||||
|
|
||||||
private List<CustomerAddressDetails> customerAddressDetailsList;
|
|
||||||
|
|
||||||
public List<CustomerAddressDetails> getCustomerAddressDetailsList() {
|
|
||||||
return customerAddressDetailsList;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCustomerAddressDetailsList(List<CustomerAddressDetails> customerAddressDetailsList) {
|
|
||||||
this.customerAddressDetailsList = customerAddressDetailsList;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
package com.baeldung.pojo.simple;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class CustomerPortfolioSimple {
|
|
||||||
|
|
||||||
private List<Customer> customerLists;
|
|
||||||
|
|
||||||
public List<Customer> getCustomerLists() {
|
|
||||||
return customerLists;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCustomerLists(List<Customer> customerLists) {
|
|
||||||
this.customerLists = customerLists;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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
|
|
@ -19,7 +19,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>18.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@ -14,12 +13,15 @@
|
|||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>18.0</version>
|
<version>18.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -10,17 +11,20 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>19.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-all</artifactId>
|
<artifactId>hamcrest-all</artifactId>
|
||||||
<version>1.3</version>
|
<version>1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -42,4 +46,8 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<guava.version>19.0</guava.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -115,6 +115,7 @@
|
|||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate</groupId>
|
||||||
<artifactId>hibernate-validator</artifactId>
|
<artifactId>hibernate-validator</artifactId>
|
||||||
@ -221,8 +222,7 @@
|
|||||||
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
|
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
|
<jackson.version>2.7.8</jackson.version>
|
||||||
<jackson.version>2.7.2</jackson.version>
|
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
@ -174,7 +174,7 @@
|
|||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.7.2</jackson.version>
|
<jackson.version>2.7.8</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>cassandra-java-client</artifactId>
|
<artifactId>cassandra-java-client</artifactId>
|
||||||
@ -6,27 +7,6 @@
|
|||||||
|
|
||||||
<name>cassandra-java-client</name>
|
<name>cassandra-java-client</name>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
|
|
||||||
<!-- logging -->
|
|
||||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
|
||||||
<logback.version>1.1.7</logback.version>
|
|
||||||
|
|
||||||
<!-- testing -->
|
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
|
||||||
<junit.version>4.12</junit.version>
|
|
||||||
<mockito.version>1.10.19</mockito.version>
|
|
||||||
<testng.version>6.8</testng.version>
|
|
||||||
<assertj.version>3.5.1</assertj.version>
|
|
||||||
|
|
||||||
<!-- maven plugins -->
|
|
||||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
|
||||||
|
|
||||||
<!-- Cassandra -->
|
|
||||||
<cassandra-driver-core.version>3.1.0</cassandra-driver-core.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- Cassandra -->
|
<!-- Cassandra -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -47,7 +27,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>19.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
@ -97,6 +77,29 @@
|
|||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
|
||||||
|
<guava.version>19.0</guava.version>
|
||||||
|
|
||||||
|
<!-- logging -->
|
||||||
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
|
<!-- testing -->
|
||||||
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
<testng.version>6.8</testng.version>
|
||||||
|
<assertj.version>3.5.1</assertj.version>
|
||||||
|
|
||||||
|
<!-- maven plugins -->
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
|
||||||
|
<!-- Cassandra -->
|
||||||
|
<cassandra-driver-core.version>3.1.0</cassandra-driver-core.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -20,12 +20,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>log4j-api</artifactId>
|
<artifactId>log4j-api</artifactId>
|
||||||
<version>2.6</version>
|
<version>2.7</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>log4j-core</artifactId>
|
<artifactId>log4j-core</artifactId>
|
||||||
<version>2.6</version>
|
<version>2.7</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!--disruptor for log4j2 async logging-->
|
<!--disruptor for log4j2 async logging-->
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -1,45 +1,172 @@
|
|||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import static org.junit.Assert.assertEquals;
|
||||||
import org.junit.*;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import play.mvc.*;
|
import java.io.BufferedReader;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.json.JSONArray;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import model.Student;
|
||||||
import play.test.*;
|
import play.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 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{
|
public class ApplicationTest{
|
||||||
|
private static final String BASE_URL = "http://localhost:9000";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void simpleCheck() {
|
public void testInServer() throws Exception {
|
||||||
int a = 1 + 1;
|
TestServer server = testServer(3333);
|
||||||
assertEquals(2, a);
|
running(server, () -> {
|
||||||
|
try {
|
||||||
|
WSClient ws = play.libs.ws.WS.newClient(3333);
|
||||||
|
CompletionStage<WSResponse> 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
|
@Test
|
||||||
public void renderTemplate() {
|
public void whenDeletesCreatedRecord_thenCorrect() {
|
||||||
Content html = views.html.index.render("Your new application is ready.");
|
Student student = new Student("Usain", "Bolt", 25);
|
||||||
assertEquals("text/html", html.contentType());
|
JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
|
||||||
assertTrue(html.body().contains("Your new application is ready."));
|
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();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
@ -1,25 +0,0 @@
|
|||||||
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."));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
1
pom.xml
1
pom.xml
@ -34,7 +34,6 @@
|
|||||||
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
|
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
|
||||||
|
|
||||||
<module>gson</module>
|
<module>gson</module>
|
||||||
<module>gson-jackson-performance</module>
|
|
||||||
<module>guava</module>
|
<module>guava</module>
|
||||||
<module>guava18</module>
|
<module>guava18</module>
|
||||||
<module>guava19</module>
|
<module>guava19</module>
|
||||||
|
@ -5,108 +5,71 @@
|
|||||||
<artifactId>rest-assured</artifactId>
|
<artifactId>rest-assured</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
<name>rest-assured</name>
|
<name>rest-assured</name>
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>3.3</version>
|
|
||||||
<configuration>
|
|
||||||
<source>8</source>
|
|
||||||
<target>8</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
<version>3.1-b06</version>
|
<version>3.1-b06</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>servlet-api</artifactId>
|
<artifactId>servlet-api</artifactId>
|
||||||
<version>2.5</version>
|
<version>2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-security -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-security</artifactId>
|
<artifactId>jetty-security</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlet -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-servlet</artifactId>
|
<artifactId>jetty-servlet</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlets -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-servlets</artifactId>
|
<artifactId>jetty-servlets</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-io -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-io</artifactId>
|
<artifactId>jetty-io</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-http -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-http</artifactId>
|
<artifactId>jetty-http</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-server -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-server</artifactId>
|
<artifactId>jetty-server</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-util -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jetty</groupId>
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
<artifactId>jetty-util</artifactId>
|
<artifactId>jetty-util</artifactId>
|
||||||
<version>9.2.0.M1</version>
|
<version>9.2.0.M1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>1.7.21</version>
|
<version>1.7.21</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>log4j</groupId>
|
<groupId>log4j</groupId>
|
||||||
<artifactId>log4j</artifactId>
|
<artifactId>log4j</artifactId>
|
||||||
<version>1.2.17</version>
|
<version>1.2.17</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-log4j12</artifactId>
|
<artifactId>slf4j-log4j12</artifactId>
|
||||||
<version>1.7.21</version>
|
<version>1.7.21</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/com.jayway.restassured/rest-assured-common -->
|
|
||||||
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-logging</groupId>
|
<groupId>commons-logging</groupId>
|
||||||
<artifactId>commons-logging</artifactId>
|
<artifactId>commons-logging</artifactId>
|
||||||
@ -119,22 +82,18 @@
|
|||||||
<version>4.4.5</version>
|
<version>4.4.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>3.4</version>
|
<version>3.4</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/com.github.fge/uri-template -->
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.fge</groupId>
|
<groupId>com.github.fge</groupId>
|
||||||
<artifactId>uri-template</artifactId>
|
<artifactId>uri-template</artifactId>
|
||||||
<version>0.9</version>
|
<version>0.9</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.googlecode.libphonenumber</groupId>
|
<groupId>com.googlecode.libphonenumber</groupId>
|
||||||
<artifactId>libphonenumber</artifactId>
|
<artifactId>libphonenumber</artifactId>
|
||||||
@ -156,19 +115,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-annotations</artifactId>
|
<artifactId>jackson-annotations</artifactId>
|
||||||
<version>2.8.0</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>2.8.0</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
|
||||||
<artifactId>jackson-core</artifactId>
|
|
||||||
<version>2.8.0</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -183,12 +135,10 @@
|
|||||||
<version>1.8</version>
|
<version>1.8</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>18.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.fge</groupId>
|
<groupId>com.github.fge</groupId>
|
||||||
@ -246,7 +196,6 @@
|
|||||||
<artifactId>hamcrest-all</artifactId>
|
<artifactId>hamcrest-all</artifactId>
|
||||||
<version>1.3</version>
|
<version>1.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-collections</groupId>
|
<groupId>commons-collections</groupId>
|
||||||
<artifactId>commons-collections</artifactId>
|
<artifactId>commons-collections</artifactId>
|
||||||
@ -254,4 +203,24 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.3</version>
|
||||||
|
<configuration>
|
||||||
|
<source>8</source>
|
||||||
|
<target>8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<jackson.version>2.8.3</jackson.version>
|
||||||
|
<guava.version>19.0</guava.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -156,7 +156,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.7.2</jackson.version>
|
<jackson.version>2.7.8</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringE
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -27,9 +27,7 @@ public class SpringAkkaTest extends AbstractJUnit4SpringContextTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
|
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
|
||||||
ActorRef greeter = system.actorOf(
|
ActorRef greeter = system.actorOf(SPRING_EXTENSION_PROVIDER.get(system).props("greetingActor"), "greeter");
|
||||||
SPRING_EXTENSION_PROVIDER.get(system)
|
|
||||||
.props("greetingActor"), "greeter");
|
|
||||||
|
|
||||||
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
|
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
|
||||||
Timeout timeout = Timeout.durationToTimeout(duration);
|
Timeout timeout = Timeout.durationToTimeout(duration);
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-all</artifactId>
|
<artifactId>spring-all</artifactId>
|
||||||
@ -160,6 +161,11 @@
|
|||||||
<version>3.4</version>
|
<version>3.4</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.ehcache</groupId>
|
||||||
|
<artifactId>ehcache</artifactId>
|
||||||
|
<version>3.1.3</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
24
spring-all/src/main/java/org/baeldung/ehcache/app/App.java
Executable file
24
spring-all/src/main/java/org/baeldung/ehcache/app/App.java
Executable file
@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
25
spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java
Executable file
25
spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java
Executable file
@ -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<Integer, Integer> 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<Integer, Integer> getSquareNumberCache() {
|
||||||
|
return squareNumberCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
|
|||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
||||||
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
||||||
|
@ -11,7 +11,6 @@ public class Foo {
|
|||||||
|
|
||||||
private static final AtomicInteger instanceCount = new AtomicInteger(0);
|
private static final AtomicInteger instanceCount = new AtomicInteger(0);
|
||||||
|
|
||||||
|
|
||||||
private final int instanceNum;
|
private final int instanceNum;
|
||||||
|
|
||||||
public Foo() {
|
public Foo() {
|
||||||
|
@ -18,7 +18,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|||||||
import org.springframework.web.context.WebApplicationContext;
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
import org.springframework.web.servlet.ModelAndView;
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
|
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
|
||||||
@ -43,9 +42,7 @@ public class ControllerAnnotationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testTestController() throws Exception {
|
public void testTestController() throws Exception {
|
||||||
|
|
||||||
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
|
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
|
||||||
.andReturn()
|
|
||||||
.getModelAndView();
|
|
||||||
|
|
||||||
// validate modal data
|
// validate modal data
|
||||||
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
||||||
@ -57,9 +54,7 @@ public class ControllerAnnotationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testRestController() throws Exception {
|
public void testRestController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
@ -72,9 +67,7 @@ public class ControllerAnnotationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testRestAnnotatedController() throws Exception {
|
public void testRestAnnotatedController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
@ -41,9 +41,7 @@ public class ControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testTestController() throws Exception {
|
public void testTestController() throws Exception {
|
||||||
|
|
||||||
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
|
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
|
||||||
.andReturn()
|
|
||||||
.getModelAndView();
|
|
||||||
|
|
||||||
// validate modal data
|
// validate modal data
|
||||||
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
||||||
@ -55,9 +53,7 @@ public class ControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testRestController() throws Exception {
|
public void testRestController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
@ -70,9 +66,7 @@ public class ControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testRestAnnotatedController() throws Exception {
|
public void testRestAnnotatedController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
|
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
|
||||||
String result = this.mockMvc.perform(get("/test")
|
String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.accept(MediaType.ALL))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
Assert.assertEquals("login = john, query = invoices", result);
|
Assert.assertEquals("login = john, query = invoices", result);
|
||||||
}
|
}
|
||||||
|
@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
|
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
|
||||||
this.mockMvc.perform(get("/appointments")
|
this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
|
||||||
.accept(MediaType.ALL))
|
|
||||||
.andExpect(status().isOk());
|
|
||||||
verify(appointmentService);
|
verify(appointmentService);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package org.baeldung.spring43.defaultmethods;
|
package org.baeldung.spring43.defaultmethods;
|
||||||
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
|
@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
|
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
|
||||||
MockHttpSession session = new MockHttpSession();
|
MockHttpSession session = new MockHttpSession();
|
||||||
|
|
||||||
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request")
|
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request")
|
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
|
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
|
||||||
}
|
}
|
||||||
@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
|||||||
MockHttpSession session1 = new MockHttpSession();
|
MockHttpSession session1 = new MockHttpSession();
|
||||||
MockHttpSession session2 = new MockHttpSession();
|
MockHttpSession session2 = new MockHttpSession();
|
||||||
|
|
||||||
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session")
|
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session1)
|
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.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);
|
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
|
||||||
|
|
||||||
@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
|||||||
MockHttpSession session1 = new MockHttpSession();
|
MockHttpSession session1 = new MockHttpSession();
|
||||||
MockHttpSession session2 = new MockHttpSession();
|
MockHttpSession session2 = new MockHttpSession();
|
||||||
|
|
||||||
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application")
|
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session1)
|
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.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);
|
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);
|
||||||
|
|
||||||
|
@ -88,12 +88,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.webjars</groupId>
|
<groupId>org.webjars</groupId>
|
||||||
<artifactId>bootstrap</artifactId>
|
<artifactId>bootstrap</artifactId>
|
||||||
<version>3.3.4</version>
|
<version>3.3.7-1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.webjars</groupId>
|
<groupId>org.webjars</groupId>
|
||||||
<artifactId>jquery</artifactId>
|
<artifactId>jquery</artifactId>
|
||||||
<version>2.1.4</version>
|
<version>3.1.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
@ -21,6 +21,3 @@ public class CommitIdApplication {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<title>WebJars Demo</title>
|
<title>WebJars Demo</title>
|
||||||
<link rel="stylesheet" href="/webjars/bootstrap/3.3.4/css/bootstrap.min.css" />
|
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<div class="container"><br/>
|
<div class="container"><br/>
|
||||||
<div class="alert alert-success">
|
<div class="alert alert-success">
|
||||||
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
|
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
|
||||||
<strong>Success!</strong> It is working as we expected.
|
<strong>Success!</strong> It is working as we expected.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/webjars/jquery/2.1.4/jquery.min.js"></script>
|
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
|
||||||
<script src="/webjars/bootstrap/3.3.4/js/bootstrap.min.js"></script>
|
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
@ -32,13 +32,10 @@ public class CommitIdTest {
|
|||||||
LOG.info(commitMessage);
|
LOG.info(commitMessage);
|
||||||
LOG.info(branch);
|
LOG.info(branch);
|
||||||
|
|
||||||
assertThat(commitMessage)
|
assertThat(commitMessage).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
|
|
||||||
assertThat(branch)
|
assertThat(branch).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
|
|
||||||
assertThat(commitId)
|
assertThat(commitId).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -31,22 +31,15 @@ public class SpringBootApplicationTest {
|
|||||||
private WebApplicationContext webApplicationContext;
|
private WebApplicationContext webApplicationContext;
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setupMockMvc() {
|
public void setupMockMvc() {
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
|
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
||||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
|
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||||
MediaType.APPLICATION_JSON.getSubtype(),
|
|
||||||
Charset.forName("utf8"));
|
|
||||||
|
|
||||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
|
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
|
||||||
andExpect(MockMvcResultMatchers.status().isOk()).
|
|
||||||
andExpect(MockMvcResultMatchers.content().contentType(contentType)).
|
|
||||||
andExpect(jsonPath("$", hasSize(4)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -69,7 +69,6 @@ public class SpringBootMailTest {
|
|||||||
return wiserMessage.getMimeMessage().getSubject();
|
return wiserMessage.getMimeMessage().getSubject();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private SimpleMailMessage composeEmailMessage() {
|
private SimpleMailMessage composeEmailMessage() {
|
||||||
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
||||||
mailMessage.setTo(userTo);
|
mailMessage.setTo(userTo);
|
||||||
|
@ -30,8 +30,7 @@ public class DetailsServiceClientTest {
|
|||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
|
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
|
||||||
this.server.expect(requestTo("/john/details"))
|
this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
||||||
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -1,27 +0,0 @@
|
|||||||
## Spring Cloud Config ##
|
|
||||||
|
|
||||||
To get this example working, you have to initialize a new *Git* repository in
|
|
||||||
the ```client-config``` directory first *and* you have to set the environment variable
|
|
||||||
```CONFIG_REPO``` to an absolute path of that directory.
|
|
||||||
|
|
||||||
```
|
|
||||||
$> cd client-config
|
|
||||||
$> git init
|
|
||||||
$> git add .
|
|
||||||
$> git commit -m 'Initial commit'
|
|
||||||
$> export CONFIG_REPO=$(pwd)
|
|
||||||
```
|
|
||||||
|
|
||||||
Then you're able to run the examples with ```mvn install spring-boot:run```.
|
|
||||||
|
|
||||||
### Docker ###
|
|
||||||
|
|
||||||
To get the *Docker* examples working, you have to repackage the ```spring-cloud-config-server```
|
|
||||||
and ```spring-cloud-config-client``` modules first:
|
|
||||||
|
|
||||||
```
|
|
||||||
$> mvn install spring-boot:repackage
|
|
||||||
```
|
|
||||||
|
|
||||||
Don't forget to download the *Java JCE* package from
|
|
||||||
(Oracle)[http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html].
|
|
@ -1,6 +0,0 @@
|
|||||||
FROM alpine-java:base
|
|
||||||
MAINTAINER baeldung.com
|
|
||||||
RUN apk --no-cache add netcat-openbsd
|
|
||||||
COPY files/spring-cloud-config-client-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-client.jar
|
|
||||||
COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/
|
|
||||||
RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh
|
|
@ -1,9 +0,0 @@
|
|||||||
FROM alpine-java:base
|
|
||||||
MAINTAINER baeldung.com
|
|
||||||
COPY files/spring-cloud-config-server-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-server.jar
|
|
||||||
ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \
|
|
||||||
{"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}'
|
|
||||||
ENTRYPOINT ["/usr/bin/java"]
|
|
||||||
CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"]
|
|
||||||
VOLUME /var/lib/spring-cloud/config-repo
|
|
||||||
EXPOSE 8888
|
|
2
spring-cloud-config/docker/files/.gitignore
vendored
2
spring-cloud-config/docker/files/.gitignore
vendored
@ -1,2 +0,0 @@
|
|||||||
/UnlimitedJCEPolicyJDK8
|
|
||||||
/*.jar
|
|
@ -1,8 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
while ! nc -z config-server 8888 ; do
|
|
||||||
echo "Waiting for upcoming Config Server"
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
|
|
||||||
java -jar /opt/spring-cloud/lib/config-client.jar
|
|
@ -1,52 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
|
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
|
||||||
<artifactId>spring-cloud-config</artifactId>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
|
|
||||||
<modules>
|
|
||||||
<module>spring-cloud-config-server</module>
|
|
||||||
<module>spring-cloud-config-client</module>
|
|
||||||
</modules>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>..</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencyManagement>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-parent</artifactId>
|
|
||||||
<version>1.4.0.RELEASE</version>
|
|
||||||
<type>pom</type>
|
|
||||||
<scope>import</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.cloud</groupId>
|
|
||||||
<artifactId>spring-cloud-dependencies</artifactId>
|
|
||||||
<version>Brixton.SR4</version>
|
|
||||||
<type>pom</type>
|
|
||||||
<scope>import</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</dependencyManagement>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<pluginManagement>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>1.4.0.RELEASE</version>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</pluginManagement>
|
|
||||||
</build>
|
|
||||||
</project>
|
|
@ -23,18 +23,23 @@ public class Campus {
|
|||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Point getLocation() {
|
public Point getLocation() {
|
||||||
return location;
|
return location;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLocation(Point location) {
|
public void setLocation(Point location) {
|
||||||
this.location = location;
|
this.location = location;
|
||||||
}
|
}
|
||||||
@ -56,14 +61,17 @@ public class Campus {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Campus other = (Campus) obj;
|
Campus other = (Campus) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
private Campus() {}
|
private Campus() {
|
||||||
|
}
|
||||||
|
|
||||||
public Campus(Builder b) {
|
public Campus(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
|
@ -34,30 +34,39 @@ public class Person {
|
|||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirstName() {
|
public String getFirstName() {
|
||||||
return firstName;
|
return firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
public void setFirstName(String firstName) {
|
||||||
this.firstName = firstName;
|
this.firstName = firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLastName() {
|
public String getLastName() {
|
||||||
return lastName;
|
return lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
public void setLastName(String lastName) {
|
||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getCreated() {
|
public DateTime getCreated() {
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreated(DateTime created) {
|
public void setCreated(DateTime created) {
|
||||||
this.created = created;
|
this.created = created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getUpdated() {
|
public DateTime getUpdated() {
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUpdated(DateTime updated) {
|
public void setUpdated(DateTime updated) {
|
||||||
this.updated = updated;
|
this.updated = updated;
|
||||||
}
|
}
|
||||||
@ -79,8 +88,10 @@ public class Person {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Person other = (Person) obj;
|
Person other = (Person) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,8 @@ public class Student {
|
|||||||
@Version
|
@Version
|
||||||
private long version;
|
private long version;
|
||||||
|
|
||||||
public Student() {}
|
public Student() {
|
||||||
|
}
|
||||||
|
|
||||||
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
|
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
@ -51,36 +52,47 @@ public class Student {
|
|||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirstName() {
|
public String getFirstName() {
|
||||||
return firstName;
|
return firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
public void setFirstName(String firstName) {
|
||||||
this.firstName = firstName;
|
this.firstName = firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLastName() {
|
public String getLastName() {
|
||||||
return lastName;
|
return lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
public void setLastName(String lastName) {
|
||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getDateOfBirth() {
|
public DateTime getDateOfBirth() {
|
||||||
return dateOfBirth;
|
return dateOfBirth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDateOfBirth(DateTime dateOfBirth) {
|
public void setDateOfBirth(DateTime dateOfBirth) {
|
||||||
this.dateOfBirth = dateOfBirth;
|
this.dateOfBirth = dateOfBirth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getCreated() {
|
public DateTime getCreated() {
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreated(DateTime created) {
|
public void setCreated(DateTime created) {
|
||||||
this.created = created;
|
this.created = created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getUpdated() {
|
public DateTime getUpdated() {
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUpdated(DateTime updated) {
|
public void setUpdated(DateTime updated) {
|
||||||
this.updated = updated;
|
this.updated = updated;
|
||||||
}
|
}
|
||||||
@ -105,8 +117,10 @@ public class Student {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Student other = (Student) obj;
|
Student other = (Student) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository {
|
|||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
public List<Student> findByFirstNameStartsWith(String s) {
|
public List<Student> findByFirstNameStartsWith(String s) {
|
||||||
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName")
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class);
|
||||||
.startKey(s)
|
|
||||||
.stale(Stale.FALSE),
|
|
||||||
Student.class);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
|||||||
|
|
||||||
public interface PersonRepository extends CrudRepository<Person, String> {
|
public interface PersonRepository extends CrudRepository<Person, String> {
|
||||||
List<Person> findByFirstName(String firstName);
|
List<Person> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Person> findByLastName(String lastName);
|
List<Person> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
|||||||
|
|
||||||
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
|
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
|
||||||
List<Student> findByFirstName(String firstName);
|
List<Student> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Student> findByLastName(String lastName);
|
List<Student> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
|||||||
public class PersonRepositoryService implements PersonService {
|
public class PersonRepositoryService implements PersonService {
|
||||||
|
|
||||||
private PersonRepository repo;
|
private PersonRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setPersonRepository(PersonRepository repo) {
|
public void setPersonRepository(PersonRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -18,6 +18,7 @@ public class PersonTemplateService implements PersonService {
|
|||||||
private static final String DESIGN_DOC = "person";
|
private static final String DESIGN_DOC = "person";
|
||||||
|
|
||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
||||||
this.template = template;
|
this.template = template;
|
||||||
|
@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
|||||||
public class StudentRepositoryService implements StudentService {
|
public class StudentRepositoryService implements StudentService {
|
||||||
|
|
||||||
private StudentRepository repo;
|
private StudentRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setStudentRepository(StudentRepository repo) {
|
public void setStudentRepository(StudentRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -18,6 +18,7 @@ public class StudentTemplateService implements StudentService {
|
|||||||
private static final String DESIGN_DOC = "student";
|
private static final String DESIGN_DOC = "student";
|
||||||
|
|
||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
||||||
this.template = template;
|
this.template = template;
|
||||||
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
|||||||
|
|
||||||
public interface PersonRepository extends CrudRepository<Person, String> {
|
public interface PersonRepository extends CrudRepository<Person, String> {
|
||||||
List<Person> findByFirstName(String firstName);
|
List<Person> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Person> findByLastName(String lastName);
|
List<Person> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
|||||||
|
|
||||||
public interface StudentRepository extends CrudRepository<Student, String> {
|
public interface StudentRepository extends CrudRepository<Student, String> {
|
||||||
List<Student> findByFirstName(String firstName);
|
List<Student> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Student> findByLastName(String lastName);
|
List<Student> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
|
|||||||
public class CampusServiceImpl implements CampusService {
|
public class CampusServiceImpl implements CampusService {
|
||||||
|
|
||||||
private CampusRepository repo;
|
private CampusRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCampusRepository(CampusRepository repo) {
|
public void setCampusRepository(CampusRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
|||||||
public class PersonServiceImpl implements PersonService {
|
public class PersonServiceImpl implements PersonService {
|
||||||
|
|
||||||
private PersonRepository repo;
|
private PersonRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setPersonRepository(PersonRepository repo) {
|
public void setPersonRepository(PersonRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
|||||||
public class StudentServiceImpl implements StudentService {
|
public class StudentServiceImpl implements StudentService {
|
||||||
|
|
||||||
private StudentRepository repo;
|
private StudentRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setStudentRepository(StudentRepository repo) {
|
public void setStudentRepository(StudentRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -30,24 +30,14 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
|||||||
static final String joeCollegeId = "student:" + joe + ":" + college;
|
static final String joeCollegeId = "student:" + joe + ":" + college;
|
||||||
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
||||||
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
||||||
static final JsonObject jsonJoeCollege = JsonObject.empty()
|
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);
|
||||||
.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 judy = "Judy";
|
||||||
static final String jetson = "Jetson";
|
static final String jetson = "Jetson";
|
||||||
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
||||||
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
||||||
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
||||||
static final JsonObject jsonJudyJetson = JsonObject.empty()
|
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);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", judy)
|
|
||||||
.put("lastName", jetson)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
StudentService studentService;
|
StudentService studentService;
|
||||||
|
|
||||||
|
@ -46,11 +46,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
|||||||
|
|
||||||
@Bean(name = "campusTemplate")
|
@Bean(name = "campusTemplate")
|
||||||
public CouchbaseTemplate campusTemplate() throws Exception {
|
public CouchbaseTemplate campusTemplate() throws Exception {
|
||||||
CouchbaseTemplate template = new CouchbaseTemplate(
|
CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService());
|
||||||
couchbaseClusterInfo(),
|
|
||||||
campusBucket(),
|
|
||||||
mappingCouchbaseConverter(),
|
|
||||||
translationService());
|
|
||||||
template.setDefaultConsistency(getDefaultConsistency());
|
template.setDefaultConsistency(getDefaultConsistency());
|
||||||
return template;
|
return template;
|
||||||
}
|
}
|
||||||
|
@ -26,53 +26,21 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private CampusRepository campusRepo;
|
private CampusRepository campusRepo;
|
||||||
|
|
||||||
private final Campus Brown = Campus.Builder.newInstance()
|
private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build();
|
||||||
.id("campus:Brown")
|
|
||||||
.name("Brown")
|
|
||||||
.location(new Point(71.4025, 51.8268))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Cornell = Campus.Builder.newInstance()
|
private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build();
|
||||||
.id("campus:Cornell")
|
|
||||||
.name("Cornell")
|
|
||||||
.location(new Point(76.4833, 42.4459))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Columbia = Campus.Builder.newInstance()
|
private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build();
|
||||||
.id("campus:Columbia")
|
|
||||||
.name("Columbia")
|
|
||||||
.location(new Point(73.9626, 40.8075))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Dartmouth = Campus.Builder.newInstance()
|
private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build();
|
||||||
.id("campus:Dartmouth")
|
|
||||||
.name("Dartmouth")
|
|
||||||
.location(new Point(72.2887, 43.7044))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Harvard = Campus.Builder.newInstance()
|
private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build();
|
||||||
.id("campus:Harvard")
|
|
||||||
.name("Harvard")
|
|
||||||
.location(new Point(71.1167, 42.3770))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Penn = Campus.Builder.newInstance()
|
private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build();
|
||||||
.id("campus:Penn")
|
|
||||||
.name("Penn")
|
|
||||||
.location(new Point(75.1932, 39.9522))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Princeton = Campus.Builder.newInstance()
|
private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build();
|
||||||
.id("campus:Princeton")
|
|
||||||
.name("Princeton")
|
|
||||||
.location(new Point(74.6514, 40.3340))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Yale = Campus.Builder.newInstance()
|
private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build();
|
||||||
.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 Boston = new Point(71.0589, 42.3601);
|
||||||
private final Point NewYorkCity = new Point(74.0059, 40.7128);
|
private final Point NewYorkCity = new Point(74.0059, 40.7128);
|
||||||
|
@ -31,24 +31,14 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
|||||||
static final String joeCollegeId = "student:" + joe + ":" + college;
|
static final String joeCollegeId = "student:" + joe + ":" + college;
|
||||||
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
||||||
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
||||||
static final JsonObject jsonJoeCollege = JsonObject.empty()
|
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);
|
||||||
.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 judy = "Judy";
|
||||||
static final String jetson = "Jetson";
|
static final String jetson = "Jetson";
|
||||||
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
||||||
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
||||||
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
||||||
static final JsonObject jsonJudyJetson = JsonObject.empty()
|
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);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", judy)
|
|
||||||
.put("lastName", jetson)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
StudentServiceImpl studentService;
|
StudentServiceImpl studentService;
|
||||||
|
@ -43,8 +43,7 @@ public class ElasticSearchUnitTests {
|
|||||||
@Test
|
@Test
|
||||||
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
||||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
|
||||||
.setSource(jsonObject).get();
|
|
||||||
String index = response.getIndex();
|
String index = response.getIndex();
|
||||||
String type = response.getType();
|
String type = response.getType();
|
||||||
assertTrue(response.isCreated());
|
assertTrue(response.isCreated());
|
||||||
@ -55,8 +54,7 @@ public class ElasticSearchUnitTests {
|
|||||||
@Test
|
@Test
|
||||||
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
||||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
|
||||||
.setSource(jsonObject).get();
|
|
||||||
String id = response.getId();
|
String id = response.getId();
|
||||||
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
|
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
|
||||||
assertTrue(deleteResponse.isFound());
|
assertTrue(deleteResponse.isFound());
|
||||||
@ -77,29 +75,11 @@ public class ElasticSearchUnitTests {
|
|||||||
@Test
|
@Test
|
||||||
public void givenSearchParamters_thenReturnResults() {
|
public void givenSearchParamters_thenReturnResults() {
|
||||||
boolean isExecutedSuccessfully = true;
|
boolean isExecutedSuccessfully = true;
|
||||||
SearchResponse response = client.prepareSearch()
|
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();
|
||||||
.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()
|
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();
|
||||||
.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()
|
SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet();
|
||||||
.setTypes()
|
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
|
|
||||||
.setFrom(0).setSize(60).setExplain(true)
|
|
||||||
.execute()
|
|
||||||
.actionGet();
|
|
||||||
try {
|
try {
|
||||||
response2.getHits();
|
response2.getHits();
|
||||||
response3.getHits();
|
response3.getHits();
|
||||||
@ -114,14 +94,8 @@ public class ElasticSearchUnitTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
||||||
XContentBuilder builder = XContentFactory.jsonBuilder()
|
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject();
|
||||||
.startObject()
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get();
|
||||||
.field("fullName", "Test")
|
|
||||||
.field("salary", "11500")
|
|
||||||
.field("age", "10")
|
|
||||||
.endObject();
|
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
|
||||||
.setSource(builder).get();
|
|
||||||
assertTrue(response.isCreated());
|
assertTrue(response.isCreated());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,6 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
|||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
|
|
||||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
||||||
@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||||
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
||||||
config
|
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL);
|
||||||
.driverConfiguration()
|
|
||||||
.setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
|
|
||||||
.setURI(URL);
|
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,7 +10,6 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
|||||||
import org.springframework.data.neo4j.server.Neo4jServer;
|
import org.springframework.data.neo4j.server.Neo4jServer;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
|
|
||||||
@EnableTransactionManagement
|
@EnableTransactionManagement
|
||||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||||
@Configuration
|
@Configuration
|
||||||
@ -21,9 +20,7 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||||
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
||||||
config
|
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
|
||||||
.driverConfiguration()
|
|
||||||
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
|
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,9 +21,11 @@ public class Movie {
|
|||||||
private int released;
|
private int released;
|
||||||
private String tagline;
|
private String tagline;
|
||||||
|
|
||||||
@Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List<Role> roles;
|
@Relationship(type = "ACTED_IN", direction = Relationship.INCOMING)
|
||||||
|
private List<Role> roles;
|
||||||
|
|
||||||
public Movie() { }
|
public Movie() {
|
||||||
|
}
|
||||||
|
|
||||||
public String getTitle() {
|
public String getTitle() {
|
||||||
return title;
|
return title;
|
||||||
@ -57,5 +59,4 @@ public class Movie {
|
|||||||
this.roles = roles;
|
this.roles = roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.spring.data.neo4j.domain;
|
package com.baeldung.spring.data.neo4j.domain;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||||
import org.neo4j.ogm.annotation.GraphId;
|
import org.neo4j.ogm.annotation.GraphId;
|
||||||
@ -21,7 +20,8 @@ public class Person {
|
|||||||
@Relationship(type = "ACTED_IN")
|
@Relationship(type = "ACTED_IN")
|
||||||
private List<Movie> movies;
|
private List<Movie> movies;
|
||||||
|
|
||||||
public Person() { }
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.spring.data.neo4j.domain;
|
package com.baeldung.spring.data.neo4j.domain;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||||
import org.neo4j.ogm.annotation.EndNode;
|
import org.neo4j.ogm.annotation.EndNode;
|
||||||
|
@ -20,5 +20,3 @@ public interface MovieRepository extends GraphRepository<Movie> {
|
|||||||
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
|
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
|
||||||
List<Map<String, Object>> graph(@Param("limit") int limit);
|
List<Map<String, Object>> graph(@Param("limit") int limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -4,7 +4,6 @@ import com.baeldung.spring.data.neo4j.domain.Person;
|
|||||||
import org.springframework.data.neo4j.repository.GraphRepository;
|
import org.springframework.data.neo4j.repository.GraphRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface PersonRepository extends GraphRepository<Person> {
|
public interface PersonRepository extends GraphRepository<Person> {
|
||||||
|
|
||||||
|
@ -82,8 +82,7 @@ public class MovieRepositoryTest {
|
|||||||
@DirtiesContext
|
@DirtiesContext
|
||||||
public void testFindAll() {
|
public void testFindAll() {
|
||||||
System.out.println("findAll");
|
System.out.println("findAll");
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||||
(Collection<Movie>) movieRepository.findAll();
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
}
|
}
|
||||||
@ -93,8 +92,7 @@ public class MovieRepositoryTest {
|
|||||||
public void testFindByTitleContaining() {
|
public void testFindByTitleContaining() {
|
||||||
System.out.println("findByTitleContaining");
|
System.out.println("findByTitleContaining");
|
||||||
String title = "Italian";
|
String title = "Italian";
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = movieRepository.findByTitleContaining(title);
|
||||||
movieRepository.findByTitleContaining(title);
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
}
|
}
|
||||||
@ -126,8 +124,7 @@ public class MovieRepositoryTest {
|
|||||||
public void testDeleteAll() {
|
public void testDeleteAll() {
|
||||||
System.out.println("deleteAll");
|
System.out.println("deleteAll");
|
||||||
movieRepository.deleteAll();
|
movieRepository.deleteAll();
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||||
(Collection<Movie>) movieRepository.findAll();
|
|
||||||
assertEquals(0, result.size());
|
assertEquals(0, result.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.spring.data.redis.queue;
|
package com.baeldung.spring.data.redis.queue;
|
||||||
|
|
||||||
|
|
||||||
public interface MessagePublisher {
|
public interface MessagePublisher {
|
||||||
|
|
||||||
void publish(final String message);
|
void publish(final String message);
|
||||||
|
@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher {
|
|||||||
public RedisMessagePublisher() {
|
public RedisMessagePublisher() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate,
|
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
|
||||||
final ChannelTopic topic) {
|
|
||||||
this.redisTemplate = redisTemplate;
|
this.redisTemplate = redisTemplate;
|
||||||
this.topic = topic;
|
this.topic = topic;
|
||||||
}
|
}
|
||||||
|
@ -9,8 +9,7 @@ public class HibernateUtil {
|
|||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public static Session getHibernateSession() {
|
public static Session getHibernateSession() {
|
||||||
|
|
||||||
final SessionFactory sf = new Configuration()
|
final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory();
|
||||||
.configure("criteria.cfg.xml").buildSessionFactory();
|
|
||||||
|
|
||||||
// factory = new Configuration().configure().buildSessionFactory();
|
// factory = new Configuration().configure().buildSessionFactory();
|
||||||
final Session session = sf.openSession();
|
final Session session = sf.openSession();
|
||||||
|
@ -226,8 +226,7 @@ public class ApplicationView {
|
|||||||
// Set projections Row Count
|
// Set projections Row Count
|
||||||
public Long[] projectionRowCount() {
|
public Long[] projectionRowCount() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount())
|
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
|
||||||
.list();
|
|
||||||
final Long projectedRowCount[] = new Long[itemProjected.size()];
|
final Long projectedRowCount[] = new Long[itemProjected.size()];
|
||||||
for (int i = 0; i < itemProjected.size(); i++) {
|
for (int i = 0; i < itemProjected.size(); i++) {
|
||||||
projectedRowCount[i] = itemProjected.get(i);
|
projectedRowCount[i] = itemProjected.get(i);
|
||||||
@ -239,8 +238,7 @@ public class ApplicationView {
|
|||||||
// Set projections average of itemPrice
|
// Set projections average of itemPrice
|
||||||
public Double[] projectionAverage() {
|
public Double[] projectionAverage() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List avgItemPriceList = session.createCriteria(Item.class)
|
final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
|
||||||
.setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
|
|
||||||
|
|
||||||
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
|
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
|
||||||
for (int i = 0; i < avgItemPriceList.size(); i++) {
|
for (int i = 0; i < avgItemPriceList.size(); i++) {
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user