Merge remote-tracking branch 'upstream/master'

# Conflicts:
#	spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java
This commit is contained in:
Ambrus Adrián-Zoltán 2016-10-23 21:52:39 +03:00
commit 9c60e4471a
588 changed files with 7906 additions and 5809 deletions

View File

@ -1 +1,2 @@
### Relevant Articles:
- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)

View File

@ -11,6 +11,7 @@
</parent>
<properties>
<cxf.version>3.1.6</cxf.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
@ -26,7 +27,7 @@
<version>2.19.1</version>
<configuration>
<excludes>
<exclude>**/StudentTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
@ -44,4 +45,5 @@
<version>${cxf.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -2,20 +2,16 @@ package com.baeldung.cxf.introduction;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
import com.baeldung.cxf.introduction.Baeldung;
import com.baeldung.cxf.introduction.Student;
import com.baeldung.cxf.introduction.StudentImpl;
import org.junit.Before;
import org.junit.Test;
public class StudentTest {
public class StudentLiveTest {
private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
@ -25,7 +21,7 @@ public class StudentTest {
{
service = Service.create(SERVICE_NAME);
String endpointAddress = "http://localhost:8080/baeldung";
final String endpointAddress = "http://localhost:8080/baeldung";
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
}
@ -37,28 +33,28 @@ public class StudentTest {
@Test
public void whenUsingHelloMethod_thenCorrect() {
String endpointResponse = baeldungProxy.hello("Baeldung");
String localResponse = baeldungImpl.hello("Baeldung");
final String endpointResponse = baeldungProxy.hello("Baeldung");
final String localResponse = baeldungImpl.hello("Baeldung");
assertEquals(localResponse, endpointResponse);
}
@Test
public void whenUsingHelloStudentMethod_thenCorrect() {
Student student = new StudentImpl("John Doe");
String endpointResponse = baeldungProxy.helloStudent(student);
String localResponse = baeldungImpl.helloStudent(student);
final Student student = new StudentImpl("John Doe");
final String endpointResponse = baeldungProxy.helloStudent(student);
final String localResponse = baeldungImpl.helloStudent(student);
assertEquals(localResponse, endpointResponse);
}
@Test
public void usingGetStudentsMethod_thenCorrect() {
Student student1 = new StudentImpl("Adam");
final Student student1 = new StudentImpl("Adam");
baeldungProxy.helloStudent(student1);
Student student2 = new StudentImpl("Eve");
final Student student2 = new StudentImpl("Eve");
baeldungProxy.helloStudent(student2);
Map<Integer, Student> students = baeldungProxy.getStudents();
final Map<Integer, Student> students = baeldungProxy.getStudents();
assertEquals("Adam", students.get(1).getName());
assertEquals("Eve", students.get(2).getName());
}

View File

@ -0,0 +1,55 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-jaxrs-implementation</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cxf.version>3.1.7</cxf.version>
<httpclient.version>4.5.2</httpclient.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.cxf.jaxrs.implementation.RestfulServer</mainClass>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,72 @@
package com.baeldung.cxf.jaxrs.implementation;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("baeldung")
@Produces("text/xml")
public class Baeldung {
private Map<Integer, Course> courses = new HashMap<>();
{
Student student1 = new Student();
Student student2 = new Student();
student1.setId(1);
student1.setName("Student A");
student2.setId(2);
student2.setName("Student B");
List<Student> course1Students = new ArrayList<>();
course1Students.add(student1);
course1Students.add(student2);
Course course1 = new Course();
Course course2 = new Course();
course1.setId(1);
course1.setName("REST with Spring");
course1.setStudents(course1Students);
course2.setId(2);
course2.setName("Learn Spring Security");
courses.put(1, course1);
courses.put(2, course2);
}
@GET
@Path("courses/{courseId}")
public Course getCourse(@PathParam("courseId") int courseId) {
return findById(courseId);
}
@PUT
@Path("courses/{courseId}")
public Response updateCourse(@PathParam("courseId") int courseId, Course course) {
Course existingCourse = findById(courseId);
if (existingCourse == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (existingCourse.equals(course)) {
return Response.notModified().build();
}
courses.put(courseId, course);
return Response.ok().build();
}
@Path("courses/{courseId}/students")
public Course pathToStudent(@PathParam("courseId") int courseId) {
return findById(courseId);
}
private Course findById(int id) {
for (Map.Entry<Integer, Course> course : courses.entrySet()) {
if (course.getKey() == id) {
return course.getValue();
}
}
return null;
}
}

View File

@ -0,0 +1,86 @@
package com.baeldung.cxf.jaxrs.implementation;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "Course")
public class Course {
private int id;
private String name;
private List<Student> students = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@GET
@Path("{studentId}")
public Student getStudent(@PathParam("studentId") int studentId) {
return findById(studentId);
}
@POST
public Response createStudent(Student student) {
for (Student element : students) {
if (element.getId() == student.getId()) {
return Response.status(Response.Status.CONFLICT).build();
}
}
students.add(student);
return Response.ok(student).build();
}
@DELETE
@Path("{studentId}")
public Response deleteStudent(@PathParam("studentId") int studentId) {
Student student = findById(studentId);
if (student == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
students.remove(student);
return Response.ok().build();
}
private Student findById(int id) {
for (Student student : students) {
if (student.getId() == id) {
return student;
}
}
return null;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName()));
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.cxf.jaxrs.implementation;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
public class RestfulServer {
public static void main(String args[]) throws Exception {
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
factoryBean.setResourceClasses(Baeldung.class);
factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung()));
factoryBean.setAddress("http://localhost:8080/");
Server server = factoryBean.create();
System.out.println("Server ready...");
Thread.sleep(60 * 1000);
System.out.println("Server exiting");
server.destroy();
System.exit(0);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.cxf.jaxrs.implementation;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName()));
}
}

View File

@ -0,0 +1,4 @@
<Course>
<id>2</id>
<name>Apache CXF Support for RESTful</name>
</Course>

View File

@ -0,0 +1,4 @@
<Student>
<id>2</id>
<name>Student B</name>
</Student>

View File

@ -0,0 +1,4 @@
<Student>
<id>3</id>
<name>Student C</name>
</Student>

View File

@ -0,0 +1,4 @@
<Course>
<id>3</id>
<name>Apache CXF Support for RESTful</name>
</Course>

View File

@ -0,0 +1,4 @@
<Course>
<id>1</id>
<name>REST with Spring</name>
</Course>

View File

@ -0,0 +1,130 @@
package com.baeldung.cxf.jaxrs.implementation;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.bind.JAXB;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class ServiceLiveTest {
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
private static CloseableHttpClient client;
@BeforeClass
public static void createClient() {
client = HttpClients.createDefault();
}
@AfterClass
public static void closeClient() throws IOException {
client.close();
}
@Test
public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "3");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "1");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(304, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "2");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(2);
assertEquals(2, course.getId());
assertEquals("Apache CXF Support for RESTful", course.getName());
}
@Test
public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "1/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(409, response.getStatusLine().getStatusCode());
}
@Test
public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(200, response.getStatusLine().getStatusCode());
final Student student = getStudent(2, 3);
assertEquals(3, student.getId());
assertEquals("Student C", student.getName());
}
@Test
public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3");
final HttpResponse response = client.execute(httpDelete);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1");
final HttpResponse response = client.execute(httpDelete);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(1);
assertEquals(1, course.getStudents().size());
assertEquals(2, course.getStudents().get(0).getId());
assertEquals("Student B", course.getStudents().get(0).getName());
}
private Course getCourse(int courseOrder) throws IOException {
final URL url = new URL(BASE_URL + courseOrder);
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
}
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
}
}

View File

@ -51,7 +51,7 @@
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>StudentTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
@ -60,7 +60,7 @@
<profiles>
<profile>
<id>integration</id>
<id>live</id>
<build>
<plugins>
<plugin>

View File

@ -6,7 +6,7 @@ import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class StudentTest {
public class StudentLiveTest {
private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private Baeldung baeldungProxy = (Baeldung) context.getBean("client");

View File

@ -8,6 +8,7 @@
<modules>
<module>cxf-introduction</module>
<module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module>
</modules>
<dependencies>
<dependency>

3
assertj/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [AssertJs Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)

View File

@ -1,7 +1,6 @@
<?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>
<groupId>com.baeldung</groupId>
@ -9,11 +8,18 @@
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -26,11 +32,7 @@
<version>3.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
@ -46,4 +48,9 @@
</plugin>
</plugins>
</build>
<properties>
<guava.version>19.0</guava.version>
</properties>
</project>

2
autovalue/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)

2
cdi/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)

View File

@ -45,8 +45,60 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<spring.version>4.3.1.RELEASE</spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -16,7 +16,7 @@ import com.baeldung.spring.service.SpringSuperService;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
public class TestSpringInterceptor {
public class SpringInterceptorIntegrationTest {
@Autowired
SpringSuperService springSuperService;

View File

@ -11,11 +11,8 @@
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Guide to Java 8s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)

View File

@ -15,7 +15,7 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<version>2.5</version>
</dependency>
<dependency>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)

View File

@ -0,0 +1,84 @@
package com.baeldung.encoderdecoder;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class EncoderDecoder {
private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class);
private String encodeValue(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return encoded;
}
private String decode(String value) {
String decoded = null;
try {
decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return decoded;
}
@Test
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
URL url = new URL(URL);
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
}
@Test
public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
Map<String, String> requestParams = new HashMap<>();
requestParams.put("key1", "value 1");
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String encodedQuery = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(Collectors.joining("&"));
String encodedURL = "http://www.baeldung.com?" + encodedQuery;
Assert.assertThat(URL, CoreMatchers.is(encodedURL));
}
@Test
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
URL url = new URL(URL);
String query = url.getQuery();
String decodedQuery = Arrays.stream(query.split("&"))
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
.collect(Collectors.joining("&"));
Assert.assertEquals(
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
}
}

View File

@ -102,22 +102,20 @@ public class FileOperationsTest {
StringBuilder data = new StringBuilder();
Stream<String> lines = Files.lines(path);
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
Assert.assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder resultStringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line);
resultStringBuilder.append("\n");
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return resultStringBuilder.toString();
}
}

View File

@ -1,47 +1,41 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import java.time.*;
import java.time.temporal.ChronoField;
import static org.junit.Assert.assertEquals;
public class CurrentDateTimeTest {
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now();
final Calendar calendar = GregorianCalendar.getInstance();
final LocalDate now = LocalDate.now(clock);
assertEquals("10-10-2010".length(), now.toString().length());
assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH));
assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1);
assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
assertEquals(2016, now.get(ChronoField.YEAR));
}
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now();
final Calendar calendar = GregorianCalendar.getInstance();
final LocalTime now = LocalTime.now(clock);
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY));
assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE));
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
}
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now();
final Calendar calendar = GregorianCalendar.getInstance();
final Instant now = Instant.now(clock);
assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}

View File

@ -1 +1,2 @@
### Relevant Artiles:
- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)

View File

@ -13,3 +13,12 @@
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
- [Guide to Java 8s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)

View File

@ -1,211 +1,321 @@
<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>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<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>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java</name>
<name>core-java</name>
<dependencies>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<!-- web -->
<!-- web -->
<!-- marshalling -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</dependencies>
<plugins>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</build>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- marshalling -->
<jackson.version>2.7.2</jackson.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<!-- 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>
</build>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- marshalling -->
<jackson.version>2.7.8</jackson.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
</properties>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.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>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -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;
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.java.nio.selector;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
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();
}
}
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = EchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.printscreen;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Screenshot {
private final String path;
public Screenshot(String path) {
this.path = path;
}
public void getScreenshot(int timeToWait) throws Exception {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));
}
}

View File

@ -23,8 +23,7 @@ public class EchoClient {
public String sendMessage(String msg) {
try {
out.println(msg);
String resp = in.readLine();
return resp;
return in.readLine();
} catch (Exception e) {
return null;
}

View File

@ -26,8 +26,7 @@ public class GreetClient {
public String sendMessage(String msg) {
try {
out.println(msg);
String resp = in.readLine();
return resp;
return in.readLine();
} catch (Exception e) {
return null;
}

View File

@ -0,0 +1,11 @@
package org.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}

View File

@ -1,5 +1,8 @@
package com.baeldung.functionalinterface;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@ -10,9 +13,6 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Test;
import static org.junit.Assert.*;
public class FunctionalInterfaceTest {

View File

@ -0,0 +1,21 @@
package com.baeldung.java.nio.selector;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
public class EchoTest {
@Test
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
Process process = EchoServer.start();
EchoClient client = EchoClient.start();
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
assertEquals("world", resp2);
process.destroy();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.printscreen;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertTrue;
public class ScreenshotTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg");
@Test
public void testGetScreenshot() throws Exception {
screenshot.getScreenshot(2000);
assertTrue(file.exists());
}
@After
public void tearDown() throws Exception {
file.delete();
}
}

View File

@ -1,7 +1,6 @@
package com.baeldung.socket;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Executors;
@ -10,18 +9,22 @@ import static org.junit.Assert.assertEquals;
public class EchoMultiTest {
{
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555));
}
private static final Integer PORT = 5555;
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT));
Thread.sleep(500);
}
@Test
public void givenClient1_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555);
client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
assertEquals(msg1, "hello");
assertEquals(msg2, "world");
assertEquals(terminate, "bye");
@ -31,7 +34,7 @@ public class EchoMultiTest {
@Test
public void givenClient2_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555);
client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
@ -44,7 +47,7 @@ public class EchoMultiTest {
@Test
public void givenClient3_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555);
client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
@ -53,5 +56,4 @@ public class EchoMultiTest {
assertEquals(terminate, "bye");
client.stopConnection();
}
}

View File

@ -2,6 +2,7 @@ package com.baeldung.socket;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Executors;
@ -9,15 +10,19 @@ import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
public class EchoTest {
{
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444));
}
private static final Integer PORT = 4444;
EchoClient client = new EchoClient();
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
Thread.sleep(500);
}
private EchoClient client = new EchoClient();
@Before
public void init() {
client.startConnection("127.0.0.1", 4444);
client.startConnection("127.0.0.1", PORT);
}
@Test
@ -37,5 +42,4 @@ public class EchoTest {
public void tearDown() {
client.stopConnection();
}
}

View File

@ -2,6 +2,7 @@ package com.baeldung.socket;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Executors;
@ -10,16 +11,20 @@ import static org.junit.Assert.assertEquals;
public class GreetServerTest {
GreetClient client;
private GreetClient client;
{
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666));
private static final Integer PORT = 6666;
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
Thread.sleep(500);
}
@Before
public void init() {
client = new GreetClient();
client.startConnection("127.0.0.1", 6666);
client.startConnection("127.0.0.1", PORT);
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)

2
dozer/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Mapping With Dozer](http://www.baeldung.com/dozer)

View File

@ -3,3 +3,6 @@
This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api
###Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign)

View File

@ -1 +0,0 @@

View File

@ -1,4 +1,4 @@
.classpath
.project
.settings
.classpath
.project
.settings
target/

2
flyway/README.MD Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)

View File

@ -1,8 +1,8 @@
CREATE TABLE IF NOT EXISTS `employee` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20),
`email` varchar(50),
`date_of_birth` timestamp
CREATE TABLE IF NOT EXISTS `employee` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20),
`email` varchar(50),
`date_of_birth` timestamp
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;

View File

@ -1,8 +1,8 @@
CREATE TABLE IF NOT EXISTS `department` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `department` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
ALTER TABLE `employee` ADD `dept_id` int AFTER `email`;

View File

@ -1,5 +1,5 @@
flyway.user=root
flyway.password=mysql
flyway.schemas=app-db
flyway.url=jdbc:mysql://localhost:3306/
flyway.user=root
flyway.password=mysql
flyway.schemas=app-db
flyway.url=jdbc:mysql://localhost:3306/
flyway.locations=filesystem:db/migration

View File

@ -1,34 +1,34 @@
<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>flyway-migration</artifactId>
<version>1.0</version>
<name>flyway-migration</name>
<description>A sample project to demonstrate Flyway migrations</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>4.0.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<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>flyway</artifactId>
<version>1.0</version>
<name>flyway</name>
<description>A sample project to demonstrate Flyway migrations</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>4.0.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

2
gatling/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling)

View File

@ -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.

View File

@ -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>

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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

View File

@ -5,3 +5,4 @@
### Relevant Articles:
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)

View File

@ -19,7 +19,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>

View File

@ -15,3 +15,4 @@
- [Guava Lists](http://www.baeldung.com/guava-lists)
- [Guava Sets](http://www.baeldung.com/guava-sets)
- [Guava Maps](http://www.baeldung.com/guava-maps)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)

View File

@ -1,7 +1,6 @@
<?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>
<groupId>com.baeldung</groupId>
@ -14,12 +13,15 @@
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>

View File

@ -1,5 +1,6 @@
<?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>
<groupId>com.baeldung</groupId>
@ -10,20 +11,23 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -42,4 +46,8 @@
</plugins>
</build>
<properties>
<guava.version>19.0</guava.version>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More