Resolving merge conflict
This commit is contained in:
commit
2f1ea093c4
50
annotations/annotation-processing/pom.xml
Normal file
50
annotations/annotation-processing/pom.xml
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<artifactId>annotations</artifactId>
|
||||||
|
<relativePath>../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>annotation-processing</artifactId>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<auto-service.version>1.0-rc2</auto-service.version>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.auto.service</groupId>
|
||||||
|
<artifactId>auto-service</artifactId>
|
||||||
|
<version>${auto-service.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,132 @@
|
|||||||
|
package com.baeldung.annotation.processor;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import javax.annotation.processing.*;
|
||||||
|
import javax.lang.model.SourceVersion;
|
||||||
|
import javax.lang.model.element.Element;
|
||||||
|
import javax.lang.model.element.TypeElement;
|
||||||
|
import javax.lang.model.type.ExecutableType;
|
||||||
|
import javax.tools.Diagnostic;
|
||||||
|
import javax.tools.JavaFileObject;
|
||||||
|
|
||||||
|
import com.google.auto.service.AutoService;
|
||||||
|
|
||||||
|
@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty")
|
||||||
|
@SupportedSourceVersion(SourceVersion.RELEASE_8)
|
||||||
|
@AutoService(Processor.class)
|
||||||
|
public class BuilderProcessor extends AbstractProcessor {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||||
|
for (TypeElement annotation : annotations) {
|
||||||
|
|
||||||
|
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||||
|
|
||||||
|
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
||||||
|
.collect(Collectors.partitioningBy(element ->
|
||||||
|
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
||||||
|
&& element.getSimpleName().toString().startsWith("set")));
|
||||||
|
|
||||||
|
List<Element> setters = annotatedMethods.get(true);
|
||||||
|
List<Element> otherMethods = annotatedMethods.get(false);
|
||||||
|
|
||||||
|
otherMethods.forEach(element ->
|
||||||
|
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
||||||
|
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||||
|
|
||||||
|
if (setters.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||||
|
|
||||||
|
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
||||||
|
setter -> setter.getSimpleName().toString(),
|
||||||
|
setter -> ((ExecutableType) setter.asType())
|
||||||
|
.getParameterTypes().get(0).toString()
|
||||||
|
));
|
||||||
|
|
||||||
|
try {
|
||||||
|
writeBuilderFile(className, setterMap);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeBuilderFile(String className, Map<String, String> setterMap) throws IOException {
|
||||||
|
|
||||||
|
String packageName = null;
|
||||||
|
int lastDot = className.lastIndexOf('.');
|
||||||
|
if (lastDot > 0) {
|
||||||
|
packageName = className.substring(0, lastDot);
|
||||||
|
}
|
||||||
|
|
||||||
|
String simpleClassName = className.substring(lastDot + 1);
|
||||||
|
String builderClassName = className + "Builder";
|
||||||
|
String builderSimpleClassName = builderClassName.substring(lastDot + 1);
|
||||||
|
|
||||||
|
JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName);
|
||||||
|
try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
|
||||||
|
|
||||||
|
if (packageName != null) {
|
||||||
|
out.print("package ");
|
||||||
|
out.print(packageName);
|
||||||
|
out.println(";");
|
||||||
|
out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
out.print("public class ");
|
||||||
|
out.print(builderSimpleClassName);
|
||||||
|
out.println(" {");
|
||||||
|
out.println();
|
||||||
|
|
||||||
|
out.print(" private ");
|
||||||
|
out.print(simpleClassName);
|
||||||
|
out.print(" object = new ");
|
||||||
|
out.print(simpleClassName);
|
||||||
|
out.println("();");
|
||||||
|
out.println();
|
||||||
|
|
||||||
|
out.print(" public ");
|
||||||
|
out.print(simpleClassName);
|
||||||
|
out.println(" build() {");
|
||||||
|
out.println(" return object;");
|
||||||
|
out.println(" }");
|
||||||
|
out.println();
|
||||||
|
|
||||||
|
setterMap.entrySet().forEach(setter -> {
|
||||||
|
String methodName = setter.getKey();
|
||||||
|
String argumentType = setter.getValue();
|
||||||
|
|
||||||
|
out.print(" public ");
|
||||||
|
out.print(builderSimpleClassName);
|
||||||
|
out.print(" ");
|
||||||
|
out.print(methodName);
|
||||||
|
|
||||||
|
out.print("(");
|
||||||
|
|
||||||
|
out.print(argumentType);
|
||||||
|
out.println(" value) {");
|
||||||
|
out.print(" object.");
|
||||||
|
out.print(methodName);
|
||||||
|
out.println("(value);");
|
||||||
|
out.println(" return this;");
|
||||||
|
out.println(" }");
|
||||||
|
out.println();
|
||||||
|
});
|
||||||
|
|
||||||
|
out.println("}");
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.annotation.processor;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
@Retention(RetentionPolicy.SOURCE)
|
||||||
|
public @interface BuilderProperty {
|
||||||
|
}
|
51
annotations/annotation-user/pom.xml
Normal file
51
annotations/annotation-user/pom.xml
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>annotations</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>annotation-user</artifactId>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>annotation-processing</artifactId>
|
||||||
|
<version>${project.parent.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.annotation;
|
||||||
|
|
||||||
|
import com.baeldung.annotation.processor.BuilderProperty;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@BuilderProperty
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@BuilderProperty
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.annotation;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class PersonBuilderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||||
|
|
||||||
|
Person person = new PersonBuilder()
|
||||||
|
.setAge(25)
|
||||||
|
.setName("John")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(25, person.getAge());
|
||||||
|
assertEquals("John", person.getName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
20
annotations/pom.xml
Normal file
20
annotations/pom.xml
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
<?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">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>annotations</artifactId>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>annotation-processing</module>
|
||||||
|
<module>annotation-user</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
</project>
|
1
annotations/readme.md
Normal file
1
annotations/readme.md
Normal file
@ -0,0 +1 @@
|
|||||||
|
|
54
apache-cxf/cxf-jaxrs-implementation/pom.xml
Normal file
54
apache-cxf/cxf-jaxrs-implementation/pom.xml
Normal file
@ -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,68 @@
|
|||||||
|
package com.baeldung.cxf.jaxrs.implementation;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
@Path("baeldung")
|
||||||
|
@Produces("text/xml")
|
||||||
|
public class Baeldung {
|
||||||
|
private Map<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);
|
||||||
|
Response response;
|
||||||
|
if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) {
|
||||||
|
courses.put(courseOrder, course);
|
||||||
|
response = Response.ok().build();
|
||||||
|
} else {
|
||||||
|
response = Response.notModified().build();
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Path("courses/{courseOrder}/students")
|
||||||
|
public Course pathToStudent(@PathParam("courseOrder") int courseOrder) {
|
||||||
|
return courses.get(courseOrder);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,73 @@
|
|||||||
|
package com.baeldung.cxf.jaxrs.implementation;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
import javax.xml.bind.annotation.XmlRootElement;
|
||||||
|
|
||||||
|
@XmlRootElement(name = "Course")
|
||||||
|
public class Course {
|
||||||
|
private int id;
|
||||||
|
private String name;
|
||||||
|
private List<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<Student>();
|
||||||
|
}
|
||||||
|
students.add(student);
|
||||||
|
return Response.ok(student).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@DELETE
|
||||||
|
@Path("{studentOrder}")
|
||||||
|
public Response deleteStudent(@PathParam("studentOrder") int studentOrder) {
|
||||||
|
Student student = students.get(studentOrder);
|
||||||
|
Response response;
|
||||||
|
if (student != null) {
|
||||||
|
students.remove(studentOrder);
|
||||||
|
response = Response.ok().build();
|
||||||
|
} else {
|
||||||
|
response = Response.notModified().build();
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
@ -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,93 @@
|
|||||||
|
package com.baeldung.cxf.jaxrs.implementation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import javax.xml.bind.JAXB;
|
||||||
|
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpDelete;
|
||||||
|
import org.apache.http.client.methods.HttpPost;
|
||||||
|
import org.apache.http.client.methods.HttpPut;
|
||||||
|
import org.apache.http.entity.InputStreamEntity;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
|
||||||
|
public class ServiceTest {
|
||||||
|
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
|
||||||
|
private static CloseableHttpClient client;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void createClient() {
|
||||||
|
client = HttpClients.createDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void closeClient() throws IOException {
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPutCourse_thenCorrect() throws IOException {
|
||||||
|
HttpPut httpPut = new HttpPut(BASE_URL + "3");
|
||||||
|
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml");
|
||||||
|
httpPut.setEntity(new InputStreamEntity(resourceStream));
|
||||||
|
httpPut.setHeader("Content-Type", "text/xml");
|
||||||
|
|
||||||
|
HttpResponse response = client.execute(httpPut);
|
||||||
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
|
Course course = getCourse(3);
|
||||||
|
assertEquals(3, course.getId());
|
||||||
|
assertEquals("Apache CXF Support for RESTful", course.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPostStudent_thenCorrect() throws IOException {
|
||||||
|
HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
|
||||||
|
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml");
|
||||||
|
httpPost.setEntity(new InputStreamEntity(resourceStream));
|
||||||
|
httpPost.setHeader("Content-Type", "text/xml");
|
||||||
|
|
||||||
|
HttpResponse response = client.execute(httpPost);
|
||||||
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
|
Student student = getStudent(2, 0);
|
||||||
|
assertEquals(3, student.getId());
|
||||||
|
assertEquals("Student C", student.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDeleteStudent_thenCorrect() throws IOException {
|
||||||
|
HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0");
|
||||||
|
HttpResponse response = client.execute(httpDelete);
|
||||||
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
|
Course course = getCourse(1);
|
||||||
|
assertEquals(1, course.getStudents().size());
|
||||||
|
assertEquals(2, course.getStudents().get(0).getId());
|
||||||
|
assertEquals("Student B", course.getStudents().get(0).getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Course getCourse(int courseOrder) throws IOException {
|
||||||
|
URL url = new URL(BASE_URL + courseOrder);
|
||||||
|
InputStream input = url.openStream();
|
||||||
|
Course course = JAXB.unmarshal(new InputStreamReader(input), Course.class);
|
||||||
|
return course;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
|
||||||
|
URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
|
||||||
|
InputStream input = url.openStream();
|
||||||
|
Student student = JAXB.unmarshal(new InputStreamReader(input), Student.class);
|
||||||
|
return student;
|
||||||
|
}
|
||||||
|
}
|
@ -8,6 +8,7 @@
|
|||||||
<modules>
|
<modules>
|
||||||
<module>cxf-introduction</module>
|
<module>cxf-introduction</module>
|
||||||
<module>cxf-spring</module>
|
<module>cxf-spring</module>
|
||||||
|
<module>cxf-jaxrs-implementation</module>
|
||||||
</modules>
|
</modules>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@ -9,11 +8,18 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>19.0</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-guava</artifactId>
|
||||||
|
<version>3.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
@ -26,11 +32,7 @@
|
|||||||
<version>3.5.1</version>
|
<version>3.5.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-guava</artifactId>
|
|
||||||
<version>3.0.0</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -46,4 +48,9 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<guava.version>19.0</guava.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -12,3 +12,13 @@
|
|||||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||||
|
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||||
|
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||||
|
- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
|
||||||
|
- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
|
||||||
|
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
||||||
|
- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||||
|
- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)
|
||||||
|
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||||
|
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||||
|
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<artifactId>core-java8</artifactId>
|
<artifactId>core-java8</artifactId>
|
||||||
<version>0.1-SNAPSHOT</version>
|
|
||||||
|
|
||||||
<name>core-java8</name>
|
<name>core-java8</name>
|
||||||
|
|
||||||
@ -14,7 +15,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>2.4</version>
|
<version>2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -111,6 +112,9 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
<logback.version>1.0.13</logback.version>
|
<logback.version>1.0.13</logback.version>
|
||||||
|
1
core-java-8/src/main/resources/fileTest.txt
Normal file
1
core-java-8/src/main/resources/fileTest.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
Hello World from fileTest.txt!!!
|
@ -1,17 +1,71 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.*;
|
||||||
import java.util.List;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
import java.util.Random;
|
|
||||||
|
|
||||||
public class RandomListElementTest {
|
public class RandomListElementTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
||||||
List<Integer> givenList = Arrays.asList(1, 2, 3);
|
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||||
Random rand = new Random();
|
Random rand = new Random();
|
||||||
|
|
||||||
givenList.get(rand.nextInt(givenList.size()));
|
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));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,121 @@
|
|||||||
|
package com.baeldung.file;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.hamcrest.CoreMatchers;
|
||||||
|
import org.hamcrest.Matchers;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class FileOperationsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||||
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
|
InputStream inputStream = new FileInputStream(file);
|
||||||
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||||
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
|
Class clazz = FileOperationsTest.class;
|
||||||
|
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||||
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||||
|
String expectedData = "BSD License";
|
||||||
|
|
||||||
|
Class clazz = Matchers.class;
|
||||||
|
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||||
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
|
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||||
|
String expectedData = "Baeldung";
|
||||||
|
|
||||||
|
URL urlObject = new URL("http://www.baeldung.com/");
|
||||||
|
|
||||||
|
URLConnection urlConnection = urlObject.openConnection();
|
||||||
|
|
||||||
|
InputStream inputStream = urlConnection.getInputStream();
|
||||||
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
|
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||||
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
|
String data = FileUtils.readFileToString(file);
|
||||||
|
|
||||||
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||||
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
|
byte[] fileBytes = Files.readAllBytes(path);
|
||||||
|
String data = new String(fileBytes);
|
||||||
|
|
||||||
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||||
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
|
StringBuilder data = new StringBuilder();
|
||||||
|
Stream<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 {
|
||||||
|
StringBuilder resultStringBuilder = new StringBuilder();
|
||||||
|
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||||
|
String line;
|
||||||
|
while ((line = bufferedReader.readLine()) != null) {
|
||||||
|
resultStringBuilder.append(line).append("\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultStringBuilder.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -21,7 +21,7 @@ public class JavaFolderSizeTest {
|
|||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
final String separator = File.separator;
|
final String separator = File.separator;
|
||||||
path = "src" + separator + "test" + separator + "resources";
|
path = String.format("src%stest%sresources", separator, separator);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -79,7 +79,9 @@ public class JavaFolderSizeTest {
|
|||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
|
|
||||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum();
|
final long size = StreamSupport.stream(files.spliterator(), false)
|
||||||
|
.filter(File::isFile)
|
||||||
|
.mapToLong(File::length).sum();
|
||||||
|
|
||||||
assertEquals(expectedSize, size);
|
assertEquals(expectedSize, size);
|
||||||
}
|
}
|
||||||
@ -101,13 +103,11 @@ public class JavaFolderSizeTest {
|
|||||||
long length = 0;
|
long length = 0;
|
||||||
final File[] files = folder.listFiles();
|
final File[] files = folder.listFiles();
|
||||||
|
|
||||||
final int count = files.length;
|
for (File file : files) {
|
||||||
|
if (file.isFile()) {
|
||||||
for (int i = 0; i < count; i++) {
|
length += file.length();
|
||||||
if (files[i].isFile()) {
|
|
||||||
length += files[i].length();
|
|
||||||
} else {
|
} else {
|
||||||
length += getFolderSize(files[i]);
|
length += getFolderSize(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return length;
|
return length;
|
||||||
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.util;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.*;
|
||||||
|
import java.time.temporal.ChronoField;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class CurrentDateTimeTest {
|
||||||
|
|
||||||
|
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturnCurrentDate() {
|
||||||
|
|
||||||
|
final LocalDate now = LocalDate.now(clock);
|
||||||
|
|
||||||
|
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(2016, now.get(ChronoField.YEAR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturnCurrentTime() {
|
||||||
|
|
||||||
|
final LocalTime now = LocalTime.now(clock);
|
||||||
|
|
||||||
|
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturnCurrentTimestamp() {
|
||||||
|
|
||||||
|
final Instant now = Instant.now(clock);
|
||||||
|
|
||||||
|
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||||
|
}
|
||||||
|
}
|
1
core-java-8/src/test/resources/test.txt
Normal file
1
core-java-8/src/test/resources/test.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat.
|
5
core-java-9/README.md
Normal file
5
core-java-9/README.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
=========
|
||||||
|
|
||||||
|
## Core Java 9 Examples
|
||||||
|
|
||||||
|
http://inprogress.baeldung.com/java-9-new-features/
|
93
core-java-9/pom.xml
Normal file
93
core-java-9/pom.xml
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>core-java9</artifactId>
|
||||||
|
<version>0.2-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<name>core-java9</name>
|
||||||
|
|
||||||
|
<pluginRepositories>
|
||||||
|
<pluginRepository>
|
||||||
|
<id>apache.snapshots</id>
|
||||||
|
<url>http://repository.apache.org/snapshots/</url>
|
||||||
|
</pluginRepository>
|
||||||
|
</pluginRepositories>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest-library</artifactId>
|
||||||
|
<version>${org.hamcrest.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<version>${mockito.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-9</finalName>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.9</source>
|
||||||
|
<target>1.9</target>
|
||||||
|
<verbose>true</verbose>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- logging -->
|
||||||
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
<logback.version>1.0.13</logback.version>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- maven plugins -->
|
||||||
|
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
|
<!-- testing -->
|
||||||
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
|
public interface PrivateInterface {
|
||||||
|
|
||||||
|
private static String staticPrivate() {
|
||||||
|
return "static private";
|
||||||
|
}
|
||||||
|
|
||||||
|
private String instancePrivate() {
|
||||||
|
return "instance private";
|
||||||
|
}
|
||||||
|
|
||||||
|
public default void check(){
|
||||||
|
String result = staticPrivate();
|
||||||
|
if (!result.equals("static private"))
|
||||||
|
throw new AssertionError("Incorrect result for static private interface method");
|
||||||
|
PrivateInterface pvt = new PrivateInterface() {
|
||||||
|
};
|
||||||
|
result = pvt.instancePrivate();
|
||||||
|
if (!result.equals("instance private"))
|
||||||
|
throw new AssertionError("Incorrect result for instance private interface method");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.java9.process;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
|
||||||
|
public class ProcessUtils {
|
||||||
|
|
||||||
|
public static String getClassPath(){
|
||||||
|
String cp = System.getProperty("java.class.path");
|
||||||
|
System.out.println("ClassPath is "+cp);
|
||||||
|
return cp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static File getJavaCmd() throws IOException{
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
File javaCmd;
|
||||||
|
if(System.getProperty("os.name").startsWith("Win")){
|
||||||
|
javaCmd = new File(javaHome, "bin/java.exe");
|
||||||
|
}else{
|
||||||
|
javaCmd = new File(javaHome, "bin/java");
|
||||||
|
}
|
||||||
|
if(javaCmd.canExecute()){
|
||||||
|
return javaCmd;
|
||||||
|
}else{
|
||||||
|
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getMainClass(){
|
||||||
|
return System.getProperty("sun.java.command");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getSystemProperties(){
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.java9.process;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class ServiceMain {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws InterruptedException {
|
||||||
|
ProcessHandle thisProcess = ProcessHandle.current();
|
||||||
|
long pid = thisProcess.getPid();
|
||||||
|
|
||||||
|
|
||||||
|
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||||
|
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
||||||
|
|
||||||
|
for (int i = 0; i < 10000; i++) {
|
||||||
|
System.out.println("Process " + procName + " with ID " + pid + " is running!");
|
||||||
|
Thread.sleep(10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -7,11 +7,10 @@
|
|||||||
</encoder>
|
</encoder>
|
||||||
</appender>
|
</appender>
|
||||||
|
|
||||||
<logger name="org.springframework" level="WARN" />
|
<!-- <logger name="org.springframework" level="WARN" /> -->
|
||||||
<logger name="org.baeldung" level="DEBUG" />
|
|
||||||
|
|
||||||
<root level="INFO">
|
<root level="INFO">
|
||||||
<appender-ref ref="STDOUT" />
|
<appender-ref ref="STDOUT"/>
|
||||||
</root>
|
</root>
|
||||||
|
|
||||||
</configuration>
|
</configuration>
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class Java9OptionalsStreamTest {
|
||||||
|
|
||||||
|
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void filterOutPresentOptionalsWithFilter() {
|
||||||
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
|
List<String> filteredList = listOfOptionals.stream()
|
||||||
|
.filter(Optional::isPresent)
|
||||||
|
.map(Optional::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(2, filteredList.size());
|
||||||
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
assertEquals("bar", filteredList.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void filterOutPresentOptionalsWithFlatMap() {
|
||||||
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
|
List<String> filteredList = listOfOptionals.stream()
|
||||||
|
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
assertEquals("bar", filteredList.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void filterOutPresentOptionalsWithFlatMap2() {
|
||||||
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
|
List<String> filteredList = listOfOptionals.stream()
|
||||||
|
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
assertEquals("bar", filteredList.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void filterOutPresentOptionalsWithJava9() {
|
||||||
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
|
List<String> filteredList = listOfOptionals.stream()
|
||||||
|
.flatMap(Optional::stream)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(2, filteredList.size());
|
||||||
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
assertEquals("bar", filteredList.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.java9;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
|
||||||
|
import java.awt.Image;
|
||||||
|
import java.awt.image.BaseMultiResolutionImage;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.awt.image.MultiResolutionImage;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MultiResultionImageTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void baseMultiResImageTest() {
|
||||||
|
int baseIndex = 1;
|
||||||
|
int length = 4;
|
||||||
|
BufferedImage[] resolutionVariants = new BufferedImage[length];
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
resolutionVariants[i] = createImage(i);
|
||||||
|
}
|
||||||
|
MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
|
||||||
|
List<Image> rvImageList = bmrImage.getResolutionVariants();
|
||||||
|
assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
|
||||||
|
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
int imageSize = getSize(i);
|
||||||
|
Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
|
||||||
|
assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int getSize(int i) {
|
||||||
|
return 8 * (i + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static BufferedImage createImage(int i) {
|
||||||
|
return new BufferedImage(getSize(i), getSize(i),
|
||||||
|
BufferedImage.TYPE_INT_RGB);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.java9;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class OptionalToStreamTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOptionalToStream() {
|
||||||
|
Optional<String> op = Optional.ofNullable("String value");
|
||||||
|
Stream<String> strOptionalStream = op.stream();
|
||||||
|
Stream<String> filteredStream = strOptionalStream.filter((str) -> {
|
||||||
|
return str != null && str.startsWith("String");
|
||||||
|
});
|
||||||
|
assertEquals(1, filteredStream.count());
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
1
core-java-9/src/test/java/com/baeldung/java9/README.MD
Normal file
1
core-java-9/src/test/java/com/baeldung/java9/README.MD
Normal file
@ -0,0 +1 @@
|
|||||||
|
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.java9;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class SetExamplesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testUnmutableSet() {
|
||||||
|
Set<String> strKeySet = Set.of("key1", "key2", "key3");
|
||||||
|
try {
|
||||||
|
strKeySet.add("newKey");
|
||||||
|
} catch (UnsupportedOperationException uoe) {
|
||||||
|
}
|
||||||
|
assertEquals(strKeySet.size(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testArrayToSet() {
|
||||||
|
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
|
||||||
|
Set<Integer> intSet = Set.of(intArray);
|
||||||
|
assertEquals(intSet.size(), intArray.length);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,126 @@
|
|||||||
|
package com.baeldung.java9.httpclient;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import static java.net.HttpURLConnection.HTTP_OK;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.CookieManager;
|
||||||
|
import java.net.CookiePolicy;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpHeaders;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLParameters;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SimpleHttpRequestsTest {
|
||||||
|
|
||||||
|
private URI httpURI;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() throws URISyntaxException {
|
||||||
|
httpURI = new URI("http://www.baeldung.com/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
||||||
|
HttpRequest request = HttpRequest.create( httpURI ).GET();
|
||||||
|
HttpResponse response = request.response();
|
||||||
|
int responseStatusCode = response.statusCode();
|
||||||
|
String responseBody = response.body(HttpResponse.asString());
|
||||||
|
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
|
||||||
|
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||||
|
long before = System.currentTimeMillis();
|
||||||
|
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
||||||
|
futureResponse.thenAccept( response -> {
|
||||||
|
String responseBody = response.body(HttpResponse.asString());
|
||||||
|
});
|
||||||
|
HttpResponse resp = futureResponse.get();
|
||||||
|
HttpHeaders hs = resp.headers();
|
||||||
|
assertTrue("There should be more then 1 header.", hs.map().size() >1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
||||||
|
requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE);
|
||||||
|
HttpRequest request = requestBuilder.POST();
|
||||||
|
HttpResponse response = request.response();
|
||||||
|
int statusCode = response.statusCode();
|
||||||
|
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
|
||||||
|
CookieManager cManager = new CookieManager();
|
||||||
|
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
|
||||||
|
|
||||||
|
SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||||
|
|
||||||
|
HttpClient.Builder hcBuilder = HttpClient.create();
|
||||||
|
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
||||||
|
HttpClient httpClient = hcBuilder.build();
|
||||||
|
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
||||||
|
|
||||||
|
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
||||||
|
HttpResponse response = request.response();
|
||||||
|
int statusCode = response.statusCode();
|
||||||
|
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
|
||||||
|
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
||||||
|
String [] proto = sslP1.getApplicationProtocols();
|
||||||
|
String [] cifers = sslP1.getCipherSuites();
|
||||||
|
System.out.println(printStringArr(proto));
|
||||||
|
System.out.println(printStringArr(cifers));
|
||||||
|
return sslP1;
|
||||||
|
}
|
||||||
|
|
||||||
|
String printStringArr(String ... args ){
|
||||||
|
if(args == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (String s : args){
|
||||||
|
sb.append(s);
|
||||||
|
sb.append("\n");
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
String printHeaders(HttpHeaders h){
|
||||||
|
if(h == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
Map<String, List<String>> hMap = h.map();
|
||||||
|
for(String k : hMap.keySet()){
|
||||||
|
sb.append(k).append(":");
|
||||||
|
List<String> l = hMap.get(k);
|
||||||
|
if( l != null ){
|
||||||
|
l.forEach( s -> { sb.append(s).append(","); } );
|
||||||
|
}
|
||||||
|
sb.append("\n");
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DiamondTest {
|
||||||
|
|
||||||
|
static class FooClass<X> {
|
||||||
|
FooClass(X x) {
|
||||||
|
}
|
||||||
|
|
||||||
|
<Z> FooClass(X x, Z z) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void diamondTest() {
|
||||||
|
FooClass<Integer> fc = new FooClass<>(1) {
|
||||||
|
};
|
||||||
|
FooClass<? extends Integer> fc0 = new FooClass<>(1) {
|
||||||
|
};
|
||||||
|
FooClass<?> fc1 = new FooClass<>(1) {
|
||||||
|
};
|
||||||
|
FooClass<? super Integer> fc2 = new FooClass<>(1) {
|
||||||
|
};
|
||||||
|
|
||||||
|
FooClass<Integer> fc3 = new FooClass<>(1, "") {
|
||||||
|
};
|
||||||
|
FooClass<? extends Integer> fc4 = new FooClass<>(1, "") {
|
||||||
|
};
|
||||||
|
FooClass<?> fc5 = new FooClass<>(1, "") {
|
||||||
|
};
|
||||||
|
FooClass<? super Integer> fc6 = new FooClass<>(1, "") {
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
|
import com.baeldung.java9.language.PrivateInterface;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PrivateInterfaceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
PrivateInterface piClass = new PrivateInterface() {
|
||||||
|
};
|
||||||
|
piClass.check();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TryWithResourcesTest {
|
||||||
|
|
||||||
|
static int closeCount = 0;
|
||||||
|
|
||||||
|
static class MyAutoCloseable implements AutoCloseable{
|
||||||
|
final FinalWrapper finalWrapper = new FinalWrapper();
|
||||||
|
|
||||||
|
public void close() {
|
||||||
|
closeCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
static class FinalWrapper {
|
||||||
|
public final AutoCloseable finalCloseable = new AutoCloseable() {
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
closeCount++;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void tryWithResourcesTest() {
|
||||||
|
MyAutoCloseable mac = new MyAutoCloseable();
|
||||||
|
|
||||||
|
try (mac) {
|
||||||
|
assertEquals("Expected and Actual does not match", 0, closeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (mac.finalWrapper.finalCloseable) {
|
||||||
|
assertEquals("Expected and Actual does not match", 1, closeCount);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
}
|
||||||
|
|
||||||
|
try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
|
||||||
|
assertEquals("Expected and Actual does not match", 2, closeCount);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
}
|
||||||
|
|
||||||
|
try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) {
|
||||||
|
assertEquals("Expected and Actual does not match", 3, closeCount);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
throw new CloseableException();
|
||||||
|
} catch (CloseableException ex) {
|
||||||
|
try (ex) {
|
||||||
|
assertEquals("Expected and Actual does not match", 4, closeCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("Expected and Actual does not match", 5, closeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static class CloseableException extends Exception implements AutoCloseable {
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
closeCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,112 @@
|
|||||||
|
package com.baeldung.java9.process;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import junit.framework.Assert;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class ProcessApi {
|
||||||
|
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void processInfoExample()throws NoSuchAlgorithmException{
|
||||||
|
ProcessHandle self = ProcessHandle.current();
|
||||||
|
long PID = self.getPid();
|
||||||
|
ProcessHandle.Info procInfo = self.info();
|
||||||
|
Optional<String[]> args = procInfo.arguments();
|
||||||
|
Optional<String> cmd = procInfo.commandLine();
|
||||||
|
Optional<Instant> startTime = procInfo.startInstant();
|
||||||
|
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
|
||||||
|
|
||||||
|
waistCPU();
|
||||||
|
System.out.println("Args "+ args);
|
||||||
|
System.out.println("Command " +cmd.orElse("EmptyCmd"));
|
||||||
|
System.out.println("Start time: "+ startTime.get().toString());
|
||||||
|
System.out.println(cpuUsage.get().toMillis());
|
||||||
|
|
||||||
|
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
|
||||||
|
allProc.forEach(p -> {
|
||||||
|
System.out.println("Proc "+ p.getPid());
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createAndDestroyProcess() throws IOException, InterruptedException{
|
||||||
|
int numberOfChildProcesses = 5;
|
||||||
|
for(int i=0; i < numberOfChildProcesses; i++){
|
||||||
|
createNewJVM(ServiceMain.class, i).getPid();
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||||
|
assertEquals( childProc.count(), numberOfChildProcesses);
|
||||||
|
|
||||||
|
childProc = ProcessHandle.current().children();
|
||||||
|
childProc.forEach(processHandle -> {
|
||||||
|
assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
|
||||||
|
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
|
||||||
|
onProcExit.thenAccept(procHandle -> {
|
||||||
|
System.out.println("Process with PID "+ procHandle.getPid() + " has stopped");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
Thread.sleep(10000);
|
||||||
|
|
||||||
|
childProc = ProcessHandle.current().children();
|
||||||
|
childProc.forEach(procHandle -> {
|
||||||
|
assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
|
||||||
|
});
|
||||||
|
|
||||||
|
Thread.sleep(5000);
|
||||||
|
|
||||||
|
childProc = ProcessHandle.current().children();
|
||||||
|
childProc.forEach(procHandle -> {
|
||||||
|
assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive());
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private Process createNewJVM(Class mainClass, int number) throws IOException{
|
||||||
|
ArrayList<String> cmdParams = new ArrayList<String>(5);
|
||||||
|
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
|
||||||
|
cmdParams.add("-cp");
|
||||||
|
cmdParams.add(ProcessUtils.getClassPath());
|
||||||
|
cmdParams.add(mainClass.getName());
|
||||||
|
cmdParams.add("Service "+ number);
|
||||||
|
ProcessBuilder myService = new ProcessBuilder(cmdParams);
|
||||||
|
myService.inheritIO();
|
||||||
|
return myService.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void waistCPU() throws NoSuchAlgorithmException{
|
||||||
|
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
||||||
|
SecureRandom sr = SecureRandom.getInstanceStrong();
|
||||||
|
Duration somecpu = Duration.ofMillis(4200L);
|
||||||
|
Instant end = Instant.now().plus(somecpu);
|
||||||
|
while (Instant.now().isBefore(end)) {
|
||||||
|
//System.out.println(sr.nextInt());
|
||||||
|
randArr.add( sr.nextInt() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
13
core-java-9/src/test/resources/.gitignore
vendored
Normal file
13
core-java-9/src/test/resources/.gitignore
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
*.class
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
@ -124,6 +124,12 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>1.10</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -168,7 +174,7 @@
|
|||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.7.2</jackson.version>
|
<jackson.version>2.7.8</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||||
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.java.nio.selector;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.SocketChannel;
|
||||||
|
|
||||||
|
public class EchoClient {
|
||||||
|
private static SocketChannel client;
|
||||||
|
private static ByteBuffer buffer;
|
||||||
|
private static EchoClient instance;
|
||||||
|
|
||||||
|
public static EchoClient start() {
|
||||||
|
if (instance == null)
|
||||||
|
instance = new EchoClient();
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private EchoClient() {
|
||||||
|
try {
|
||||||
|
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
|
||||||
|
buffer = ByteBuffer.allocate(256);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sendMessage(String msg) {
|
||||||
|
buffer = ByteBuffer.wrap(msg.getBytes());
|
||||||
|
String response = null;
|
||||||
|
try {
|
||||||
|
client.write(buffer);
|
||||||
|
buffer.clear();
|
||||||
|
client.read(buffer);
|
||||||
|
response = new String(buffer.array()).trim();
|
||||||
|
System.out.println("response=" + response);
|
||||||
|
buffer.clear();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,50 @@
|
|||||||
|
package com.baeldung.java.nio.selector;
|
||||||
|
|
||||||
|
import java.nio.channels.ServerSocketChannel;
|
||||||
|
import java.nio.channels.SocketChannel;
|
||||||
|
import java.nio.channels.Selector;
|
||||||
|
import java.nio.channels.SelectionKey;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
|
public class EchoServer {
|
||||||
|
|
||||||
|
public static void main(String[] args)
|
||||||
|
|
||||||
|
throws IOException {
|
||||||
|
Selector selector = Selector.open();
|
||||||
|
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
||||||
|
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
||||||
|
serverSocket.configureBlocking(false);
|
||||||
|
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(256);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
selector.select();
|
||||||
|
Set<SelectionKey> selectedKeys = selector.selectedKeys();
|
||||||
|
Iterator<SelectionKey> iter = selectedKeys.iterator();
|
||||||
|
while (iter.hasNext()) {
|
||||||
|
|
||||||
|
SelectionKey key = iter.next();
|
||||||
|
|
||||||
|
if (key.isAcceptable()) {
|
||||||
|
SocketChannel client = serverSocket.accept();
|
||||||
|
client.configureBlocking(false);
|
||||||
|
client.register(selector, SelectionKey.OP_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key.isReadable()) {
|
||||||
|
SocketChannel client = (SocketChannel) key.channel();
|
||||||
|
client.read(buffer);
|
||||||
|
buffer.flip();
|
||||||
|
client.write(buffer);
|
||||||
|
buffer.clear();
|
||||||
|
}
|
||||||
|
iter.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public abstract class Animal implements Eating {
|
||||||
|
|
||||||
|
public static final String CATEGORY = "domestic";
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Animal(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract String getSound();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public class Bird extends Animal {
|
||||||
|
private boolean walks;
|
||||||
|
|
||||||
|
public Bird() {
|
||||||
|
super("bird");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Bird(String name, boolean walks) {
|
||||||
|
super(name);
|
||||||
|
setWalks(walks);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Bird(String name) {
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String eats() {
|
||||||
|
return "grains";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getSound() {
|
||||||
|
return "chaps";
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean walks() {
|
||||||
|
return walks;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setWalks(boolean walks) {
|
||||||
|
this.walks = walks;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public interface Eating {
|
||||||
|
String eats();
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public class Goat extends Animal implements Locomotion {
|
||||||
|
|
||||||
|
public Goat(String name) {
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getSound() {
|
||||||
|
return "bleat";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getLocomotion() {
|
||||||
|
return "walks";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String eats() {
|
||||||
|
return "grass";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public interface Locomotion {
|
||||||
|
String getLocomotion();
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
private String name;
|
||||||
|
private int age;
|
||||||
|
}
|
@ -0,0 +1,65 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class ComplexClass {
|
||||||
|
|
||||||
|
private List<?> genericList;
|
||||||
|
private Set<Integer> integerSet;
|
||||||
|
|
||||||
|
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
|
||||||
|
super();
|
||||||
|
this.genericList = genericArrayList;
|
||||||
|
this.integerSet = integerHashSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
|
||||||
|
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (!(obj instanceof ComplexClass))
|
||||||
|
return false;
|
||||||
|
ComplexClass other = (ComplexClass) obj;
|
||||||
|
if (genericList == null) {
|
||||||
|
if (other.genericList != null)
|
||||||
|
return false;
|
||||||
|
} else if (!genericList.equals(other.genericList))
|
||||||
|
return false;
|
||||||
|
if (integerSet == null) {
|
||||||
|
if (other.integerSet != null)
|
||||||
|
return false;
|
||||||
|
} else if (!integerSet.equals(other.integerSet))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected List<?> getGenericList() {
|
||||||
|
return genericList;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setGenericArrayList(List<?> genericList) {
|
||||||
|
this.genericList = genericList;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Set<Integer> getIntegerSet() {
|
||||||
|
return integerSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setIntegerSet(Set<Integer> integerSet) {
|
||||||
|
this.integerSet = integerSet;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
public class PrimitiveClass {
|
||||||
|
|
||||||
|
private boolean primitiveBoolean;
|
||||||
|
private int primitiveInt;
|
||||||
|
|
||||||
|
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
|
||||||
|
super();
|
||||||
|
this.primitiveBoolean = primitiveBoolean;
|
||||||
|
this.primitiveInt = primitiveInt;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean isPrimitiveBoolean() {
|
||||||
|
return primitiveBoolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + (primitiveBoolean ? 1231 : 1237);
|
||||||
|
result = prime * result + primitiveInt;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
PrimitiveClass other = (PrimitiveClass) obj;
|
||||||
|
if (primitiveBoolean != other.primitiveBoolean)
|
||||||
|
return false;
|
||||||
|
if (primitiveInt != other.primitiveInt)
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
|
||||||
|
this.primitiveBoolean = primitiveBoolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int getPrimitiveInt() {
|
||||||
|
return primitiveInt;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setPrimitiveInt(int primitiveInt) {
|
||||||
|
this.primitiveInt = primitiveInt;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
public class Rectangle extends Shape {
|
||||||
|
private double width;
|
||||||
|
private double length;
|
||||||
|
|
||||||
|
public Rectangle(double width, double length) {
|
||||||
|
this.width = width;
|
||||||
|
this.length = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double area() {
|
||||||
|
return width * length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double perimeter() {
|
||||||
|
return 2 * (width + length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
long temp;
|
||||||
|
temp = Double.doubleToLongBits(length);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
temp = Double.doubleToLongBits(width);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Rectangle other = (Rectangle) obj;
|
||||||
|
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
|
||||||
|
return false;
|
||||||
|
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected double getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected double getLength() {
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
|
||||||
|
public class Square extends Rectangle {
|
||||||
|
|
||||||
|
Color color;
|
||||||
|
|
||||||
|
public Square(double width, Color color) {
|
||||||
|
super(width, width);
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* (non-Javadoc)
|
||||||
|
* @see java.lang.Object#hashCode()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = super.hashCode();
|
||||||
|
result = prime * result + ((color == null) ? 0 : color.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* (non-Javadoc)
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!super.equals(obj)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!(obj instanceof Square)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Square other = (Square) obj;
|
||||||
|
if (color == null) {
|
||||||
|
if (other.color != null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else if (!color.equals(other.color)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Color getColor() {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setColor(Color color) {
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,326 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class ReflectionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
|
||||||
|
Object person = new Person();
|
||||||
|
Field[] fields = person.getClass().getDeclaredFields();
|
||||||
|
|
||||||
|
List<String> actualFieldNames = getFieldNames(fields);
|
||||||
|
|
||||||
|
assertTrue(Arrays.asList("name", "age")
|
||||||
|
.containsAll(actualFieldNames));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenObject_whenGetsClassName_thenCorrect() {
|
||||||
|
Object goat = new Goat("goat");
|
||||||
|
Class<?> clazz = goat.getClass();
|
||||||
|
|
||||||
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||||
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassName_whenCreatesObject_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
|
|
||||||
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||||
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenRecognisesModifiers_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
|
int goatMods = goatClass.getModifiers();
|
||||||
|
int animalMods = animalClass.getModifiers();
|
||||||
|
|
||||||
|
assertTrue(Modifier.isPublic(goatMods));
|
||||||
|
assertTrue(Modifier.isAbstract(animalMods));
|
||||||
|
assertTrue(Modifier.isPublic(animalMods));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsPackageInfo_thenCorrect() {
|
||||||
|
Goat goat = new Goat("goat");
|
||||||
|
Class<?> goatClass = goat.getClass();
|
||||||
|
Package pkg = goatClass.getPackage();
|
||||||
|
|
||||||
|
assertEquals("com.baeldung.java.reflection", pkg.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsSuperClass_thenCorrect() {
|
||||||
|
Goat goat = new Goat("goat");
|
||||||
|
String str = "any string";
|
||||||
|
|
||||||
|
Class<?> goatClass = goat.getClass();
|
||||||
|
Class<?> goatSuperClass = goatClass.getSuperclass();
|
||||||
|
|
||||||
|
assertEquals("Animal", goatSuperClass.getSimpleName());
|
||||||
|
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsImplementedInterfaces_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
|
Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
||||||
|
Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
||||||
|
|
||||||
|
assertEquals(1, goatInterfaces.length);
|
||||||
|
assertEquals(1, animalInterfaces.length);
|
||||||
|
assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
|
||||||
|
assertEquals("Eating", animalInterfaces[0].getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsConstructor_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
|
Constructor<?>[] constructors = goatClass.getConstructors();
|
||||||
|
|
||||||
|
assertEquals(1, constructors.length);
|
||||||
|
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsFields_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
|
Field[] fields = animalClass.getDeclaredFields();
|
||||||
|
|
||||||
|
List<String> actualFields = getFieldNames(fields);
|
||||||
|
|
||||||
|
assertEquals(2, actualFields.size());
|
||||||
|
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsMethods_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
|
Method[] methods = animalClass.getDeclaredMethods();
|
||||||
|
List<String> actualMethods = getMethodNames(methods);
|
||||||
|
|
||||||
|
assertEquals(4, actualMethods.size());
|
||||||
|
assertTrue(actualMethods.containsAll(Arrays.asList("getName",
|
||||||
|
"setName", "getSound")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsAllConstructors_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Constructor<?>[] constructors = birdClass.getConstructors();
|
||||||
|
|
||||||
|
assertEquals(3, constructors.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
|
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
|
Constructor<?> cons3 = birdClass.getConstructor(String.class,
|
||||||
|
boolean.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
|
||||||
|
Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
|
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
|
Constructor<?> cons3 = birdClass.getConstructor(String.class,
|
||||||
|
boolean.class);
|
||||||
|
|
||||||
|
Bird bird1 = (Bird) cons1.newInstance();
|
||||||
|
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
|
||||||
|
Bird bird3 = (Bird) cons3.newInstance("dove", true);
|
||||||
|
|
||||||
|
assertEquals("bird", bird1.getName());
|
||||||
|
assertEquals("Weaver bird", bird2.getName());
|
||||||
|
assertEquals("dove", bird3.getName());
|
||||||
|
assertFalse(bird1.walks());
|
||||||
|
assertTrue(bird3.walks());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsPublicFields_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Field[] fields = birdClass.getFields();
|
||||||
|
assertEquals(1, fields.length);
|
||||||
|
assertEquals("CATEGORY", fields[0].getName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsPublicFieldByName_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Field field = birdClass.getField("CATEGORY");
|
||||||
|
assertEquals("CATEGORY", field.getName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsDeclaredFields_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Field[] fields = birdClass.getDeclaredFields();
|
||||||
|
assertEquals(1, fields.length);
|
||||||
|
assertEquals("walks", fields[0].getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsFieldsByName_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Field field = birdClass.getDeclaredField("walks");
|
||||||
|
assertEquals("walks", field.getName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassField_whenGetsType_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Field field = Class.forName("com.baeldung.java.reflection.Bird")
|
||||||
|
.getDeclaredField("walks");
|
||||||
|
Class<?> fieldClass = field.getType();
|
||||||
|
assertEquals("boolean", fieldClass.getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassField_whenSetsAndGetsValue_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Bird bird = (Bird) birdClass.newInstance();
|
||||||
|
Field field = birdClass.getDeclaredField("walks");
|
||||||
|
field.setAccessible(true);
|
||||||
|
|
||||||
|
assertFalse(field.getBoolean(bird));
|
||||||
|
assertFalse(bird.walks());
|
||||||
|
|
||||||
|
field.set(bird, true);
|
||||||
|
|
||||||
|
assertTrue(field.getBoolean(bird));
|
||||||
|
assertTrue(bird.walks());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Field field = birdClass.getField("CATEGORY");
|
||||||
|
field.setAccessible(true);
|
||||||
|
|
||||||
|
assertEquals("domestic", field.get(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsAllPublicMethods_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Method[] methods = birdClass.getMethods();
|
||||||
|
List<String> methodNames = getMethodNames(methods);
|
||||||
|
|
||||||
|
assertTrue(methodNames.containsAll(Arrays
|
||||||
|
.asList("equals", "notifyAll", "hashCode",
|
||||||
|
"walks", "eats", "toString")));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect()
|
||||||
|
throws ClassNotFoundException {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
||||||
|
|
||||||
|
List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
|
||||||
|
|
||||||
|
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
|
||||||
|
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
|
||||||
|
assertTrue(actualMethodNames.containsAll(expectedMethodNames));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMethodName_whenGetsMethod_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
|
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
|
||||||
|
boolean.class);
|
||||||
|
|
||||||
|
assertFalse(walksMethod.isAccessible());
|
||||||
|
assertFalse(setWalksMethod.isAccessible());
|
||||||
|
|
||||||
|
walksMethod.setAccessible(true);
|
||||||
|
setWalksMethod.setAccessible(true);
|
||||||
|
|
||||||
|
assertTrue(walksMethod.isAccessible());
|
||||||
|
assertTrue(setWalksMethod.isAccessible());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMethod_whenInvokes_thenCorrect()
|
||||||
|
throws Exception {
|
||||||
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
Bird bird = (Bird) birdClass.newInstance();
|
||||||
|
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
|
||||||
|
boolean.class);
|
||||||
|
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
|
boolean walks = (boolean) walksMethod.invoke(bird);
|
||||||
|
|
||||||
|
assertFalse(walks);
|
||||||
|
assertFalse(bird.walks());
|
||||||
|
|
||||||
|
setWalksMethod.invoke(bird, true);
|
||||||
|
boolean walks2 = (boolean) walksMethod.invoke(bird);
|
||||||
|
|
||||||
|
assertTrue(walks2);
|
||||||
|
assertTrue(bird.walks());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> getFieldNames(Field[] fields) {
|
||||||
|
List<String> fieldNames = new ArrayList<>();
|
||||||
|
for (Field field : fields)
|
||||||
|
fieldNames.add(field.getName());
|
||||||
|
return fieldNames;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> getMethodNames(Method[] methods) {
|
||||||
|
List<String> methodNames = new ArrayList<>();
|
||||||
|
for (Method method : methods)
|
||||||
|
methodNames.add(method.getName());
|
||||||
|
return methodNames;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
502
core-java/src/test/java/com/baeldung/java/regex/RegexTest.java
Normal file
502
core-java/src/test/java/com/baeldung/java/regex/RegexTest.java
Normal file
@ -0,0 +1,502 @@
|
|||||||
|
package com.baeldung.java.regex;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RegexTest {
|
||||||
|
private static Pattern pattern;
|
||||||
|
private static Matcher matcher;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenSimpleRegexMatches_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("foo");
|
||||||
|
Matcher matcher = pattern.matcher("foo");
|
||||||
|
assertTrue(matcher.find());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("foo");
|
||||||
|
Matcher matcher = pattern.matcher("foofoo");
|
||||||
|
int matches = 0;
|
||||||
|
while (matcher.find())
|
||||||
|
matches++;
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
|
||||||
|
int matches = runTest(".", "foo");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
|
||||||
|
int matches = runTest("foo.", "foofoo");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenORSet_whenMatchesAny_thenCorrect() {
|
||||||
|
int matches = runTest("[abc]", "b");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
|
||||||
|
int matches = runTest("[abc]", "cab");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
|
||||||
|
int matches = runTest("[bcr]at", "bat cat rat");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNORSet_whenMatchesNon_thenCorrect() {
|
||||||
|
int matches = runTest("[^abc]", "g");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
|
||||||
|
int matches = runTest("[^bcr]at", "sat mat eat");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
|
||||||
|
int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
|
||||||
|
int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 26);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
|
||||||
|
int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 28);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
|
||||||
|
int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
|
||||||
|
int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
|
||||||
|
int matches = runTest("[1-3[7-9]]", "123456789");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
|
||||||
|
int matches = runTest("[1-6&&[3-9]]", "123456789");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
|
||||||
|
int matches = runTest("[0-9&&[^2468]]", "123456789");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDigits_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\d", "123");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonDigits_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\D", "a6c");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhiteSpace_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\s", "a c");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\S", "a c");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWordCharacter_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\w", "hi!");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonWordCharacter_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\W", "hi!");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\a?", "hi");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
|
||||||
|
int matches = runTest("\\a{0,1}", "hi");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\a*", "hi");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||||
|
int matches = runTest("\\a{0,}", "hi");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("\\a+", "hi");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||||
|
int matches = runTest("\\a{1,}", "hi");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBraceQuantifier_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("a{3}", "aaaaaa");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
|
||||||
|
int matches = runTest("a{3}", "aa");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("a{2,3}", "aaaa");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
|
||||||
|
int matches = runTest("a{2,3}?", "aaaa");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroup_whenMatches_thenCorrect() {
|
||||||
|
int matches = runTest("(\\d\\d)", "12");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroup_whenMatches_thenCorrect2() {
|
||||||
|
int matches = runTest("(\\d\\d)", "1212");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroup_whenMatches_thenCorrect3() {
|
||||||
|
int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
|
||||||
|
int matches = runTest("(\\d\\d)\\1", "1212");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
|
||||||
|
int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
assertEquals(matches, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
|
||||||
|
int matches = runTest("(\\d\\d)\\1", "1213");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesAtBeginning_thenCorrect() {
|
||||||
|
int matches = runTest("^dog", "dogs are friendly");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
|
||||||
|
int matches = runTest("^dog", "are dogs are friendly?");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesAtEnd_thenCorrect() {
|
||||||
|
int matches = runTest("dog$", "Man's best friend is a dog");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
|
||||||
|
int matches = runTest("dog$", "is a dog man's best friend?");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
|
||||||
|
int matches = runTest("\\bdog\\b", "a dog is friendly");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
|
||||||
|
int matches = runTest("\\bdog\\b", "dog is man's best friend");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
|
||||||
|
int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
|
||||||
|
int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
|
||||||
|
int matches = runTest("\u00E9", "\u0065\u0301");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
|
||||||
|
int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
|
||||||
|
int matches = runTest("dog", "This is a Dog");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||||
|
int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||||
|
int matches = runTest("(?i)dog", "This is a Dog");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
|
||||||
|
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
|
||||||
|
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
|
||||||
|
int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("(.*)");
|
||||||
|
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||||
|
matcher.find();
|
||||||
|
assertEquals("this is a text", matcher.group(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
|
||||||
|
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||||
|
matcher.find();
|
||||||
|
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("(?s)(.*)");
|
||||||
|
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||||
|
matcher.find();
|
||||||
|
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
|
||||||
|
int matches = runTest("(.*)", "text");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
|
||||||
|
int matches = runTest("(.*)", "text", Pattern.LITERAL);
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
|
||||||
|
int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
|
||||||
|
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||||
|
assertFalse(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
|
||||||
|
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
|
||||||
|
int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||||
|
assertTrue(matches > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMatch_whenGetsIndices_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("dog");
|
||||||
|
Matcher matcher = pattern.matcher("This dog is mine");
|
||||||
|
matcher.find();
|
||||||
|
assertEquals(5, matcher.start());
|
||||||
|
assertEquals(8, matcher.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenStudyMethodsWork_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("dog");
|
||||||
|
Matcher matcher = pattern.matcher("dogs are friendly");
|
||||||
|
assertTrue(matcher.lookingAt());
|
||||||
|
assertFalse(matcher.matches());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMatchesStudyMethodWorks_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("dog");
|
||||||
|
Matcher matcher = pattern.matcher("dog");
|
||||||
|
assertTrue(matcher.matches());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReplaceFirstWorks_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("dog");
|
||||||
|
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
|
||||||
|
String newStr = matcher.replaceFirst("cat");
|
||||||
|
assertEquals("cats are domestic animals, dogs are friendly", newStr);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReplaceAllWorks_thenCorrect() {
|
||||||
|
Pattern pattern = Pattern.compile("dog");
|
||||||
|
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
|
||||||
|
String newStr = matcher.replaceAll("cat");
|
||||||
|
assertEquals("cats are domestic animals, cats are friendly", newStr);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized static int runTest(String regex, String text) {
|
||||||
|
pattern = Pattern.compile(regex);
|
||||||
|
matcher = pattern.matcher(text);
|
||||||
|
int matches = 0;
|
||||||
|
while (matcher.find())
|
||||||
|
matches++;
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized static int runTest(String regex, String text, int flags) {
|
||||||
|
pattern = Pattern.compile(regex, flags);
|
||||||
|
matcher = pattern.matcher(text);
|
||||||
|
int matches = 0;
|
||||||
|
while (matcher.find())
|
||||||
|
matches++;
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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,33 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ComplexClassTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEqualsAndHashcodes() {
|
||||||
|
|
||||||
|
ArrayList<String> strArrayList = new ArrayList<String>();
|
||||||
|
strArrayList.add("abc");
|
||||||
|
strArrayList.add("def");
|
||||||
|
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
||||||
|
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
||||||
|
|
||||||
|
ArrayList<String> strArrayListD = new ArrayList<String>();
|
||||||
|
strArrayListD.add("lmn");
|
||||||
|
strArrayListD.add("pqr");
|
||||||
|
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
|
||||||
|
|
||||||
|
Assert.assertFalse(aObject.equals(dObject));
|
||||||
|
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PrimitiveClassTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTwoEqualsObjects() {
|
||||||
|
|
||||||
|
PrimitiveClass aObject = new PrimitiveClass(false, 2);
|
||||||
|
PrimitiveClass bObject = new PrimitiveClass(false, 2);
|
||||||
|
PrimitiveClass dObject = new PrimitiveClass(true, 2);
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
|
||||||
|
|
||||||
|
Assert.assertFalse(aObject.equals(dObject));
|
||||||
|
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SquareClassTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEqualsAndHashcodes() {
|
||||||
|
|
||||||
|
Square aObject = new Square(10, Color.BLUE);
|
||||||
|
Square bObject = new Square(10, Color.BLUE);
|
||||||
|
|
||||||
|
Square dObject = new Square(20, Color.BLUE);
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
|
||||||
|
|
||||||
|
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
|
||||||
|
|
||||||
|
Assert.assertFalse(aObject.equals(dObject));
|
||||||
|
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,63 +1,65 @@
|
|||||||
package org.baeldung.java.collections;
|
package org.baeldung.java.collections;
|
||||||
|
|
||||||
|
import com.google.common.collect.Sets;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.*;
|
import java.util.stream.*;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.*;
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import static org.hamcrest.core.IsNot.not;
|
import static org.hamcrest.core.IsNot.not;
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class ArrayListTest {
|
public class ArrayListTest {
|
||||||
|
|
||||||
List<String> stringsToSearch;
|
private List<String> stringsToSearch;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
List<String> xs = LongStream.range(0, 16)
|
List<String> list = LongStream.range(0, 16)
|
||||||
.boxed()
|
.boxed()
|
||||||
.map(Long::toHexString)
|
.map(Long::toHexString)
|
||||||
.collect(Collectors.toList());
|
.collect(toCollection(ArrayList::new));
|
||||||
stringsToSearch = new ArrayList<>(xs);
|
stringsToSearch = new ArrayList<>(list);
|
||||||
stringsToSearch.addAll(xs);
|
stringsToSearch.addAll(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
|
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
|
||||||
List<String> xs = new ArrayList<>();
|
List<String> list = new ArrayList<>();
|
||||||
assertTrue(xs.isEmpty());
|
assertTrue(list.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
||||||
Collection<Integer> numbers =
|
Collection<Integer> numbers =
|
||||||
IntStream.range(0, 10).boxed().collect(Collectors.toSet());
|
IntStream.range(0, 10).boxed().collect(toSet());
|
||||||
|
|
||||||
List<Integer> xs = new ArrayList<>(numbers);
|
List<Integer> list = new ArrayList<>(numbers);
|
||||||
assertEquals(10, xs.size());
|
assertEquals(10, list.size());
|
||||||
assertTrue(numbers.containsAll(xs));
|
assertTrue(numbers.containsAll(list));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenElement_whenAddToArrayList_thenIsAdded() {
|
public void givenElement_whenAddToArrayList_thenIsAdded() {
|
||||||
List<Long> xs = new ArrayList<>();
|
List<Long> list = new ArrayList<>();
|
||||||
|
|
||||||
xs.add(1L);
|
list.add(1L);
|
||||||
xs.add(2L);
|
list.add(2L);
|
||||||
xs.add(1, 3L);
|
list.add(1, 3L);
|
||||||
|
|
||||||
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs));
|
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
||||||
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
||||||
Collection<Long> ys = LongStream.range(4, 10).boxed().collect(Collectors.toList());
|
LongStream.range(4, 10).boxed()
|
||||||
xs.addAll(0, ys);
|
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
|
||||||
|
|
||||||
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
|
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -89,7 +91,7 @@ public class ArrayListTest {
|
|||||||
List<String> result = stringsToSearch
|
List<String> result = stringsToSearch
|
||||||
.stream()
|
.stream()
|
||||||
.filter(matchingStrings::contains)
|
.filter(matchingStrings::contains)
|
||||||
.collect(Collectors.toList());
|
.collect(toCollection(ArrayList::new));
|
||||||
|
|
||||||
assertEquals(6, result.size());
|
assertEquals(6, result.size());
|
||||||
}
|
}
|
||||||
@ -104,37 +106,33 @@ public class ArrayListTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
|
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
|
||||||
List<Integer> xs = new ArrayList<>(
|
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
|
||||||
IntStream.range(0, 10).boxed().collect(Collectors.toList())
|
Collections.reverse(list);
|
||||||
);
|
|
||||||
Collections.reverse(xs);
|
|
||||||
|
|
||||||
xs.remove(0);
|
list.remove(0);
|
||||||
assertThat(xs.get(0), equalTo(8));
|
assertThat(list.get(0), equalTo(8));
|
||||||
|
|
||||||
xs.remove(Integer.valueOf(0));
|
list.remove(Integer.valueOf(0));
|
||||||
assertFalse(xs.contains(0));
|
assertFalse(list.contains(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
|
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
|
||||||
List<Integer> xs = new ArrayList<>(
|
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
|
||||||
IntStream.range(0, 10).boxed().collect(Collectors.toList())
|
ListIterator<Integer> it = list.listIterator(list.size());
|
||||||
);
|
List<Integer> result = new ArrayList<>(list.size());
|
||||||
ListIterator<Integer> it = xs.listIterator(xs.size());
|
|
||||||
List<Integer> result = new ArrayList<>(xs.size());
|
|
||||||
while (it.hasPrevious()) {
|
while (it.hasPrevious()) {
|
||||||
result.add(it.previous());
|
result.add(it.previous());
|
||||||
}
|
}
|
||||||
|
|
||||||
Collections.reverse(xs);
|
Collections.reverse(list);
|
||||||
assertThat(result, equalTo(xs));
|
assertThat(result, equalTo(list));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
||||||
Set<String> matchingStrings
|
Set<String> matchingStrings
|
||||||
= new HashSet<>(Arrays.asList("a", "b", "c", "d", "e", "f"));
|
= Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
||||||
|
|
||||||
Iterator<String> it = stringsToSearch.iterator();
|
Iterator<String> it = stringsToSearch.iterator();
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
|
@ -0,0 +1,90 @@
|
|||||||
|
package org.baeldung.java.md5;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
|
||||||
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.hash.HashCode;
|
||||||
|
import com.google.common.hash.Hashing;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.*;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
|
||||||
|
public class JavaMD5Test {
|
||||||
|
|
||||||
|
|
||||||
|
String filename = "src/test/resources/test_md5.txt";
|
||||||
|
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||||
|
|
||||||
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
|
String password = "ILoveJava";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException {
|
||||||
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
|
String password = "ILoveJava";
|
||||||
|
|
||||||
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||||
|
md.update(password.getBytes());
|
||||||
|
byte[] digest = md.digest();
|
||||||
|
String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase();
|
||||||
|
|
||||||
|
assertThat(myHash.equals(hash)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException {
|
||||||
|
String filename = "src/test/resources/test_md5.txt";
|
||||||
|
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||||
|
|
||||||
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||||
|
md.update(Files.readAllBytes(Paths.get(filename)));
|
||||||
|
byte[] digest = md.digest();
|
||||||
|
String myChecksum = DatatypeConverter
|
||||||
|
.printHexBinary(digest).toUpperCase();
|
||||||
|
|
||||||
|
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPassword_whenHashingUsingCommons_thenVerifying() {
|
||||||
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
|
String password = "ILoveJava";
|
||||||
|
|
||||||
|
String md5Hex = DigestUtils
|
||||||
|
.md5Hex(password).toUpperCase();
|
||||||
|
|
||||||
|
assertThat(md5Hex.equals(hash)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
|
||||||
|
String filename = "src/test/resources/test_md5.txt";
|
||||||
|
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||||
|
|
||||||
|
HashCode hash = com.google.common.io.Files
|
||||||
|
.hash(new File(filename), Hashing.md5());
|
||||||
|
String myChecksum = hash.toString()
|
||||||
|
.toUpperCase();
|
||||||
|
|
||||||
|
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
1
core-java/src/test/resources/test_md5.txt
Normal file
1
core-java/src/test/resources/test_md5.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
hello world
|
BIN
couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar
vendored
BIN
couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar
vendored
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,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 {
|
|
||||||
}
|
|
BIN
couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar
vendored
BIN
couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar
vendored
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
|
|
233
couchbase-sdk-intro/mvnw
vendored
233
couchbase-sdk-intro/mvnw
vendored
@ -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} "$@"
|
|
145
couchbase-sdk-intro/mvnw.cmd
vendored
145
couchbase-sdk-intro/mvnw.cmd
vendored
@ -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
|
|
233
couchbase-sdk-spring-service/mvnw
vendored
233
couchbase-sdk-spring-service/mvnw
vendored
@ -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} "$@"
|
|
145
couchbase-sdk-spring-service/mvnw.cmd
vendored
145
couchbase-sdk-spring-service/mvnw.cmd
vendored
@ -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>
|
|
50
couchbase-sdk/README.md
Normal file
50
couchbase-sdk/README.md
Normal file
@ -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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>couchbase-sdk-async</artifactId>
|
<artifactId>couchbase-sdk</artifactId>
|
||||||
<version>0.1-SNAPSHOT</version>
|
<version>0.1-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>couchbase-sdk-async</name>
|
<name>couchbase-sdk</name>
|
||||||
<description>Couchbase SDK Asynchronous Operations</description>
|
<description>Couchbase SDK Tutorials</description>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- Couchbase SDK -->
|
<!-- Couchbase SDK -->
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.couchbase.service;
|
package com.baeldung.couchbase.async;
|
||||||
|
|
||||||
public interface CouchbaseEntity {
|
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 {
|
public class Person implements CouchbaseEntity {
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.couchbase.person;
|
package com.baeldung.couchbase.async.person;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
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.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import com.baeldung.couchbase.service.AbstractCrudService;
|
import com.baeldung.couchbase.async.service.AbstractCrudService;
|
||||||
import com.baeldung.couchbase.service.BucketService;
|
import com.baeldung.couchbase.async.service.BucketService;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class PersonCrudService extends AbstractCrudService<Person> {
|
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 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.JsonDocument;
|
||||||
import com.couchbase.client.java.document.json.JsonObject;
|
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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
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;
|
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.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.baeldung.couchbase.async.CouchbaseEntity;
|
||||||
import com.couchbase.client.core.BackpressureException;
|
import com.couchbase.client.core.BackpressureException;
|
||||||
import com.couchbase.client.core.time.Delay;
|
import com.couchbase.client.core.time.Delay;
|
||||||
import com.couchbase.client.java.AsyncBucket;
|
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;
|
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;
|
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.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.couchbase.service;
|
package com.baeldung.couchbase.async.service;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user