commit
fe577c073d
6
.gitignore
vendored
6
.gitignore
vendored
@ -7,8 +7,11 @@
|
||||
|
||||
# Eclipse
|
||||
.settings/
|
||||
*.project
|
||||
*.classpath
|
||||
.prefs
|
||||
*.prefs
|
||||
.metadata/
|
||||
|
||||
# Intellij
|
||||
.idea/
|
||||
@ -21,3 +24,6 @@
|
||||
# Maven
|
||||
log/
|
||||
target/
|
||||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
[submodule "testgitrepo"]
|
||||
path = testgitrepo
|
||||
url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/
|
11
.project
11
.project
@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>parent</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
</natures>
|
||||
</projectDescription>
|
@ -1,7 +1,7 @@
|
||||
|
||||
The "REST with Spring" Classes
|
||||
==============================
|
||||
After 5 months of work, here's the Master Class: <br/>
|
||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
|
||||
@ -19,3 +19,8 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
|
||||
|
||||
- import the included **formatter** in Eclipse:
|
||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
||||
|
||||
|
||||
CI - Jenkins
|
||||
================================
|
||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)**
|
||||
|
@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>RemoteSystemsTempFiles</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.rse.ui.remoteSystemsTempNature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
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 @@
|
||||
|
47
apache-cxf/cxf-introduction/pom.xml
Normal file
47
apache-cxf/cxf-introduction/pom.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?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-introduction</artifactId>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.cxf.introduction.Server</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/StudentTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jws.WebService;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
|
||||
@WebService
|
||||
public interface Baeldung {
|
||||
public String hello(String name);
|
||||
|
||||
public String helloStudent(Student student);
|
||||
|
||||
@XmlJavaTypeAdapter(StudentMapAdapter.class)
|
||||
public Map<Integer, Student> getStudents();
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jws.WebService;
|
||||
|
||||
@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
|
||||
public class BaeldungImpl implements Baeldung {
|
||||
private Map<Integer, Student> students = new LinkedHashMap<Integer, Student>();
|
||||
|
||||
public String hello(String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
|
||||
public String helloStudent(Student student) {
|
||||
students.put(students.size() + 1, student);
|
||||
return "Hello " + student.getName();
|
||||
}
|
||||
|
||||
public Map<Integer, Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.ws.Endpoint;
|
||||
|
||||
public class Server {
|
||||
public static void main(String args[]) throws InterruptedException {
|
||||
BaeldungImpl implementor = new BaeldungImpl();
|
||||
String address = "http://localhost:8080/baeldung";
|
||||
Endpoint.publish(address, implementor);
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
|
||||
@XmlJavaTypeAdapter(StudentAdapter.class)
|
||||
public interface Student {
|
||||
public String getName();
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class StudentAdapter extends XmlAdapter<StudentImpl, Student> {
|
||||
public StudentImpl marshal(Student student) throws Exception {
|
||||
if (student instanceof StudentImpl) {
|
||||
return (StudentImpl) student;
|
||||
}
|
||||
return new StudentImpl(student.getName());
|
||||
}
|
||||
|
||||
public Student unmarshal(StudentImpl student) throws Exception {
|
||||
return student;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
@XmlType(name = "Student")
|
||||
public class StudentImpl implements Student {
|
||||
private String name;
|
||||
|
||||
StudentImpl() {
|
||||
}
|
||||
|
||||
public StudentImpl(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
@XmlType(name = "StudentMap")
|
||||
public class StudentMap {
|
||||
private List<StudentEntry> entries = new ArrayList<StudentEntry>();
|
||||
|
||||
@XmlElement(nillable = false, name = "entry")
|
||||
public List<StudentEntry> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
@XmlType(name = "StudentEntry")
|
||||
public static class StudentEntry {
|
||||
private Integer id;
|
||||
private Student student;
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setStudent(Student student) {
|
||||
this.student = student;
|
||||
}
|
||||
|
||||
public Student getStudent() {
|
||||
return student;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class StudentMapAdapter extends XmlAdapter<StudentMap, Map<Integer, Student>> {
|
||||
public StudentMap marshal(Map<Integer, Student> boundMap) throws Exception {
|
||||
StudentMap valueMap = new StudentMap();
|
||||
for (Map.Entry<Integer, Student> boundEntry : boundMap.entrySet()) {
|
||||
StudentMap.StudentEntry valueEntry = new StudentMap.StudentEntry();
|
||||
valueEntry.setStudent(boundEntry.getValue());
|
||||
valueEntry.setId(boundEntry.getKey());
|
||||
valueMap.getEntries().add(valueEntry);
|
||||
}
|
||||
return valueMap;
|
||||
}
|
||||
|
||||
public Map<Integer, Student> unmarshal(StudentMap valueMap) throws Exception {
|
||||
Map<Integer, Student> boundMap = new LinkedHashMap<Integer, Student>();
|
||||
for (StudentMap.StudentEntry studentEntry : valueMap.getEntries()) {
|
||||
boundMap.put(studentEntry.getId(), studentEntry.getStudent());
|
||||
}
|
||||
return boundMap;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.namespace.QName;
|
||||
import javax.xml.ws.Service;
|
||||
import javax.xml.ws.soap.SOAPBinding;
|
||||
|
||||
import com.baeldung.cxf.introduction.Baeldung;
|
||||
import com.baeldung.cxf.introduction.Student;
|
||||
import com.baeldung.cxf.introduction.StudentImpl;
|
||||
|
||||
public class StudentTest {
|
||||
private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
|
||||
private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
|
||||
|
||||
private Service service;
|
||||
private Baeldung baeldungProxy;
|
||||
private BaeldungImpl baeldungImpl;
|
||||
|
||||
{
|
||||
service = Service.create(SERVICE_NAME);
|
||||
String endpointAddress = "http://localhost:8080/baeldung";
|
||||
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void reinstantiateBaeldungInstances() {
|
||||
baeldungImpl = new BaeldungImpl();
|
||||
baeldungProxy = service.getPort(PORT_NAME, Baeldung.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloMethod_thenCorrect() {
|
||||
String endpointResponse = baeldungProxy.hello("Baeldung");
|
||||
String localResponse = baeldungImpl.hello("Baeldung");
|
||||
assertEquals(localResponse, endpointResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloStudentMethod_thenCorrect() {
|
||||
Student student = new StudentImpl("John Doe");
|
||||
String endpointResponse = baeldungProxy.helloStudent(student);
|
||||
String localResponse = baeldungImpl.helloStudent(student);
|
||||
assertEquals(localResponse, endpointResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usingGetStudentsMethod_thenCorrect() {
|
||||
Student student1 = new StudentImpl("Adam");
|
||||
baeldungProxy.helloStudent(student1);
|
||||
|
||||
Student student2 = new StudentImpl("Eve");
|
||||
baeldungProxy.helloStudent(student2);
|
||||
|
||||
Map<Integer, Student> students = baeldungProxy.getStudents();
|
||||
assertEquals("Adam", students.get(1).getName());
|
||||
assertEquals("Eve", students.get(2).getName());
|
||||
}
|
||||
}
|
1
apache-cxf/cxf-spring/.gitignore
vendored
Normal file
1
apache-cxf/cxf-spring/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
target/
|
129
apache-cxf/cxf-spring/pom.xml
Normal file
129
apache-cxf/cxf-spring/pom.xml
Normal file
@ -0,0 +1,129 @@
|
||||
<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-spring</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</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.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>StudentTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>1.4.19</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>tomcat8x</containerId>
|
||||
<type>embedded</type>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.hostname>localhost</cargo.hostname>
|
||||
<cargo.servlet.port>8081</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.apache.cxf.transport.servlet.CXFServlet;
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
public class AppInitializer implements WebApplicationInitializer {
|
||||
@Override
|
||||
public void onStartup(ServletContext container) {
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
context.register(ServiceConfiguration.class);
|
||||
container.addListener(new ContextLoaderListener(context));
|
||||
|
||||
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
|
||||
dispatcher.addMapping("/services/*");
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.jws.WebService;
|
||||
|
||||
@WebService
|
||||
public interface Baeldung {
|
||||
String hello(String name);
|
||||
|
||||
String register(Student student);
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.jws.WebService;
|
||||
|
||||
@WebService(endpointInterface = "com.baeldung.cxf.spring.Baeldung")
|
||||
public class BaeldungImpl implements Baeldung {
|
||||
private int counter;
|
||||
|
||||
public String hello(String name) {
|
||||
return "Hello " + name + "!";
|
||||
}
|
||||
|
||||
public String register(Student student) {
|
||||
counter++;
|
||||
return student.getName() + " is registered student number " + counter;
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ClientConfiguration {
|
||||
@Bean(name = "client")
|
||||
public Object generateProxy() {
|
||||
return proxyFactoryBean().create();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JaxWsProxyFactoryBean proxyFactoryBean() {
|
||||
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
|
||||
proxyFactory.setServiceClass(Baeldung.class);
|
||||
proxyFactory.setAddress("http://localhost:8081/services/baeldung");
|
||||
return proxyFactory;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.xml.ws.Endpoint;
|
||||
|
||||
import org.apache.cxf.Bus;
|
||||
import org.apache.cxf.bus.spring.SpringBus;
|
||||
import org.apache.cxf.jaxws.EndpointImpl;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ServiceConfiguration {
|
||||
@Bean(name = Bus.DEFAULT_BUS_ID)
|
||||
public SpringBus springBus() {
|
||||
return new SpringBus();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Endpoint endpoint() {
|
||||
EndpointImpl endpoint = new EndpointImpl(springBus(), new BaeldungImpl());
|
||||
endpoint.publish("http://localhost:8081/services/baeldung");
|
||||
return endpoint;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
public class Student {
|
||||
private String name;
|
||||
|
||||
Student() {
|
||||
}
|
||||
|
||||
public Student(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.cxf.spring;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
public class StudentTest {
|
||||
private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
|
||||
private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloMethod_thenCorrect() {
|
||||
String response = baeldungProxy.hello("John Doe");
|
||||
assertEquals("Hello John Doe!", response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRegisterMethod_thenCorrect() {
|
||||
Student student1 = new Student("Adam");
|
||||
Student student2 = new Student("Eve");
|
||||
String student1Response = baeldungProxy.register(student1);
|
||||
String student2Response = baeldungProxy.register(student2);
|
||||
|
||||
assertEquals("Adam is registered student number 1", student1Response);
|
||||
assertEquals("Eve is registered student number 2", student2Response);
|
||||
}
|
||||
}
|
41
apache-cxf/pom.xml
Normal file
41
apache-cxf/pom.xml
Normal file
@ -0,0 +1,41 @@
|
||||
<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>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
<module>cxf-spring</module>
|
||||
</modules>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
<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>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.5.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
@ -1,37 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="lib" path="src/test/resources/jars/herold.jar"/>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
@ -1,36 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>apache-fop</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.common.project.facet.core.builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.validation.validationbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
||||
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.3.0.201307091516-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[false]]></enableImports>
|
||||
<configs>
|
||||
<config>src/main/webapp/WEB-INF/api-servlet.xml</config>
|
||||
</configs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
@ -1,6 +1,6 @@
|
||||
<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>org.baeldung</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-fop</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
@ -142,16 +142,12 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.8.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.34</mysql-connector-java.version>
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.5.5</jackson.version>
|
||||
<jackson.version>2.7.2</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.9</org.slf4j.version>
|
||||
@ -161,7 +157,7 @@
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>17.0</guava.version> <!-- upgrade to 18.0 -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.3.2</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
@ -172,14 +168,14 @@
|
||||
<httpcore.version>4.4</httpcore.version>
|
||||
<httpclient.version>4.4</httpclient.version>
|
||||
|
||||
<rest-assured.version>2.4.0</rest-assured.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.12</cargo-maven2-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
|
49
assertj/pom.xml
Normal file
49
assertj/pom.xml
Normal file
@ -0,0 +1,49 @@
|
||||
<?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>assertj</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>19.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-guava</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.assertj.introduction.domain;
|
||||
|
||||
public class Dog {
|
||||
private String name;
|
||||
private Float weight;
|
||||
|
||||
public Dog(String name, Float weight) {
|
||||
this.name = name;
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Float getWeight() {
|
||||
return weight;
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.assertj.introduction.domain;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public Person(String name, Integer age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
@ -0,0 +1,141 @@
|
||||
package com.baeldung.assertj.introduction;
|
||||
|
||||
import com.baeldung.assertj.introduction.domain.Dog;
|
||||
import com.baeldung.assertj.introduction.domain.Person;
|
||||
import org.assertj.core.util.Maps;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class AssertJCoreTest {
|
||||
|
||||
@Test
|
||||
public void whenComparingReferences_thenNotEqual() throws Exception {
|
||||
Dog fido = new Dog("Fido", 5.15f);
|
||||
Dog fidosClone = new Dog("Fido", 5.15f);
|
||||
|
||||
assertThat(fido).isNotEqualTo(fidosClone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingFields_thenEqual() throws Exception {
|
||||
Dog fido = new Dog("Fido", 5.15f);
|
||||
Dog fidosClone = new Dog("Fido", 5.15f);
|
||||
|
||||
assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_thenContains() throws Exception {
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list)
|
||||
.contains("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(list).startsWith("1");
|
||||
assertThat(list).doesNotContainNull();
|
||||
|
||||
assertThat(list)
|
||||
.isNotEmpty()
|
||||
.contains("1")
|
||||
.startsWith("1")
|
||||
.doesNotContainNull()
|
||||
.containsSequence("2", "3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingRunnable_thenIsInterface() throws Exception {
|
||||
assertThat(Runnable.class).isInterface();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||
char someCharacter = 'c';
|
||||
|
||||
assertThat(someCharacter)
|
||||
.isNotEqualTo('a')
|
||||
.inUnicode()
|
||||
.isGreaterThanOrEqualTo('b')
|
||||
.isLowerCase();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
|
||||
assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingWithOffset_thenEquals() throws Exception {
|
||||
assertThat(5.1).isEqualTo(5, withPrecision(1d));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingString_then() throws Exception {
|
||||
assertThat("".isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingFile_then() throws Exception {
|
||||
final File someFile = File.createTempFile("aaa", "bbb");
|
||||
someFile.deleteOnExit();
|
||||
|
||||
assertThat(someFile)
|
||||
.exists()
|
||||
.isFile()
|
||||
.canRead()
|
||||
.canWrite();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIS_then() throws Exception {
|
||||
InputStream given = new ByteArrayInputStream("foo".getBytes());
|
||||
InputStream expected = new ByteArrayInputStream("foo".getBytes());
|
||||
|
||||
assertThat(given).hasSameContentAs(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenMap_then() throws Exception {
|
||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKey(2)
|
||||
.doesNotContainKeys(10)
|
||||
.contains(entry(2, "a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenException_then() throws Exception {
|
||||
Exception ex = new Exception("abc");
|
||||
|
||||
assertThat(ex)
|
||||
.hasNoCause()
|
||||
.hasMessageEndingWith("c");
|
||||
}
|
||||
|
||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||
@Test
|
||||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||
Person person = new Person("Alex", 34);
|
||||
|
||||
assertThat(person.getAge())
|
||||
.as("%s's age should be equal to 100")
|
||||
.isEqualTo(100);
|
||||
}
|
||||
}
|
@ -0,0 +1,121 @@
|
||||
package com.baeldung.assertj.introduction;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.HashBasedTable;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.Table;
|
||||
import com.google.common.collect.TreeRangeMap;
|
||||
import com.google.common.io.Files;
|
||||
import org.assertj.guava.data.MapEntry;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
import static org.assertj.guava.api.Assertions.assertThat;
|
||||
import static org.assertj.guava.api.Assertions.entry;
|
||||
|
||||
public class AssertJGuavaTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
|
||||
final File temp1 = File.createTempFile("bael", "dung1");
|
||||
final File temp2 = File.createTempFile("bael", "dung2");
|
||||
|
||||
assertThat(Files.asByteSource(temp1))
|
||||
.hasSize(0)
|
||||
.hasSameContentAs(Files.asByteSource(temp2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
|
||||
final Multimap<Integer, String> mmap = ArrayListMultimap.create();
|
||||
mmap.put(1, "one");
|
||||
mmap.put(1, "1");
|
||||
|
||||
assertThat(mmap)
|
||||
.hasSize(2)
|
||||
.containsKeys(1)
|
||||
.contains(entry(1, "one"))
|
||||
.contains(entry(1, "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
|
||||
final Multimap<Integer, String> mmap1 = ArrayListMultimap.create();
|
||||
mmap1.put(1, "one");
|
||||
mmap1.put(1, "1");
|
||||
mmap1.put(2, "two");
|
||||
mmap1.put(2, "2");
|
||||
|
||||
final Multimap<Integer, String> mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
|
||||
mmap1_clone.put(1, "one");
|
||||
mmap1_clone.put(1, "1");
|
||||
mmap1_clone.put(2, "two");
|
||||
mmap1_clone.put(2, "2");
|
||||
|
||||
final Multimap<Integer, String> mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
|
||||
mmap2.put(1, "one");
|
||||
mmap2.put(1, "1");
|
||||
|
||||
assertThat(mmap1)
|
||||
.containsAllEntriesOf(mmap2)
|
||||
.containsAllEntriesOf(mmap1_clone)
|
||||
.hasSameEntriesAs(mmap1_clone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||
final Optional<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something)
|
||||
.isPresent()
|
||||
.extractingValue()
|
||||
.isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range)
|
||||
.hasOpenedLowerBound()
|
||||
.isNotEmpty()
|
||||
.hasClosedUpperBound()
|
||||
.contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final TreeRangeMap<Integer, String> map = TreeRangeMap.create();
|
||||
|
||||
map.put(Range.closed(0, 60), "F");
|
||||
map.put(Range.closed(61, 70), "D");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKeys(0)
|
||||
.contains(MapEntry.entry(34, "F"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Table<Integer, String, String> table = HashBasedTable.create(2, 2);
|
||||
|
||||
table.put(1, "A", "PRESENT");
|
||||
table.put(1, "B", "ABSENT");
|
||||
|
||||
assertThat(table)
|
||||
.hasRowCount(1)
|
||||
.containsValues("ABSENT")
|
||||
.containsCell(1, "B", "ABSENT");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
package com.baeldung.assertj.introduction;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static java.time.LocalDate.ofYearDay;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class AssertJJava8Test {
|
||||
|
||||
@Test
|
||||
public void givenOptional_shouldAssert() throws Exception {
|
||||
final Optional<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional)
|
||||
.isPresent()
|
||||
.hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> predicate = s -> s.length() > 4;
|
||||
|
||||
assertThat(predicate)
|
||||
.accepts("aaaaa", "bbbbb")
|
||||
.rejects("a", "b")
|
||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
||||
.rejectsAll(asList("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_shouldAssert() throws Exception {
|
||||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||
final LocalDate todayDate = LocalDate.now();
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDate.of(2020, 7, 8))
|
||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
|
||||
assertThat(todayDate)
|
||||
.isAfter(LocalDate.of(1989, 7, 8))
|
||||
.isToday();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_shouldAssert() throws Exception {
|
||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||
|
||||
assertThat(givenLocalTime)
|
||||
.isAfter(LocalTime.of(1, 0))
|
||||
.hasSameHourAs(LocalTime.of(12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear)
|
||||
.contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::isLeapYear)
|
||||
.contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(Object::getClass)
|
||||
.contains(LocalDate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
||||
.contains(2015, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldSatisfy() throws Exception {
|
||||
final String givenString = "someString";
|
||||
|
||||
assertThat(givenString)
|
||||
.satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldMatch() throws Exception {
|
||||
final String emptyString = "";
|
||||
|
||||
assertThat(emptyString)
|
||||
.matches(String::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||
final List<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList)
|
||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
37
autovalue-tutorial/pom.xml
Normal file
37
autovalue-tutorial/pom.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>autovalue-tutorial</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>AutoValue</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>7</source>
|
||||
<target>7</target>
|
||||
<useIncrementalCompilation>false</useIncrementalCompilation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.auto.value</groupId>
|
||||
<artifactId>auto-value</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.autovalue;
|
||||
|
||||
import com.google.auto.value.AutoValue;
|
||||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoney {
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.autovalue;
|
||||
|
||||
import com.google.auto.value.AutoValue;
|
||||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoneyWithBuilder {
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
|
||||
abstract Builder setAmount(long amount);
|
||||
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.autovalue;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class Foo {
|
||||
private final String text;
|
||||
private final int number;
|
||||
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.autovalue;
|
||||
public final class ImmutableMoney {
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result
|
||||
+ ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.autovalue;
|
||||
|
||||
public class MutableMoney {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
private long amount;
|
||||
private String currency;
|
||||
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package com.baeldung.autovalue;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MoneyTest {
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
}
|
52
cdi/pom.xml
Normal file
52
cdi/pom.xml
Normal file
@ -0,0 +1,52 @@
|
||||
<?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>cdi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>1.8.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>2.3.5.Final</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
14
cdi/src/main/java/com/baeldung/interceptor/Audited.java
Normal file
14
cdi/src/main/java/com/baeldung/interceptor/Audited.java
Normal file
@ -0,0 +1,14 @@
|
||||
package com.baeldung.interceptor;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.interceptor.InterceptorBinding;
|
||||
|
||||
@InterceptorBinding
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Audited {
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.interceptor;
|
||||
|
||||
import javax.interceptor.AroundInvoke;
|
||||
import javax.interceptor.Interceptor;
|
||||
import javax.interceptor.InvocationContext;
|
||||
|
||||
@Audited
|
||||
@Interceptor
|
||||
public class AuditedInterceptor {
|
||||
public static boolean calledBefore = false;
|
||||
public static boolean calledAfter = false;
|
||||
|
||||
@AroundInvoke
|
||||
public Object auditMethod(InvocationContext ctx) throws Exception {
|
||||
calledBefore = true;
|
||||
Object result = ctx.proceed();
|
||||
calledAfter = true;
|
||||
return result;
|
||||
}
|
||||
}
|
10
cdi/src/main/java/com/baeldung/service/SuperService.java
Normal file
10
cdi/src/main/java/com/baeldung/service/SuperService.java
Normal file
@ -0,0 +1,10 @@
|
||||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.interceptor.Audited;
|
||||
|
||||
public class SuperService {
|
||||
@Audited
|
||||
public String deliverService(String uid) {
|
||||
return uid;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.spring.aspect;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@Aspect
|
||||
public class SpringTestAspect {
|
||||
@Autowired
|
||||
private List<String> accumulator;
|
||||
|
||||
@Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
|
||||
public Object auditMethod(ProceedingJoinPoint jp) throws Throwable {
|
||||
String methodName = jp.getSignature().getName();
|
||||
accumulator.add("Call to " + methodName);
|
||||
Object obj = jp.proceed();
|
||||
accumulator.add("Method called successfully: " + methodName);
|
||||
return obj;
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.spring.configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
import com.baeldung.spring.aspect.SpringTestAspect;
|
||||
import com.baeldung.spring.service.SpringSuperService;
|
||||
|
||||
@Configuration
|
||||
@EnableAspectJAutoProxy
|
||||
public class AppConfig {
|
||||
@Bean
|
||||
public SpringSuperService springSuperService() {
|
||||
return new SpringSuperService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringTestAspect springTestAspect() {
|
||||
return new SpringTestAspect();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public List<String> getAccumulator() {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.spring.service;
|
||||
|
||||
public class SpringSuperService {
|
||||
public String getInfoFromService(String code) {
|
||||
return code;
|
||||
}
|
||||
}
|
8
cdi/src/main/resources/META-INF/beans.xml
Normal file
8
cdi/src/main/resources/META-INF/beans.xml
Normal file
@ -0,0 +1,8 @@
|
||||
<beans xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/beans_1_2.xsd">
|
||||
<interceptors>
|
||||
<class>com.baeldung.interceptor.AuditedInterceptor</class>
|
||||
</interceptors>
|
||||
</beans>
|
38
cdi/src/test/java/com/baeldung/test/TestInterceptor.java
Normal file
38
cdi/src/test/java/com/baeldung/test/TestInterceptor.java
Normal file
@ -0,0 +1,38 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.interceptor.AuditedInterceptor;
|
||||
import com.baeldung.service.SuperService;
|
||||
|
||||
public class TestInterceptor {
|
||||
Weld weld;
|
||||
WeldContainer container;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
weld = new Weld();
|
||||
container = weld.initialize();
|
||||
}
|
||||
|
||||
@After
|
||||
public void shutdown() {
|
||||
weld.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() {
|
||||
SuperService superService = container.select(SuperService.class).get();
|
||||
String code = "123456";
|
||||
superService.deliverService(code);
|
||||
|
||||
Assert.assertTrue(AuditedInterceptor.calledBefore);
|
||||
Assert.assertTrue(AuditedInterceptor.calledAfter);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.spring.configuration.AppConfig;
|
||||
import com.baeldung.spring.service.SpringSuperService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = { AppConfig.class })
|
||||
public class TestSpringInterceptor {
|
||||
@Autowired
|
||||
SpringSuperService springSuperService;
|
||||
|
||||
@Autowired
|
||||
private List<String> accumulator;
|
||||
|
||||
@Test
|
||||
public void givenService_whenServiceAndAspectExecuted_thenOk() {
|
||||
String code = "123456";
|
||||
String result = springSuperService.getInfoFromService(code);
|
||||
Assert.assertThat(accumulator.size(), is(2));
|
||||
Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
|
||||
Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>core-java-8</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src/main/webapp"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
@ -1,101 +0,0 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
|
||||
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
|
||||
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
|
||||
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
|
||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
|
||||
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
||||
org.eclipse.jdt.core.compiler.compliance=1.8
|
||||
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
||||
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
||||
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
||||
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
|
||||
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deadCode=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
|
||||
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
|
||||
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
|
||||
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
|
||||
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
|
||||
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
|
||||
org.eclipse.jdt.core.compiler.source=1.8
|
@ -1,57 +0,0 @@
|
||||
eclipse.preferences.version=1
|
||||
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
|
||||
sp_cleanup.add_default_serial_version_id=true
|
||||
sp_cleanup.add_generated_serial_version_id=false
|
||||
sp_cleanup.add_missing_annotations=true
|
||||
sp_cleanup.add_missing_deprecated_annotations=true
|
||||
sp_cleanup.add_missing_methods=false
|
||||
sp_cleanup.add_missing_nls_tags=false
|
||||
sp_cleanup.add_missing_override_annotations=true
|
||||
sp_cleanup.add_missing_override_annotations_interface_methods=true
|
||||
sp_cleanup.add_serial_version_id=false
|
||||
sp_cleanup.always_use_blocks=true
|
||||
sp_cleanup.always_use_parentheses_in_expressions=true
|
||||
sp_cleanup.always_use_this_for_non_static_field_access=false
|
||||
sp_cleanup.always_use_this_for_non_static_method_access=false
|
||||
sp_cleanup.convert_functional_interfaces=false
|
||||
sp_cleanup.convert_to_enhanced_for_loop=true
|
||||
sp_cleanup.correct_indentation=true
|
||||
sp_cleanup.format_source_code=true
|
||||
sp_cleanup.format_source_code_changes_only=true
|
||||
sp_cleanup.make_local_variable_final=true
|
||||
sp_cleanup.make_parameters_final=true
|
||||
sp_cleanup.make_private_fields_final=false
|
||||
sp_cleanup.make_type_abstract_if_missing_method=false
|
||||
sp_cleanup.make_variable_declarations_final=true
|
||||
sp_cleanup.never_use_blocks=false
|
||||
sp_cleanup.never_use_parentheses_in_expressions=false
|
||||
sp_cleanup.on_save_use_additional_actions=true
|
||||
sp_cleanup.organize_imports=true
|
||||
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
|
||||
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
|
||||
sp_cleanup.remove_private_constructors=true
|
||||
sp_cleanup.remove_trailing_whitespaces=true
|
||||
sp_cleanup.remove_trailing_whitespaces_all=true
|
||||
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
|
||||
sp_cleanup.remove_unnecessary_casts=true
|
||||
sp_cleanup.remove_unnecessary_nls_tags=false
|
||||
sp_cleanup.remove_unused_imports=true
|
||||
sp_cleanup.remove_unused_local_variables=false
|
||||
sp_cleanup.remove_unused_private_fields=true
|
||||
sp_cleanup.remove_unused_private_members=false
|
||||
sp_cleanup.remove_unused_private_methods=true
|
||||
sp_cleanup.remove_unused_private_types=true
|
||||
sp_cleanup.sort_members=false
|
||||
sp_cleanup.sort_members_all=false
|
||||
sp_cleanup.use_anonymous_class_creation=false
|
||||
sp_cleanup.use_blocks=true
|
||||
sp_cleanup.use_blocks_only_for_return_and_throw=false
|
||||
sp_cleanup.use_lambda=false
|
||||
sp_cleanup.use_parentheses_in_expressions=false
|
||||
sp_cleanup.use_this_for_non_static_field_access=true
|
||||
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
|
||||
sp_cleanup.use_this_for_non_static_method_access=true
|
||||
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
|
@ -1,4 +0,0 @@
|
||||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.3.0.201307091516-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[false]]></enableImports>
|
||||
<configs>
|
||||
<config>src/main/webapp/WEB-INF/api-servlet.xml</config>
|
||||
</configs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
@ -3,4 +3,22 @@
|
||||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||
- [Guide to Java 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,10 +1,12 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>spring-rest</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>spring-rest</name>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>core-java8</artifactId>
|
||||
|
||||
<name>core-java8</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@ -40,6 +42,12 @@
|
||||
<version>3.3.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
@ -56,6 +64,13 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
@ -97,6 +112,9 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
@ -114,9 +132,9 @@
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Period;
|
||||
|
||||
public class UseDuration {
|
||||
|
||||
public LocalTime modifyDates(LocalTime localTime,Duration duration){
|
||||
return localTime.plus(duration);
|
||||
}
|
||||
|
||||
public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
|
||||
return Duration.between(localTime1, localTime2);
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
public class UseLocalDate {
|
||||
|
||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateUsingParseMethod(String representation){
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateFromClock(){
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public LocalDate getNextDay(LocalDate localDate){
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
public LocalDate getPreviousDay(LocalDate localDate){
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
public DayOfWeek getDayOfWeek(LocalDate localDate){
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
public LocalDate getFirstDayOfMonth(){
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartOfDay(LocalDate localDate){
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
|
||||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
|
||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
|
||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeFromClock(){
|
||||
LocalTime localTime = LocalTime.now();
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime addAnHour(LocalTime localTime){
|
||||
LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
|
||||
return newTime;
|
||||
}
|
||||
|
||||
public int getHourFromLocalTime(LocalTime localTime){
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
public class UsePeriod {
|
||||
|
||||
public LocalDate modifyDates(LocalDate localDate,Period period){
|
||||
return localDate.plus(period);
|
||||
}
|
||||
|
||||
public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date){
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar){
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class UseZonedDateTime {
|
||||
|
||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||
return zonedDateTime;
|
||||
}
|
||||
}
|
91
core-java-8/src/main/java/com/baeldung/enums/Pizza.java
Normal file
91
core-java-8/src/main/java/com/baeldung/enums/Pizza.java
Normal file
@ -0,0 +1,91 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED(5) {
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
READY(2) {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
DELIVERED(0) {
|
||||
@Override
|
||||
public boolean isDelivered() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private int timeToDelivery;
|
||||
|
||||
public boolean isOrdered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDelivered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatusEnum(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isDeliverable() {
|
||||
return this.status.isReady();
|
||||
}
|
||||
|
||||
public void printTimeToDeliver() {
|
||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(
|
||||
Collectors.groupingBy(Pizza::getStatus,
|
||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in express mode");
|
||||
}
|
||||
},
|
||||
NORMAL {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in normal mode");
|
||||
}
|
||||
};
|
||||
|
||||
public abstract void deliver(Pizza pz);
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE;
|
||||
|
||||
PizzaDeliverySystemConfiguration() {
|
||||
// Do the configuration initialization which
|
||||
// involves overriding defaults like delivery strategy
|
||||
}
|
||||
|
||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
||||
|
||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
||||
return deliveryStrategy;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveAction;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CustomRecursiveAction extends RecursiveAction {
|
||||
|
||||
private String workLoad = "";
|
||||
private static final int THRESHOLD = 4;
|
||||
|
||||
private static Logger logger = Logger.getAnonymousLogger();
|
||||
|
||||
public CustomRecursiveAction(String workLoad) {
|
||||
this.workLoad = workLoad;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void compute() {
|
||||
|
||||
if (workLoad.length() > THRESHOLD) {
|
||||
ForkJoinTask.invokeAll(createSubtasks());
|
||||
} else {
|
||||
processing(workLoad);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||
|
||||
List<CustomRecursiveAction> subtasks =
|
||||
new ArrayList<>();
|
||||
|
||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
||||
|
||||
subtasks.add(new CustomRecursiveAction(partOne));
|
||||
subtasks.add(new CustomRecursiveAction(partTwo));
|
||||
|
||||
return subtasks;
|
||||
}
|
||||
|
||||
private void processing(String work) {
|
||||
String result = work.toUpperCase();
|
||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
|
||||
public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||
|
||||
private int[] arr;
|
||||
|
||||
private static final int THRESHOLD = 20;
|
||||
|
||||
public CustomRecursiveTask(int[] arr) {
|
||||
this.arr = arr;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
|
||||
if (arr.length > THRESHOLD) {
|
||||
|
||||
return ForkJoinTask.invokeAll(createSubtasks())
|
||||
.stream()
|
||||
.mapToInt(ForkJoinTask::join)
|
||||
.sum();
|
||||
|
||||
} else {
|
||||
return processing(arr);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||
dividedTasks.add(new CustomRecursiveTask(
|
||||
Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||
dividedTasks.add(new CustomRecursiveTask(
|
||||
Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||
return dividedTasks;
|
||||
}
|
||||
|
||||
private Integer processing(int[] arr) {
|
||||
return Arrays.stream(arr)
|
||||
.filter(a -> a > 10 && a < 27)
|
||||
.map(a -> a * 10)
|
||||
.sum();
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.forkjoin.util;
|
||||
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
public class PoolUtil {
|
||||
|
||||
public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[]{23, 15};
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
//do nothing
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.streamApi;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Created by Alex Vengr
|
||||
*/
|
||||
public class Product {
|
||||
|
||||
private int price;
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean utilize;
|
||||
|
||||
public Product(int price, String name) {
|
||||
this(price);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Product(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Product() {
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public static Stream<String> streamOf(List<String> list) {
|
||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CountingTask extends RecursiveTask<Integer> {
|
||||
|
||||
private final TreeNode node;
|
||||
|
||||
public CountingTask(TreeNode node) {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
return node.value + node.children.stream()
|
||||
.map(childNode -> new CountingTask(childNode).fork())
|
||||
.collect(Collectors.summingInt(ForkJoinTask::join));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
|
||||
/**
|
||||
* This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging.
|
||||
* Without the exiting executor service, the task would hang indefinitely.
|
||||
* This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests.
|
||||
*/
|
||||
public class ExitingExecutorServiceExample {
|
||||
|
||||
public static void main(String... args) {
|
||||
|
||||
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||
|
||||
executorService.submit(() -> {
|
||||
while (true) {
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
int value;
|
||||
|
||||
Set<TreeNode> children;
|
||||
|
||||
public TreeNode(int value, TreeNode... children) {
|
||||
this.value = value;
|
||||
this.children = Sets.newHashSet(children);
|
||||
}
|
||||
|
||||
}
|
30
core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
30
core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.baeldung.unzip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
public class UnzipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String fileZip = "src/main/resources/compressed.zip";
|
||||
final byte[] buffer = new byte[1024];
|
||||
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
|
||||
ZipEntry zipEntry = zis.getNextEntry();
|
||||
while (zipEntry != null) {
|
||||
final String fileName = zipEntry.getName();
|
||||
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
|
||||
final FileOutputStream fos = new FileOutputStream(newFile);
|
||||
int len;
|
||||
while ((len = zis.read(buffer)) > 0) {
|
||||
fos.write(buffer, 0, len);
|
||||
}
|
||||
fos.close();
|
||||
zipEntry = zis.getNextEntry();
|
||||
}
|
||||
zis.closeEntry();
|
||||
zis.close();
|
||||
}
|
||||
}
|
43
core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
Normal file
43
core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
Normal file
@ -0,0 +1,43 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipDirectory {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
|
||||
zipFile(fileToZip, fileToZip.getName(), zipOut);
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
|
||||
if (fileToZip.isHidden()) {
|
||||
return;
|
||||
}
|
||||
if (fileToZip.isDirectory()) {
|
||||
final File[] children = fileToZip.listFiles();
|
||||
for (final File childFile : children) {
|
||||
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
}
|
28
core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
28
core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
@ -0,0 +1,28 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest/test1.txt";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
zipOut.close();
|
||||
fis.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipMultipleFiles {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
for (final String srcFile : srcFiles) {
|
||||
final File fileToZip = new File(srcFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
BIN
core-java-8/src/main/resources/compressed.zip
Normal file
BIN
core-java-8/src/main/resources/compressed.zip
Normal file
Binary file not shown.
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