fix conflicts
This commit is contained in:
commit
a74e46da82
|
@ -0,0 +1 @@
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
<?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>
|
||||
</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>**/ServiceTest</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>
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.cxf.jaxrs.implementation;
|
||||
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("baeldung")
|
||||
@Produces("text/xml")
|
||||
public class Baeldung {
|
||||
private Map<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/{courseOrder}")
|
||||
public Course getCourse(@PathParam("courseOrder") int courseOrder) {
|
||||
return courses.get(courseOrder);
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("courses/{courseOrder}")
|
||||
public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) {
|
||||
Course existingCourse = courses.get(courseOrder);
|
||||
|
||||
if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) {
|
||||
courses.put(courseOrder, course);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
return Response.notModified().build();
|
||||
}
|
||||
|
||||
@Path("courses/{courseOrder}/students")
|
||||
public Course pathToStudent(@PathParam("courseOrder") int courseOrder) {
|
||||
return courses.get(courseOrder);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.cxf.jaxrs.implementation;
|
||||
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@XmlRootElement(name = "Course")
|
||||
public class Course {
|
||||
private int id;
|
||||
private String name;
|
||||
private List<Student> students;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
|
||||
public void setStudents(List<Student> students) {
|
||||
this.students = students;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("{studentOrder}")
|
||||
public Student getStudent(@PathParam("studentOrder")int studentOrder) {
|
||||
return students.get(studentOrder);
|
||||
}
|
||||
|
||||
@POST
|
||||
public Response postStudent(Student student) {
|
||||
if (students == null) {
|
||||
students = new ArrayList<>();
|
||||
}
|
||||
students.add(student);
|
||||
return Response.ok(student).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("{studentOrder}")
|
||||
public Response deleteStudent(@PathParam("studentOrder") int studentOrder) {
|
||||
Student student = students.get(studentOrder);
|
||||
if (student != null) {
|
||||
students.remove(studentOrder);
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.notModified().build();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.cxf.jaxrs.implementation;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement(name = "Student")
|
||||
public class Student {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
<Course>
|
||||
<id>3</id>
|
||||
<name>Apache CXF Support for RESTful</name>
|
||||
</Course>
|
|
@ -0,0 +1,5 @@
|
|||
|
||||
<Student>
|
||||
<id>3</id>
|
||||
<name>Student C</name>
|
||||
</Student>
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.cxf.jaxrs.implementation;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.entity.InputStreamEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.xml.bind.JAXB;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ServiceTest {
|
||||
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
|
||||
private static CloseableHttpClient client;
|
||||
|
||||
@BeforeClass
|
||||
public static void createClient() {
|
||||
client = HttpClients.createDefault();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void closeClient() throws IOException {
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutCourse_thenCorrect() throws IOException {
|
||||
HttpPut httpPut = new HttpPut(BASE_URL + "3");
|
||||
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml");
|
||||
httpPut.setEntity(new InputStreamEntity(resourceStream));
|
||||
httpPut.setHeader("Content-Type", "text/xml");
|
||||
|
||||
HttpResponse response = client.execute(httpPut);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
|
||||
Course course = getCourse(3);
|
||||
assertEquals(3, course.getId());
|
||||
assertEquals("Apache CXF Support for RESTful", course.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostStudent_thenCorrect() throws IOException {
|
||||
HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
|
||||
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml");
|
||||
httpPost.setEntity(new InputStreamEntity(resourceStream));
|
||||
httpPost.setHeader("Content-Type", "text/xml");
|
||||
|
||||
HttpResponse response = client.execute(httpPost);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
|
||||
Student student = getStudent(2, 0);
|
||||
assertEquals(3, student.getId());
|
||||
assertEquals("Student C", student.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteStudent_thenCorrect() throws IOException {
|
||||
HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0");
|
||||
HttpResponse response = client.execute(httpDelete);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
|
||||
Course course = getCourse(1);
|
||||
assertEquals(1, course.getStudents().size());
|
||||
assertEquals(2, course.getStudents().get(0).getId());
|
||||
assertEquals("Student B", course.getStudents().get(0).getName());
|
||||
}
|
||||
|
||||
private Course getCourse(int courseOrder) throws IOException {
|
||||
URL url = new URL(BASE_URL + courseOrder);
|
||||
InputStream input = url.openStream();
|
||||
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
|
||||
}
|
||||
|
||||
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
|
||||
URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
|
||||
InputStream input = url.openStream();
|
||||
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
|
||||
}
|
||||
}
|
|
@ -8,6 +8,7 @@
|
|||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
<module>cxf-spring</module>
|
||||
<module>cxf-jaxrs-implementation</module>
|
||||
</modules>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
|
|
@ -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>
|
|
@ -15,7 +15,7 @@
|
|||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
<version>2.5</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
|
|
@ -1,17 +1,71 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomListElementTest {
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() {
|
||||
List<Integer> givenList = Arrays.asList(1, 2, 3);
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||
Random rand = new Random();
|
||||
|
||||
givenList.get(rand.nextInt(givenList.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||
|
||||
givenList.get((int)(Math.random() * givenList.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
|
||||
Random rand = new Random();
|
||||
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
|
||||
|
||||
int numberOfElements = 2;
|
||||
|
||||
for (int i = 0; i < numberOfElements; i++) {
|
||||
int randomIndex = rand.nextInt(givenList.size());
|
||||
givenList.get(randomIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
|
||||
Random rand = new Random();
|
||||
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
|
||||
|
||||
int numberOfElements = 2;
|
||||
|
||||
for (int i = 0; i < numberOfElements; i++) {
|
||||
int randomIndex = rand.nextInt(givenList.size());
|
||||
givenList.get(randomIndex);
|
||||
givenList.remove(randomIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
|
||||
Collections.shuffle(givenList);
|
||||
|
||||
int randomSeriesLength = 3;
|
||||
|
||||
givenList.subList(0, randomSeriesLength - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
|
||||
int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size();
|
||||
|
||||
givenList.get(randomIndex);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -1,17 +1,24 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class FileOperationsTest {
|
||||
|
||||
|
@ -20,34 +27,22 @@ public class FileOperationsTest {
|
|||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data, containsString(expectedData));
|
||||
}
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
|
||||
Class clazz = FileOperationsTest.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data, containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Baeldung";
|
||||
|
||||
URL urlObject = new URL("http://www.baeldung.com/");
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data, containsString(expectedData));
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -58,21 +53,69 @@ public class FileOperationsTest {
|
|||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data, containsString(expectedData));
|
||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Baeldung";
|
||||
|
||||
URL urlObject = new URL("http://www.baeldung.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
StringBuilder data = new StringBuilder();
|
||||
Stream<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();
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -174,7 +174,7 @@
|
|||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.7.2</jackson.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
package com.baeldung.java.regex;
|
||||
|
||||
public class Result {
|
||||
private boolean found = false;
|
||||
private int count = 0;
|
||||
|
||||
public Result() {
|
||||
|
||||
}
|
||||
|
||||
public boolean isFound() {
|
||||
return found;
|
||||
}
|
||||
|
||||
public void setFound(boolean found) {
|
||||
this.found = found;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -13,366 +13,368 @@ public class RegexTest {
|
|||
|
||||
@Test
|
||||
public void givenText_whenSimpleRegexMatches_thenCorrect() {
|
||||
Result result = runTest("foo", "foo");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
|
||||
Pattern pattern = Pattern.compile("foo");
|
||||
Matcher matcher = pattern.matcher("foo");
|
||||
assertTrue(matcher.find());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
|
||||
Result result = runTest("foo", "foofoo");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
Pattern pattern = Pattern.compile("foo");
|
||||
Matcher matcher = pattern.matcher("foofoo");
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
matches++;
|
||||
assertEquals(matches, 2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
|
||||
Result result = runTest(".", "foo");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest(".", "foo");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
|
||||
Result result = runTest("foo.", "foofoo");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("foo.", "foofoo");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAny_thenCorrect() {
|
||||
Result result = runTest("[abc]", "b");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("[abc]", "b");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
|
||||
Result result = runTest("[abc]", "cab");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("[abc]", "cab");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
|
||||
Result result = runTest("[bcr]at", "bat cat rat");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("[bcr]at", "bat cat rat");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNORSet_whenMatchesNon_thenCorrect() {
|
||||
Result result = runTest("[^abc]", "g");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("[^abc]", "g");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
|
||||
Result result = runTest("[^bcr]at", "sat mat eat");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("[^bcr]at", "sat mat eat");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
|
||||
Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
|
||||
Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 26);
|
||||
int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
|
||||
Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 28);
|
||||
int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 28);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
|
||||
Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
|
||||
Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
|
||||
Result result = runTest("[1-3[7-9]]", "123456789");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 6);
|
||||
int matches = runTest("[1-3[7-9]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
|
||||
Result result = runTest("[1-6&&[3-9]]", "123456789");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 4);
|
||||
int matches = runTest("[1-6&&[3-9]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
|
||||
Result result = runTest("[0-9&&[^2468]]", "123456789");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 5);
|
||||
int matches = runTest("[0-9&&[^2468]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDigits_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\d", "123");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("\\d", "123");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonDigits_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\D", "a6c");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("\\D", "a6c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhiteSpace_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\s", "a c");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("\\s", "a c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\S", "a c");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("\\S", "a c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWordCharacter_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\w", "hi!");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("\\w", "hi!");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonWordCharacter_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\W", "hi!");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("\\W", "hi!");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\a?", "hi");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("\\a?", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
|
||||
Result result = runTest("\\a{0,1}", "hi");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("\\a{0,1}", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\a*", "hi");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("\\a*", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||
Result result = runTest("\\a{0,}", "hi");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 3);
|
||||
int matches = runTest("\\a{0,}", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
|
||||
Result result = runTest("\\a+", "hi");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("\\a+", "hi");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||
Result result = runTest("\\a{1,}", "hi");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("\\a{1,}", "hi");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifier_whenMatches_thenCorrect() {
|
||||
Result result = runTest("a{3}", "aaaaaa");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("a{3}", "aaaaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
|
||||
Result result = runTest("a{3}", "aa");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("a{3}", "aa");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
|
||||
Result result = runTest("a{2,3}", "aaaa");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("a{2,3}", "aaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
|
||||
Result result = runTest("a{2,3}?", "aaaa");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("a{2,3}?", "aaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect() {
|
||||
Result result = runTest("(\\d\\d)", "12");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("(\\d\\d)", "12");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect2() {
|
||||
Result result = runTest("(\\d\\d)", "1212");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 2);
|
||||
int matches = runTest("(\\d\\d)", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect3() {
|
||||
Result result = runTest("(\\d\\d)(\\d\\d)", "1212");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
|
||||
Result result = runTest("(\\d\\d)\\1", "1212");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("(\\d\\d)\\1", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
|
||||
Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212");
|
||||
assertTrue(result.isFound());
|
||||
assertEquals(result.getCount(), 1);
|
||||
int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
|
||||
Result result = runTest("(\\d\\d)\\1", "1213");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("(\\d\\d)\\1", "1213");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtBeginning_thenCorrect() {
|
||||
Result result = runTest("^dog", "dogs are friendly");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("^dog", "dogs are friendly");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
|
||||
Result result = runTest("^dog", "are dogs are friendly?");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("^dog", "are dogs are friendly?");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtEnd_thenCorrect() {
|
||||
Result result = runTest("dog$", "Man's best friend is a dog");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("dog$", "Man's best friend is a dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
|
||||
Result result = runTest("dog$", "is a dog man's best friend?");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("dog$", "is a dog man's best friend?");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
|
||||
Result result = runTest("\\bdog\\b", "a dog is friendly");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("\\bdog\\b", "a dog is friendly");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
|
||||
Result result = runTest("\\bdog\\b", "dog is man's best friend");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("\\bdog\\b", "dog is man's best friend");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
|
||||
Result result = runTest("\\bdog\\b", "snoop dogg is a rapper");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
|
||||
Result result = runTest("\\bdog\\B", "snoop dogg is a rapper");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
|
||||
Result result = runTest("\u00E9", "\u0065\u0301");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("\u00E9", "\u0065\u0301");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
|
||||
Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
|
||||
Result result = runTest("dog", "This is a Dog");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("dog", "This is a Dog");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||
Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||
Result result = runTest("(?i)dog", "This is a Dog");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("(?i)dog", "This is a Dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
|
||||
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
|
||||
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
|
||||
Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -401,38 +403,38 @@ public class RegexTest {
|
|||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
|
||||
Result result = runTest("(.*)", "text");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("(.*)", "text");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
|
||||
Result result = runTest("(.*)", "text", Pattern.LITERAL);
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("(.*)", "text", Pattern.LITERAL);
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
|
||||
Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL);
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
|
||||
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertFalse(result.isFound());
|
||||
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
|
||||
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
|
||||
Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertTrue(result.isFound());
|
||||
int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -479,25 +481,22 @@ public class RegexTest {
|
|||
|
||||
}
|
||||
|
||||
public synchronized static Result runTest(String regex, String text) {
|
||||
public synchronized static int runTest(String regex, String text) {
|
||||
pattern = Pattern.compile(regex);
|
||||
matcher = pattern.matcher(text);
|
||||
Result result = new Result();
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
result.setCount(result.getCount() + 1);
|
||||
if (result.getCount() > 0)
|
||||
result.setFound(true);
|
||||
return result;
|
||||
matches++;
|
||||
return matches;
|
||||
}
|
||||
|
||||
public synchronized static Result runTest(String regex, String text, int flags) {
|
||||
public synchronized static int runTest(String regex, String text, int flags) {
|
||||
pattern = Pattern.compile(regex, flags);
|
||||
matcher = pattern.matcher(text);
|
||||
Result result = new Result();
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
result.setCount(result.getCount() + 1);
|
||||
if (result.getCount() > 0)
|
||||
result.setFound(true);
|
||||
return result;
|
||||
matches++;
|
||||
return matches;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
package org.baeldung.core.exceptions;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class FileNotFoundExceptionTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class);
|
||||
|
||||
private String fileName = Double.toString(Math.random());
|
||||
|
||||
@Test(expected = BusinessException.class)
|
||||
public void raiseBusinessSpecificException() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
throw new BusinessException("BusinessException: necessary file was not present.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFile() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
try {
|
||||
new File(fileName).createNewFile();
|
||||
readFailingFile();
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException("BusinessException: even creation is not possible.", ioe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logError() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
LOG.error("Optional file " + fileName + " was not found.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void readFailingFile() throws IOException {
|
||||
BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
|
||||
rd.readLine();
|
||||
// no need to close file
|
||||
}
|
||||
|
||||
private class BusinessException extends RuntimeException {
|
||||
BusinessException(String string, FileNotFoundException ex) {
|
||||
super(string, ex);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
hello world
|
Binary file not shown.
|
@ -1 +0,0 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
|
|
@ -1,15 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.7.3.201602250914-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[false]]></enableImports>
|
||||
<configs>
|
||||
</configs>
|
||||
<autoconfigs>
|
||||
</autoconfigs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
Binary file not shown.
|
@ -1 +0,0 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
|
|
@ -1,233 +0,0 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
#
|
||||
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
|
||||
# for the new JDKs provided by Oracle.
|
||||
#
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
|
||||
#
|
||||
# Oracle JDKs
|
||||
#
|
||||
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=`/usr/libexec/java_home`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Migwn, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
local basedir=$(pwd)
|
||||
local wdir=$(pwd)
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
wdir=$(cd "$wdir/.."; pwd)
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} "$@"
|
|
@ -1,145 +0,0 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
|
||||
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -1,40 +0,0 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>couchbase-sdk-intro</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk-intro</name>
|
||||
<description>Intro to the Couchbase SDK</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
||||
<dependency>
|
||||
<groupId>com.couchbase.client</groupId>
|
||||
<artifactId>java-client</artifactId>
|
||||
<version>${couchbase.client.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.7</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.2.6</couchbase.client.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Binary file not shown.
|
@ -1 +0,0 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
|
|
@ -1,233 +0,0 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
#
|
||||
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
|
||||
# for the new JDKs provided by Oracle.
|
||||
#
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
|
||||
#
|
||||
# Oracle JDKs
|
||||
#
|
||||
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=`/usr/libexec/java_home`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Migwn, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
local basedir=$(pwd)
|
||||
local wdir=$(pwd)
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
wdir=$(cd "$wdir/.."; pwd)
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} "$@"
|
|
@ -1,145 +0,0 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
|
||||
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -1,102 +0,0 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>couchbase-sdk-spring-service</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk-spring-service</name>
|
||||
<description>Intro to the Couchbase SDK</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
||||
<dependency>
|
||||
<groupId>com.couchbase.client</groupId>
|
||||
<artifactId>java-client</artifactId>
|
||||
<version>${couchbase.client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Context for Dependency Injection -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging with SLF4J & LogBack -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Test-Scoped Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.7</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.2.6</couchbase.client.version>
|
||||
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,31 +0,0 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.couchbase.service.JsonDocumentConverter;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
|
||||
@Service
|
||||
public class FluentPersonDocumentConverter implements JsonDocumentConverter<Person> {
|
||||
|
||||
@Override
|
||||
public JsonDocument toDocument(Person p) {
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("type", "Person")
|
||||
.put("name", p.getName())
|
||||
.put("homeTown", p.getHomeTown());
|
||||
return JsonDocument.create(p.getId(), content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Person fromDocument(JsonDocument doc) {
|
||||
JsonObject content = doc.content();
|
||||
return Person.Builder.newInstance()
|
||||
.id(doc.id())
|
||||
.type("Person")
|
||||
.name(content.getString("name"))
|
||||
.homeTown(content.getString("homeTown"))
|
||||
.build();
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="com.baeldung" level="DEBUG" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -1,9 +0,0 @@
|
|||
package com.baeldung.couchbase;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase"})
|
||||
public class IntegrationTestConfig {
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
## Couchbase SDK Tutorial Project
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk)
|
||||
- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
|
||||
- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
|
||||
|
||||
### Overview
|
||||
This Maven project contains the Java code for the Couchbase entities and Spring services
|
||||
as described in the tutorials, as well as a unit/integration test
|
||||
for each service implementation.
|
||||
|
||||
### Working with the Code
|
||||
The project was developed and tested using Java 7 and 8 in the Eclipse-based
|
||||
Spring Source Toolkit (STS) and therefore should run fine in any
|
||||
recent version of Eclipse or another IDE of your choice
|
||||
that supports Java 7 or later.
|
||||
|
||||
### Building the Project
|
||||
You can also build the project using Maven outside of any IDE:
|
||||
```
|
||||
mvn clean install
|
||||
```
|
||||
|
||||
### Package Organization
|
||||
Java classes for the intro tutorial are in the
|
||||
org.baeldung.couchbase.intro package.
|
||||
|
||||
Java classes for the Spring service tutorial are in the
|
||||
org.baeldung.couchbase.spring package hierarchy.
|
||||
|
||||
Java classes for the Asynchronous Couchbase tutorial are in the
|
||||
org.baeldung.couchbase.async package hierarchy.
|
||||
|
||||
|
||||
### Running the tests
|
||||
The test classes for the Spring service tutorial are:
|
||||
- org.baeldung.couchbase.spring.service.ClusterServiceTest
|
||||
- org.baeldung.couchbase.spring.person.PersonCrudServiceTest
|
||||
|
||||
The test classes for the Asynchronous Couchbase tutorial are in the
|
||||
org.baeldung.couchbase.async package hierarchy:
|
||||
- org.baeldung.couchbase.async.service.ClusterServiceTest
|
||||
- org.baeldung.couchbase.async.person.PersonCrudServiceTest
|
||||
|
||||
The test classes may be run as JUnit tests from your IDE
|
||||
or using the Maven command line:
|
||||
```
|
||||
mvn test
|
||||
```
|
|
@ -3,11 +3,11 @@
|
|||
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>couchbase-sdk-async</artifactId>
|
||||
<artifactId>couchbase-sdk</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk-async</name>
|
||||
<description>Couchbase SDK Asynchronous Operations</description>
|
||||
<name>couchbase-sdk</name>
|
||||
<description>Couchbase SDK Tutorials</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async;
|
||||
|
||||
public interface CouchbaseEntity {
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import com.baeldung.couchbase.service.CouchbaseEntity;
|
||||
import com.baeldung.couchbase.async.CouchbaseEntity;
|
||||
|
||||
public class Person implements CouchbaseEntity {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
|
@ -6,8 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.couchbase.service.AbstractCrudService;
|
||||
import com.baeldung.couchbase.service.BucketService;
|
||||
import com.baeldung.couchbase.async.service.AbstractCrudService;
|
||||
import com.baeldung.couchbase.async.service.BucketService;
|
||||
|
||||
@Service
|
||||
public class PersonCrudService extends AbstractCrudService<Person> {
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.couchbase.service.JsonDocumentConverter;
|
||||
import com.baeldung.couchbase.async.service.JsonDocumentConverter;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.couchbase.async.CouchbaseEntity;
|
||||
import com.couchbase.client.core.BackpressureException;
|
||||
import com.couchbase.client.core.time.Delay;
|
||||
import com.couchbase.client.java.AsyncBucket;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import java.util.List;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.examples;
|
||||
package com.baeldung.couchbase.intro;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
public class Person {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
@ -8,8 +8,9 @@ import javax.annotation.PostConstruct;
|
|||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.couchbase.service.CrudService;
|
||||
import com.baeldung.couchbase.service.TutorialBucketService;import com.couchbase.client.java.Bucket;
|
||||
import com.baeldung.couchbase.spring.service.CrudService;
|
||||
import com.baeldung.couchbase.spring.service.TutorialBucketService;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.ReplicaMode;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.couchbase.service.JsonDocumentConverter;
|
||||
import com.baeldung.couchbase.spring.service.JsonDocumentConverter;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import java.util.List;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
public interface CrudService<T> {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase;
|
||||
package com.baeldung.couchbase.async;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
|||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { IntegrationTestConfig.class })
|
||||
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public abstract class IntegrationTest {
|
||||
public abstract class AsyncIntegrationTest {
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.couchbase.async;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase.async"})
|
||||
public class AsyncIntegrationTestConfig {
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
@ -13,12 +13,15 @@ import org.junit.Test;
|
|||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
import com.baeldung.couchbase.IntegrationTest;
|
||||
import com.baeldung.couchbase.service.BucketService;
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTest;
|
||||
import com.baeldung.couchbase.async.person.Person;
|
||||
import com.baeldung.couchbase.async.person.PersonCrudService;
|
||||
import com.baeldung.couchbase.async.person.PersonDocumentConverter;
|
||||
import com.baeldung.couchbase.async.service.BucketService;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
||||
public class PersonCrudServiceTest extends IntegrationTest {
|
||||
public class PersonCrudServiceTest extends AsyncIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private PersonCrudService personService;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
@ -10,14 +10,15 @@ import org.springframework.test.context.TestExecutionListeners;
|
|||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
import com.baeldung.couchbase.IntegrationTest;
|
||||
import com.baeldung.couchbase.IntegrationTestConfig;
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTest;
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTestConfig;
|
||||
import com.baeldung.couchbase.async.service.ClusterService;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { IntegrationTestConfig.class })
|
||||
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public class ClusterServiceTest extends IntegrationTest {
|
||||
public class ClusterServiceTest extends AsyncIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ClusterService couchbaseService;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase;
|
||||
package com.baeldung.couchbase.spring;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
|
@ -1,9 +1,9 @@
|
|||
package com.baeldung.couchbase;
|
||||
package com.baeldung.couchbase.spring;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase"})
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase.spring"})
|
||||
public class IntegrationTestConfig {
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.person;
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
@ -8,7 +8,7 @@ import org.apache.commons.lang3.RandomStringUtils;
|
|||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import com.baeldung.couchbase.IntegrationTest;
|
||||
import com.baeldung.couchbase.spring.IntegrationTest;
|
||||
|
||||
public class PersonCrudServiceTest extends IntegrationTest {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.couchbase.service;
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
@ -10,8 +10,8 @@ import org.springframework.test.context.TestExecutionListeners;
|
|||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
import com.baeldung.couchbase.IntegrationTest;
|
||||
import com.baeldung.couchbase.IntegrationTestConfig;
|
||||
import com.baeldung.couchbase.spring.IntegrationTest;
|
||||
import com.baeldung.couchbase.spring.IntegrationTestConfig;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -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>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>18.0</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
|
@ -115,6 +115,7 @@
|
|||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
|
@ -221,8 +222,7 @@
|
|||
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<jackson.version>2.7.2</jackson.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue