merged my master with upstream/eugenp master
This commit is contained in:
commit
ff2cffa1f0
|
@ -7,8 +7,11 @@
|
|||
|
||||
# Eclipse
|
||||
.settings/
|
||||
*.project
|
||||
*.classpath
|
||||
.prefs
|
||||
*.prefs
|
||||
.metadata/
|
||||
|
||||
# Intellij
|
||||
.idea/
|
||||
|
@ -23,3 +26,4 @@ log/
|
|||
target/
|
||||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
|
|
17
.project
17
.project
|
@ -1,17 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>parent-modules</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</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>
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
<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>
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<configuration>
|
||||
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
|
||||
</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.5.0</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>jetty9x</containerId>
|
||||
<type>embedded</type>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.hostname>localhost</cargo.hostname>
|
||||
<cargo.servlet.port>8080</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>
|
||||
<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-web</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,9 @@
|
|||
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,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,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
|
||||
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
|
||||
<bean id="client" factory-bean="clientFactory" factory-method="create" />
|
||||
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
|
||||
<property name="serviceClass" value="com.baeldung.cxf.spring.Baeldung" />
|
||||
<property name="address" value="http://localhost:8080/services/baeldung" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
|
||||
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
|
||||
<jaxws:endpoint id="baeldung"
|
||||
implementor="com.baeldung.cxf.spring.BaeldungImpl" address="http://localhost:8080/services/baeldung" />
|
||||
</beans>
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
version="3.0"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
|
||||
<servlet>
|
||||
<servlet-name>cxf</servlet-name>
|
||||
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>cxf</servlet-name>
|
||||
<url-pattern>/services/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
</web-app>
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.cxf.spring;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
public class StudentTest {
|
||||
private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client-beans.xml" });
|
||||
private Baeldung baeldungProxy;
|
||||
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -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,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>
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>core-java8</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
|
@ -3,9 +3,12 @@
|
|||
## 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)
|
||||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
|
@ -41,6 +41,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>
|
||||
|
@ -57,6 +63,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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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,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,265 @@
|
|||
package com.baeldung.collectors;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
import static com.google.common.collect.Sets.newHashSet;
|
||||
import static java.util.stream.Collectors.averagingDouble;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.partitioningBy;
|
||||
import static java.util.stream.Collectors.summarizingDouble;
|
||||
import static java.util.stream.Collectors.summingDouble;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toMap;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class Java8CollectorsTest {
|
||||
|
||||
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(toList());
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream()
|
||||
.collect(toSet());
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList.stream()
|
||||
.collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream()
|
||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining());
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining(" "));
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList.stream()
|
||||
.collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result)
|
||||
.containsKeys(true, false)
|
||||
.satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true))
|
||||
.contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false))
|
||||
.contains("a", "bb", "dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList.stream()
|
||||
.collect(counting());
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList.stream()
|
||||
.collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage())
|
||||
.isEqualTo(2);
|
||||
assertThat(result.getCount())
|
||||
.isEqualTo(4);
|
||||
assertThat(result.getMax())
|
||||
.isEqualTo(3);
|
||||
assertThat(result.getMin())
|
||||
.isEqualTo(1);
|
||||
assertThat(result.getSum())
|
||||
.isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList.stream()
|
||||
.collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList.stream()
|
||||
.collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result)
|
||||
.isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList.stream()
|
||||
.collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result)
|
||||
.isPresent()
|
||||
.hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList.stream()
|
||||
.collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry(1, newHashSet("a"))
|
||||
.containsEntry(2, newHashSet("bb", "dd"))
|
||||
.containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList.stream()
|
||||
.collect(toImmutableSet());
|
||||
|
||||
assertThat(result)
|
||||
.isInstanceOf(ImmutableSet.class)
|
||||
.contains("a", "bb", "ccc", "dd");
|
||||
|
||||
}
|
||||
|
||||
private static <T> ImmutableSetCollector<T> toImmutableSet() {
|
||||
return new ImmutableSetCollector<>();
|
||||
}
|
||||
|
||||
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
|
||||
|
||||
@Override
|
||||
public Supplier<ImmutableSet.Builder<T>> supplier() {
|
||||
return ImmutableSet::builder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
|
||||
return ImmutableSet.Builder::add;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
|
||||
return (left, right) -> left.addAll(right.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
|
||||
return ImmutableSet.Builder::build;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Characteristics> characteristics() {
|
||||
return Sets.immutableEnumSet(Characteristics.UNORDERED);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.dateapi;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class ConversionExample {
|
||||
public static void main(String[] args) {
|
||||
Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
|
||||
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
|
||||
Date dateFromInstant = Date.from(Instant.now());
|
||||
GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
|
||||
Instant instantFromDate = new Date().toInstant();
|
||||
ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.dateapi;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.YearMonth;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JavaUtilTimeTest {
|
||||
|
||||
@Test
|
||||
public void currentTime() {
|
||||
final LocalDate now = LocalDate.now();
|
||||
|
||||
System.out.println(now);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificTime() {
|
||||
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
|
||||
|
||||
System.out.println(birthDay);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractMonth() {
|
||||
Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
|
||||
|
||||
assertThat(month).isEqualTo(Month.DECEMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subtractTime() {
|
||||
LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
|
||||
|
||||
assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alterField() {
|
||||
LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
|
||||
|
||||
assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncate() {
|
||||
LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
|
||||
|
||||
assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTimeSpan() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime hourLater = now.plusHours(1);
|
||||
Duration span = Duration.between(now, hourLater);
|
||||
|
||||
assertThat(span).isEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void formatAndParse() throws ParseException {
|
||||
LocalDate someDate = LocalDate.of(2016, 12, 7);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
String formattedDate = someDate.format(formatter);
|
||||
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
|
||||
|
||||
assertThat(formattedDate).isEqualTo("2016-12-07");
|
||||
assertThat(parsedDate).isEqualTo(someDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void daysInMonth() {
|
||||
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
|
||||
|
||||
assertThat(daysInMonth).isEqualTo(28);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalDateTest {
|
||||
|
||||
UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalDate(){
|
||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDate(){
|
||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingClock_thenLocalDate(){
|
||||
Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingPlus_thenNextDay(){
|
||||
Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingMinus_thenPreviousDay(){
|
||||
Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
|
||||
Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
|
||||
Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
|
||||
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalDateTimeTest {
|
||||
|
||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDateTime(){
|
||||
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
||||
Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalTimeTest {
|
||||
|
||||
UseLocalTime useLocalTime = new UseLocalTime();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalTime(){
|
||||
Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalTime(){
|
||||
Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTime_whenAddHour_thenLocalTime(){
|
||||
Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getHourFromLocalTime(){
|
||||
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocalTimeWithMinuteSetToValue(){
|
||||
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Period;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UsePeriodTest {
|
||||
UsePeriod usingPeriod=new UsePeriod();
|
||||
|
||||
@Test
|
||||
public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
|
||||
Period period = Period.ofDays(1);
|
||||
LocalDate localDate = LocalDate.parse("2007-05-10");
|
||||
Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_thenGetPeriod(){
|
||||
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
||||
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
||||
|
||||
Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseZonedDateTimeTest {
|
||||
|
||||
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
||||
|
||||
@Test
|
||||
public void givenZoneId_thenZonedDateTime(){
|
||||
ZoneId zoneId=ZoneId.of("Europe/Paris");
|
||||
ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||
Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
public class PizzaTest {
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||
Pizza testPz = new Pizza();
|
||||
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
assertTrue(testPz.isDeliverable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
|
||||
assertTrue(undeliveredPzs.size() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
|
||||
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Vehicle;
|
||||
import com.baeldung.java_8_features.VehicleImpl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8DefaultStaticIntefaceMethodsTest {
|
||||
|
||||
@Test
|
||||
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
||||
Vehicle vehicle = new VehicleImpl();
|
||||
String overview = vehicle.getOverview();
|
||||
long[] startPosition = vehicle.startPosition();
|
||||
|
||||
assertEquals(overview, "ATV made by N&F Vehicles");
|
||||
assertEquals(startPosition[0], 23);
|
||||
assertEquals(startPosition[1], 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
|
||||
String producer = Vehicle.producer();
|
||||
assertEquals(producer, "N&F Vehicles");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.User;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8MethodReferenceTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStaticMethodReferences_whenWork_thenCorrect() {
|
||||
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(new User());
|
||||
users.add(new User());
|
||||
boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
|
||||
boolean isRealRef = users.stream().anyMatch(User::isRealUser);
|
||||
assertTrue(isReal);
|
||||
assertTrue(isRealRef);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkInstanceMethodReferences_whenWork_thenCorrect() {
|
||||
User user = new User();
|
||||
boolean isLegalName = list.stream().anyMatch(user::isLegalName);
|
||||
assertTrue(isLegalName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParticularTypeReferences_whenWork_thenCorrect() {
|
||||
long count = list.stream().filter(String::isEmpty).count();
|
||||
assertEquals(count, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkConstructorReferences_whenWork_thenCorrect() {
|
||||
Stream<User> stream = list.stream().map(User::new);
|
||||
List<User> userList = stream.collect(Collectors.toList());
|
||||
assertEquals(userList.size(), list.size());
|
||||
assertTrue(userList.get(0) instanceof User);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8OptionalTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptional_whenAsExpected_thenCorrect() {
|
||||
|
||||
Optional<String> optionalEmpty = Optional.empty();
|
||||
assertFalse(optionalEmpty.isPresent());
|
||||
|
||||
String str = "value";
|
||||
Optional<String> optional = Optional.of(str);
|
||||
assertEquals(optional.get(), "value");
|
||||
|
||||
Optional<String> optionalNullable = Optional.ofNullable(str);
|
||||
Optional<String> optionalNull = Optional.ofNullable(null);
|
||||
assertEquals(optionalNullable.get(), "value");
|
||||
assertFalse(optionalNull.isPresent());
|
||||
|
||||
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
|
||||
List<String> listNull = null;
|
||||
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
|
||||
assertTrue(listOpt == list);
|
||||
assertTrue(listOptNull.isEmpty());
|
||||
|
||||
Optional<User> user = Optional.ofNullable(getUser());
|
||||
String result = user.map(User::getAddress)
|
||||
.map(Address::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(result, "1st Avenue");
|
||||
|
||||
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
||||
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
|
||||
.flatMap(OptionalAddress::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultOpt, "1st Avenue");
|
||||
|
||||
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
||||
String resultNull = userNull.map(User::getAddress)
|
||||
.map(Address::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultNull, "not specified");
|
||||
|
||||
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
||||
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
|
||||
.flatMap(OptionalAddress::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultOptNull, "not specified");
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = CustomException.class)
|
||||
public void callMethod_whenCustomException_thenCorrect() {
|
||||
User user = new User();
|
||||
String result = user.getOrThrow();
|
||||
}
|
||||
|
||||
private User getUser() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUser() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUserNull() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private User getUserNull() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,263 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.streamApi.Product;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamApiTest {
|
||||
|
||||
private long counter;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
|
||||
|
||||
private List<Product> productList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
productList = Arrays.asList(
|
||||
new Product(23, "potatoes"), new Product(14, "orange"),
|
||||
new Product(13, "lemon"), new Product(23, "bread"),
|
||||
new Product(13, "sugar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
long size = list.stream().skip(1)
|
||||
.map(element -> element.substring(0, 3)).count();
|
||||
assertEquals(list.size() - 1, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
|
||||
counter = 0;
|
||||
long sizeFirst = list.stream()
|
||||
.skip(2).map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).count();
|
||||
assertEquals(1, counter);
|
||||
|
||||
counter = 0;
|
||||
long sizeSecond = list.stream().map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).skip(2).count();
|
||||
assertEquals(3, counter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createEmptyStream_whenEmpty_thenCorrect() {
|
||||
|
||||
Stream<String> streamEmpty = Stream.empty();
|
||||
assertEquals(0, streamEmpty.count());
|
||||
|
||||
List<String> names = Collections.emptyList();
|
||||
Stream<String> streamOf = Product.streamOf(names);
|
||||
assertTrue(streamOf.count() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenCreated_thenCorrect() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> streamOfCollection = collection.stream();
|
||||
assertEquals(3, streamOfCollection.count());
|
||||
|
||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||
assertEquals(3, streamOfArray.count());
|
||||
|
||||
String[] arr = new String[]{"a", "b", "c"};
|
||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
IntStream intStream = IntStream.range(1, 3);
|
||||
LongStream longStream = LongStream.rangeClosed(1, 3);
|
||||
Random random = new Random();
|
||||
DoubleStream doubleStream = random.doubles(3);
|
||||
assertEquals(2, intStream.count());
|
||||
assertEquals(3, longStream.count());
|
||||
assertEquals(3, doubleStream.count());
|
||||
|
||||
IntStream streamOfChars = "abc".chars();
|
||||
IntStream str = "".chars();
|
||||
assertEquals(3, streamOfChars.count());
|
||||
|
||||
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
|
||||
assertEquals("a", streamOfString.findFirst().get());
|
||||
|
||||
Path path = getPath();
|
||||
Stream<String> streamOfStrings = null;
|
||||
try {
|
||||
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
|
||||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
assertEquals(10, streamGenerated.count());
|
||||
|
||||
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
|
||||
assertTrue(40 <= streamIterated.findAny().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> stream = list.stream()
|
||||
.filter(element -> {
|
||||
log.info("filter() was called");
|
||||
return element.contains("2");
|
||||
}).map(element -> {
|
||||
log.info("map() was called");
|
||||
return element.toUpperCase();
|
||||
}).findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reduce_whenExpected_thenCorrect() {
|
||||
|
||||
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
|
||||
assertEquals(6, reduced.getAsInt());
|
||||
|
||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||
assertEquals(16, reducedTwoParams);
|
||||
|
||||
int reducedThreeParams = Stream.of(1, 2, 3)
|
||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(16, reducedThreeParams);
|
||||
|
||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
|
||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(36, reducedThreeParamsParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void collecting_whenAsExpected_thenCorrect() {
|
||||
|
||||
List<String> collectorCollection = productList.stream()
|
||||
.map(Product::getName).collect(Collectors.toList());
|
||||
|
||||
assertTrue(collectorCollection instanceof List);
|
||||
assertEquals(5, collectorCollection.size());
|
||||
|
||||
String listToString = productList.stream().map(Product::getName)
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||
|
||||
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
|
||||
assertTrue(17.2 == averagePrice);
|
||||
|
||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||
assertEquals(86, summingPrice);
|
||||
|
||||
IntSummaryStatistics statistics = productList.stream()
|
||||
.collect(Collectors.summarizingInt(Product::getPrice));
|
||||
assertEquals(23, statistics.getMax());
|
||||
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream()
|
||||
.collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream()
|
||||
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
assertEquals(2, mapPartioned.keySet().size());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void collect_whenThrows_thenCorrect() {
|
||||
Set<Product> unmodifiableSet = productList.stream()
|
||||
.collect(Collectors.collectingAndThen(Collectors.toSet(),
|
||||
Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList =
|
||||
Collector.of(LinkedList::new, LinkedList::add,
|
||||
(first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||
boolean isParallel = streamOfCollection.isParallel();
|
||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
|
||||
.anyMatch(price -> price > 200);
|
||||
assertTrue(isParallel && haveBigPrice);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsParallel_thenCorrect() {
|
||||
IntStream intStreamParallel =
|
||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertTrue(isParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsSequential_thenCorrect() {
|
||||
IntStream intStreamParallel =
|
||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertFalse(isParallel);
|
||||
}
|
||||
|
||||
private Path getPath() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Files.createTempFile(null, ".txt");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write("a\nb\nc");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void wasCalled() {
|
||||
counter++;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,113 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Detail;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamsTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||
String[] arr = new String[]{"a", "b", "c"};
|
||||
Stream<String> streamArr = Arrays.stream(arr);
|
||||
assertEquals(streamArr.count(), 3);
|
||||
|
||||
Stream<String> streamOf = Stream.of("a", "b", "c");
|
||||
assertEquals(streamOf.count(), 3);
|
||||
|
||||
long count = list.stream().distinct().count();
|
||||
assertEquals(count, 9);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
uris.add("C:\\My.txt");
|
||||
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
|
||||
assertEquals(streamMap.count(), 1);
|
||||
|
||||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream()
|
||||
.flatMap(detail -> detail.getParts().stream());
|
||||
assertEquals(streamFlatMap.count(), 4);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||
boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
|
||||
boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
|
||||
assertTrue(isValid);
|
||||
assertFalse(isValidOne);
|
||||
assertFalse(isValidTwo);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||
List<Integer> integers = new ArrayList<>();
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
|
||||
assertTrue(reduced == 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream()
|
||||
.map(element -> element.toUpperCase())
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(resultList.size(), list.size());
|
||||
assertTrue(resultList.contains(""));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkParallelStream_whenDoWork() {
|
||||
list.parallelStream().forEach(element -> doWork(element));
|
||||
}
|
||||
|
||||
private void doWork(String string) {
|
||||
assertTrue(true); //just imitate an amount of work
|
||||
}
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<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="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<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="owner.project.facets" value="java"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<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>core-java</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,5 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src/main/webapp"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
|
@ -1,95 +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.targetPlatform=1.7
|
||||
org.eclipse.jdt.core.compiler.compliance=1.7
|
||||
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=error
|
||||
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=error
|
||||
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.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.7
|
|
@ -1,55 +0,0 @@
|
|||
#Sat Jan 21 23:04:06 EET 2012
|
||||
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_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_blocks=false
|
||||
sp_cleanup.use_blocks_only_for_return_and_throw=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,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="spring-rest">
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
||||
<property name="context-root" value="spring-rest"/>
|
||||
<property name="java-output-path" value="/spring-rest/target/classes"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
|
@ -1,4 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<installed facet="java" version="1.7"/>
|
||||
</faceted-project>
|
|
@ -1 +0,0 @@
|
|||
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
|
|
@ -1 +0,0 @@
|
|||
Window
|
|
@ -1,14 +0,0 @@
|
|||
DELEGATES_PREFERENCE=delegateValidatorList
|
||||
USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300
|
||||
eclipse.preferences.version=1
|
||||
override=true
|
||||
suspend=false
|
||||
vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
|
||||
vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
|
||||
vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
|
||||
vf.version=3
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.wst.ws.service.policy.projectEnabled=false
|
|
@ -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>
|
|
@ -9,7 +9,11 @@
|
|||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>4.01</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
|
@ -97,6 +101,22 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>${testng.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
|
@ -122,8 +142,8 @@
|
|||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
@ -165,6 +185,8 @@
|
|||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<testng.version>6.8</testng.version>
|
||||
<assertj.version>3.5.1</assertj.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.commons.collections15.Predicate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatus> undeliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
|
||||
|
||||
private PizzaStatus status;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
public enum PizzaStatus {
|
||||
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;
|
||||
}
|
||||
|
||||
@JsonProperty("timeToDelivery")
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatus(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatus 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) -> undeliveredPizzaStatuses.contains(s.getStatus()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatus, List<Pizza>>
|
||||
groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(
|
||||
Collectors.groupingBy(Pizza::getStatus,
|
||||
() -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatus.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getJsonString(Pizza pz) throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
|
||||
}
|
||||
|
||||
private static Predicate<Pizza> thatAreNotDelivered() {
|
||||
return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
|
||||
}
|
||||
}
|
|
@ -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,21 @@
|
|||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.<Integer> newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
|
||||
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,80 @@
|
|||
package org.baeldung.java.enums;
|
||||
|
||||
|
||||
import com.baeldung.enums.Pizza;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
|
||||
public class PizzaTest {
|
||||
@Test
|
||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||
Pizza testPz = new Pizza();
|
||||
testPz.setStatus(Pizza.PizzaStatus.READY);
|
||||
assertTrue(testPz.isDeliverable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatus.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
|
||||
assertTrue(undeliveredPzs.size() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
|
||||
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatus.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
EnumMap<Pizza.PizzaStatus, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||
assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1);
|
||||
assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2);
|
||||
assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatus.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package org.baeldung.java.lists;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ListAssertJTest {
|
||||
|
||||
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
|
||||
|
||||
@Test
|
||||
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
|
||||
assertThat(list1)
|
||||
.isEqualTo(list2)
|
||||
.isNotEqualTo(list3);
|
||||
|
||||
assertThat(list1.equals(list2)).isTrue();
|
||||
assertThat(list1.equals(list3)).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package org.baeldung.java.lists;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ListJUnitTest {
|
||||
|
||||
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
|
||||
|
||||
@Test
|
||||
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
|
||||
Assert.assertEquals(list1, list2);
|
||||
Assert.assertNotSame(list1, list2);
|
||||
Assert.assertNotEquals(list1, list3);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package org.baeldung.java.lists;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ListTestNGTest {
|
||||
|
||||
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
|
||||
|
||||
@Test
|
||||
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
|
||||
Assert.assertEquals(list1, list2);
|
||||
Assert.assertNotSame(list1, list2);
|
||||
Assert.assertNotEquals(list1, list3);
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
|
|
@ -0,0 +1,233 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
#
|
||||
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
|
||||
# for the new JDKs provided by Oracle.
|
||||
#
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
|
||||
#
|
||||
# Oracle JDKs
|
||||
#
|
||||
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
|
||||
#
|
||||
# Apple JDKs
|
||||
#
|
||||
export JAVA_HOME=`/usr/libexec/java_home`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Migwn, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
local basedir=$(pwd)
|
||||
local wdir=$(pwd)
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
wdir=$(cd "$wdir/.."; pwd)
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} "$@"
|
|
@ -0,0 +1,145 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
|
||||
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -0,0 +1,40 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>couchbase-sdk-intro</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk-intro</name>
|
||||
<description>Intro to the Couchbase SDK</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
||||
<dependency>
|
||||
<groupId>com.couchbase.client</groupId>
|
||||
<artifactId>java-client</artifactId>
|
||||
<version>${couchbase.client.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.7</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.2.6</couchbase.client.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.couchbase.examples;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.couchbase.client.core.CouchbaseException;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.Cluster;
|
||||
import com.couchbase.client.java.CouchbaseCluster;
|
||||
import com.couchbase.client.java.ReplicaMode;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
import com.couchbase.client.java.env.CouchbaseEnvironment;
|
||||
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
||||
|
||||
public class CodeSnippets {
|
||||
|
||||
static Cluster loadClusterWithDefaultEnvironment() {
|
||||
return CouchbaseCluster.create("localhost");
|
||||
}
|
||||
|
||||
static Cluster loadClusterWithCustomEnvironment() {
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
|
||||
.connectTimeout(10000)
|
||||
.kvTimeout(3000)
|
||||
.build();
|
||||
return CouchbaseCluster.create(env, "localhost");
|
||||
}
|
||||
|
||||
static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) {
|
||||
return cluster.openBucket();
|
||||
}
|
||||
|
||||
static Bucket loadBaeldungBucket(Cluster cluster) {
|
||||
return cluster.openBucket("baeldung", "");
|
||||
}
|
||||
|
||||
static JsonDocument insertExample(Bucket bucket) {
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("name", "John Doe")
|
||||
.put("type", "Person")
|
||||
.put("email", "john.doe@mydomain.com")
|
||||
.put("homeTown", "Chicago")
|
||||
;
|
||||
String id = UUID.randomUUID().toString();
|
||||
JsonDocument document = JsonDocument.create(id, content);
|
||||
JsonDocument inserted = bucket.insert(document);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) {
|
||||
JsonDocument document = bucket.get(id);
|
||||
JsonObject content = document.content();
|
||||
content.put("homeTown", "Kansas City");
|
||||
JsonDocument upserted = bucket.upsert(document);
|
||||
return upserted;
|
||||
}
|
||||
|
||||
static JsonDocument replaceExample(Bucket bucket, String id) {
|
||||
JsonDocument document = bucket.get(id);
|
||||
JsonObject content = document.content();
|
||||
content.put("homeTown", "Milwaukee");
|
||||
JsonDocument replaced = bucket.replace(document);
|
||||
return replaced;
|
||||
}
|
||||
|
||||
static JsonDocument removeExample(Bucket bucket, String id) {
|
||||
JsonDocument removed = bucket.remove(id);
|
||||
return removed;
|
||||
}
|
||||
|
||||
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
||||
try{
|
||||
return bucket.get(id);
|
||||
}
|
||||
catch(CouchbaseException e) {
|
||||
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
||||
if(!list.isEmpty()) {
|
||||
return list.get(0);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) {
|
||||
long maxCasValue = -1;
|
||||
JsonDocument latest = null;
|
||||
for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
|
||||
if(replica.cas() > maxCasValue) {
|
||||
latest = replica;
|
||||
maxCasValue = replica.cas();
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue