commit
a55d19e6c7
@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<auto-service.version>1.0-rc2</auto-service.version>
|
<auto-service.version>1.0-rc2</auto-service.version>
|
||||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -13,6 +13,11 @@
|
|||||||
|
|
||||||
<artifactId>annotation-user</artifactId>
|
<artifactId>annotation-user</artifactId>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -24,7 +29,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
@ -37,7 +42,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.5.1</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
|
2
apache-cxf/README.md
Normal file
2
apache-cxf/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant Articles:
|
||||||
|
- [Introduction to Apache CXF Aegis Data Binding](http://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
20
apache-cxf/cxf-aegis/pom.xml
Normal file
20
apache-cxf/cxf-aegis/pom.xml
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
<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-aegis</artifactId>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>apache-cxf</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<properties>
|
||||||
|
<cxf.version>3.1.8</cxf.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.cxf</groupId>
|
||||||
|
<artifactId>cxf-rt-databinding-aegis</artifactId>
|
||||||
|
<version>${cxf.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.cxf.aegis;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class Course {
|
||||||
|
private int id;
|
||||||
|
private String name;
|
||||||
|
private String instructor;
|
||||||
|
private Date enrolmentDate;
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getInstructor() {
|
||||||
|
return instructor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInstructor(String instructor) {
|
||||||
|
this.instructor = instructor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getEnrolmentDate() {
|
||||||
|
return enrolmentDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEnrolmentDate(Date enrolmentDate) {
|
||||||
|
this.enrolmentDate = enrolmentDate;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.cxf.aegis;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public interface CourseRepo {
|
||||||
|
String getGreeting();
|
||||||
|
void setGreeting(String greeting);
|
||||||
|
Map<Integer, Course> getCourses();
|
||||||
|
void setCourses(Map<Integer, Course> courses);
|
||||||
|
void addCourse(Course course);
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.cxf.aegis;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class CourseRepoImpl implements CourseRepo {
|
||||||
|
private String greeting;
|
||||||
|
private Map<Integer, Course> courses = new HashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getGreeting() {
|
||||||
|
return greeting;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setGreeting(String greeting) {
|
||||||
|
this.greeting = greeting;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<Integer, Course> getCourses() {
|
||||||
|
return courses;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setCourses(Map<Integer, Course> courses) {
|
||||||
|
this.courses = courses;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addCourse(Course course) {
|
||||||
|
courses.put(course.getId(), course);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
<mappings>
|
||||||
|
<mapping>
|
||||||
|
<property name="instructor" ignore="true"/>
|
||||||
|
</mapping>
|
||||||
|
</mappings>
|
@ -0,0 +1,5 @@
|
|||||||
|
<mappings xmlns:ns="http://courserepo.baeldung.com">
|
||||||
|
<mapping name="ns:Baeldung">
|
||||||
|
<property name="greeting" style="attribute"/>
|
||||||
|
</mapping>
|
||||||
|
</mappings>
|
@ -0,0 +1,93 @@
|
|||||||
|
package com.baeldung.cxf.aegis;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import javax.xml.namespace.QName;
|
||||||
|
import javax.xml.stream.XMLInputFactory;
|
||||||
|
import javax.xml.stream.XMLOutputFactory;
|
||||||
|
import javax.xml.stream.XMLStreamReader;
|
||||||
|
import javax.xml.stream.XMLStreamWriter;
|
||||||
|
|
||||||
|
import org.apache.cxf.aegis.AegisContext;
|
||||||
|
import org.apache.cxf.aegis.AegisReader;
|
||||||
|
import org.apache.cxf.aegis.AegisWriter;
|
||||||
|
import org.apache.cxf.aegis.type.AegisType;
|
||||||
|
|
||||||
|
public class BaeldungTest {
|
||||||
|
private AegisContext context;
|
||||||
|
private String fileName = "baeldung.xml";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
|
||||||
|
initializeContext();
|
||||||
|
CourseRepo inputRepo = initCourseRepo();
|
||||||
|
marshalCourseRepo(inputRepo);
|
||||||
|
CourseRepo outputRepo = unmarshalCourseRepo();
|
||||||
|
Course restCourse = outputRepo.getCourses().get(1);
|
||||||
|
Course securityCourse = outputRepo.getCourses().get(2);
|
||||||
|
assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
|
||||||
|
assertEquals("REST with Spring", restCourse.getName());
|
||||||
|
assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
|
||||||
|
assertNull(restCourse.getInstructor());
|
||||||
|
assertEquals("Learn Spring Security", securityCourse.getName());
|
||||||
|
assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
|
||||||
|
assertNull(securityCourse.getInstructor());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initializeContext() {
|
||||||
|
context = new AegisContext();
|
||||||
|
Set<Type> rootClasses = new HashSet<Type>();
|
||||||
|
rootClasses.add(CourseRepo.class);
|
||||||
|
context.setRootClasses(rootClasses);
|
||||||
|
Map<Class<?>, String> beanImplementationMap = new HashMap<>();
|
||||||
|
beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
|
||||||
|
context.setBeanImplementationMap(beanImplementationMap);
|
||||||
|
context.setWriteXsiTypes(true);
|
||||||
|
context.initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private CourseRepoImpl initCourseRepo() {
|
||||||
|
Course restCourse = new Course();
|
||||||
|
restCourse.setId(1);
|
||||||
|
restCourse.setName("REST with Spring");
|
||||||
|
restCourse.setInstructor("Eugen");
|
||||||
|
restCourse.setEnrolmentDate(new Date(1234567890000L));
|
||||||
|
Course securityCourse = new Course();
|
||||||
|
securityCourse.setId(2);
|
||||||
|
securityCourse.setName("Learn Spring Security");
|
||||||
|
securityCourse.setInstructor("Eugen");
|
||||||
|
securityCourse.setEnrolmentDate(new Date(1456789000000L));
|
||||||
|
CourseRepoImpl courseRepo = new CourseRepoImpl();
|
||||||
|
courseRepo.setGreeting("Welcome to Beldung!");
|
||||||
|
courseRepo.addCourse(restCourse);
|
||||||
|
courseRepo.addCourse(securityCourse);
|
||||||
|
return courseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
|
||||||
|
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
|
||||||
|
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
|
||||||
|
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
|
||||||
|
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
|
||||||
|
xmlWriter.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private CourseRepo unmarshalCourseRepo() throws Exception {
|
||||||
|
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
|
||||||
|
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
|
||||||
|
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
|
||||||
|
xmlReader.close();
|
||||||
|
return courseRepo;
|
||||||
|
}
|
||||||
|
}
|
@ -4,15 +4,18 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>cxf-introduction</artifactId>
|
<artifactId>cxf-introduction</artifactId>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>apache-cxf</artifactId>
|
<artifactId>apache-cxf</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<cxf.version>3.1.6</cxf.version>
|
<cxf.version>3.1.8</cxf.version>
|
||||||
<surefire.version>2.19.1</surefire.version>
|
<surefire.version>2.19.1</surefire.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -24,7 +27,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>2.19.1</version>
|
<version>${surefire.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
@ -33,6 +36,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.cxf</groupId>
|
<groupId>org.apache.cxf</groupId>
|
||||||
|
2
apache-cxf/cxf-jaxrs-implementation/README.md
Normal file
2
apache-cxf/cxf-jaxrs-implementation/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
|
@ -4,17 +4,20 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>cxf-jaxrs-implementation</artifactId>
|
<artifactId>cxf-jaxrs-implementation</artifactId>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>apache-cxf</artifactId>
|
<artifactId>apache-cxf</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<cxf.version>3.1.7</cxf.version>
|
<cxf.version>3.1.8</cxf.version>
|
||||||
<httpclient.version>4.5.2</httpclient.version>
|
<httpclient.version>4.5.2</httpclient.version>
|
||||||
<surefire.version>2.19.1</surefire.version>
|
<surefire.version>2.19.1</surefire.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -26,7 +29,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>2.19.1</version>
|
<version>${surefire.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
@ -35,6 +38,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.cxf</groupId>
|
<groupId>org.apache.cxf</groupId>
|
||||||
|
@ -33,7 +33,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
<version>3.1.0</version>
|
<version>${javax.servlet-api.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -41,7 +41,7 @@
|
|||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-war-plugin</artifactId>
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
<version>2.6</version>
|
<version>${maven-war-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
</configuration>
|
</configuration>
|
||||||
@ -66,7 +66,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.cargo</groupId>
|
<groupId>org.codehaus.cargo</groupId>
|
||||||
<artifactId>cargo-maven2-plugin</artifactId>
|
<artifactId>cargo-maven2-plugin</artifactId>
|
||||||
<version>1.4.19</version>
|
<version>${cargo-maven2-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<container>
|
<container>
|
||||||
<containerId>tomcat8x</containerId>
|
<containerId>tomcat8x</containerId>
|
||||||
@ -121,9 +121,13 @@
|
|||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<cxf.version>3.1.6</cxf.version>
|
<cxf.version>3.1.8</cxf.version>
|
||||||
<spring.version>4.3.1.RELEASE</spring.version>
|
<spring.version>4.3.4.RELEASE</spring.version>
|
||||||
|
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
|
||||||
|
|
||||||
|
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||||
<surefire.version>2.19.1</surefire.version>
|
<surefire.version>2.19.1</surefire.version>
|
||||||
|
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -5,19 +5,29 @@
|
|||||||
<artifactId>apache-cxf</artifactId>
|
<artifactId>apache-cxf</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>cxf-introduction</module>
|
<module>cxf-introduction</module>
|
||||||
<module>cxf-spring</module>
|
<module>cxf-spring</module>
|
||||||
<module>cxf-jaxrs-implementation</module>
|
<module>cxf-jaxrs-implementation</module>
|
||||||
|
<module>cxf-aegis</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<defaultGoal>install</defaultGoal>
|
<defaultGoal>install</defaultGoal>
|
||||||
<pluginManagement>
|
<pluginManagement>
|
||||||
@ -25,7 +35,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.5.1</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
@ -34,7 +44,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
<version>1.5.0</version>
|
<version>${exec-maven-plugin.version}</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</pluginManagement>
|
</pluginManagement>
|
||||||
|
@ -67,7 +67,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.xmlgraphics</groupId>
|
<groupId>org.apache.xmlgraphics</groupId>
|
||||||
<artifactId>fop</artifactId>
|
<artifactId>fop</artifactId>
|
||||||
<version>1.1</version>
|
<version>${fop.version}</version>
|
||||||
<exclusions>
|
<exclusions>
|
||||||
<exclusion>
|
<exclusion>
|
||||||
<groupId>org.apache.avalon.framework</groupId>
|
<groupId>org.apache.avalon.framework</groupId>
|
||||||
@ -83,18 +83,18 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>avalon-framework</groupId>
|
<groupId>avalon-framework</groupId>
|
||||||
<artifactId>avalon-framework-api</artifactId>
|
<artifactId>avalon-framework-api</artifactId>
|
||||||
<version>4.2.0</version>
|
<version>${avalon-framework.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>avalon-framework</groupId>
|
<groupId>avalon-framework</groupId>
|
||||||
<artifactId>avalon-framework-impl</artifactId>
|
<artifactId>avalon-framework-impl</artifactId>
|
||||||
<version>4.2.0</version>
|
<version>${avalon-framework.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.dbdoclet</groupId>
|
<groupId>org.dbdoclet</groupId>
|
||||||
<artifactId>dbdoclet</artifactId>
|
<artifactId>dbdoclet</artifactId>
|
||||||
<version>8.0.2</version>
|
<version>${dbdoclet.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -108,7 +108,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sf.jtidy</groupId>
|
<groupId>net.sf.jtidy</groupId>
|
||||||
<artifactId>jtidy</artifactId>
|
<artifactId>jtidy</artifactId>
|
||||||
<version>r938</version>
|
<version>${jtidy.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -187,40 +187,22 @@
|
|||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- persistence -->
|
<fop.version>1.1</fop.version>
|
||||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
<avalon-framework.version>4.3</avalon-framework.version>
|
||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
<dbdoclet.version>8.0.2</dbdoclet.version>
|
||||||
|
<jtidy.version>r938</jtidy.version>
|
||||||
<!-- marshalling -->
|
|
||||||
<jackson.version>2.7.2</jackson.version>
|
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.9</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<logback.version>1.1.2</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- various -->
|
|
||||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
|
||||||
|
|
||||||
<!-- util -->
|
|
||||||
<guava.version>19.0</guava.version>
|
|
||||||
<commons-lang3.version>3.3.2</commons-lang3.version>
|
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
|
||||||
<httpcore.version>4.4</httpcore.version>
|
|
||||||
<httpclient.version>4.4</httpclient.version>
|
|
||||||
|
|
||||||
<rest-assured.version>2.9.0</rest-assured.version>
|
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
|
||||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
|
||||||
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
1
apache-poi/.gitignore
vendored
Normal file
1
apache-poi/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
*.docx
|
41
apache-poi/pom.xml
Normal file
41
apache-poi/pom.xml
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>apache-poi</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<poi.version>3.15</poi.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-ooxml</artifactId>
|
||||||
|
<version>${poi.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
@ -0,0 +1,95 @@
|
|||||||
|
package com.baeldung.poi.word;
|
||||||
|
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.poi.util.Units;
|
||||||
|
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
|
||||||
|
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
|
|
||||||
|
public class WordDocument {
|
||||||
|
public static String logo = "logo-leaf.png";
|
||||||
|
public static String paragraph1 = "poi-word-para1.txt";
|
||||||
|
public static String paragraph2 = "poi-word-para2.txt";
|
||||||
|
public static String paragraph3 = "poi-word-para3.txt";
|
||||||
|
public static String output = "rest-with-spring.docx";
|
||||||
|
|
||||||
|
public void handleSimpleDoc() throws Exception {
|
||||||
|
XWPFDocument document = new XWPFDocument();
|
||||||
|
|
||||||
|
XWPFParagraph title = document.createParagraph();
|
||||||
|
title.setAlignment(ParagraphAlignment.CENTER);
|
||||||
|
XWPFRun titleRun = title.createRun();
|
||||||
|
titleRun.setText("Build Your REST API with Spring");
|
||||||
|
titleRun.setColor("009933");
|
||||||
|
titleRun.setBold(true);
|
||||||
|
titleRun.setFontFamily("Courier");
|
||||||
|
titleRun.setFontSize(20);
|
||||||
|
|
||||||
|
XWPFParagraph subTitle = document.createParagraph();
|
||||||
|
subTitle.setAlignment(ParagraphAlignment.CENTER);
|
||||||
|
XWPFRun subTitleRun = subTitle.createRun();
|
||||||
|
subTitleRun.setText("from HTTP fundamentals to API Mastery");
|
||||||
|
subTitleRun.setColor("00CC44");
|
||||||
|
subTitleRun.setFontFamily("Courier");
|
||||||
|
subTitleRun.setFontSize(16);
|
||||||
|
subTitleRun.setTextPosition(20);
|
||||||
|
subTitleRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
|
||||||
|
|
||||||
|
XWPFParagraph image = document.createParagraph();
|
||||||
|
image.setAlignment(ParagraphAlignment.CENTER);
|
||||||
|
XWPFRun imageRun = image.createRun();
|
||||||
|
imageRun.setTextPosition(20);
|
||||||
|
Path imagePath = Paths.get(ClassLoader.getSystemResource(logo).toURI());
|
||||||
|
imageRun.addPicture(Files.newInputStream(imagePath), XWPFDocument.PICTURE_TYPE_PNG, imagePath.getFileName().toString(), Units.toEMU(50), Units.toEMU(50));
|
||||||
|
|
||||||
|
XWPFParagraph sectionTitle = document.createParagraph();
|
||||||
|
XWPFRun sectionTRun = sectionTitle.createRun();
|
||||||
|
sectionTRun.setText("What makes a good API?");
|
||||||
|
sectionTRun.setColor("00CC44");
|
||||||
|
sectionTRun.setBold(true);
|
||||||
|
sectionTRun.setFontFamily("Courier");
|
||||||
|
|
||||||
|
XWPFParagraph para1 = document.createParagraph();
|
||||||
|
para1.setAlignment(ParagraphAlignment.BOTH);
|
||||||
|
String string1 = convertTextFileToString(paragraph1);
|
||||||
|
XWPFRun para1Run = para1.createRun();
|
||||||
|
para1Run.setText(string1);
|
||||||
|
|
||||||
|
XWPFParagraph para2 = document.createParagraph();
|
||||||
|
para2.setAlignment(ParagraphAlignment.RIGHT);
|
||||||
|
String string2 = convertTextFileToString(paragraph2);
|
||||||
|
XWPFRun para2Run = para2.createRun();
|
||||||
|
para2Run.setText(string2);
|
||||||
|
para2Run.setItalic(true);
|
||||||
|
|
||||||
|
XWPFParagraph para3 = document.createParagraph();
|
||||||
|
para3.setAlignment(ParagraphAlignment.LEFT);
|
||||||
|
String string3 = convertTextFileToString(paragraph3);
|
||||||
|
XWPFRun para3Run = para3.createRun();
|
||||||
|
para3Run.setText(string3);
|
||||||
|
|
||||||
|
FileOutputStream out = new FileOutputStream(output);
|
||||||
|
document.write(out);
|
||||||
|
out.close();
|
||||||
|
document.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String convertTextFileToString(String fileName) {
|
||||||
|
try (Stream<String> stream = Files.lines(Paths.get(ClassLoader.getSystemResource(fileName).toURI()))) {
|
||||||
|
return stream.collect(Collectors.joining(" "));
|
||||||
|
} catch (IOException | URISyntaxException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
BIN
apache-poi/src/main/resources/logo-leaf.png
Normal file
BIN
apache-poi/src/main/resources/logo-leaf.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 782 B |
1
apache-poi/src/main/resources/poi-word-para1.txt
Normal file
1
apache-poi/src/main/resources/poi-word-para1.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
I published the first REST with Spring tutorials over four years ago, and after 300,000 readers and over a thousand personal questions over email, I am finally realizing that there is a huge education gap in the ecosystem.
|
2
apache-poi/src/main/resources/poi-word-para2.txt
Normal file
2
apache-poi/src/main/resources/poi-word-para2.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
I had to learn what makes a good API is the hard way, and I couldn’t find anything out there to help me speed things up.
|
||||||
|
It took me 3 years, more than 10 production grade APIs built from scratch and a decent number of mistakes to get to a mature understanding of how an API should really be done well.
|
3
apache-poi/src/main/resources/poi-word-para3.txt
Normal file
3
apache-poi/src/main/resources/poi-word-para3.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
Sure, there were tutorials and random code samples out there, but nothing coherent.
|
||||||
|
Nothing start to finish to act as a guide through the challenges of building a mature API with Spring.
|
||||||
|
The educational gap between beginner and the API professional remains vast.
|
47
apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
Normal file
47
apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.poi.word;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||||
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class WordTest {
|
||||||
|
static WordDocument wordDocument;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void generateMSWordFile() throws Exception {
|
||||||
|
WordTest.wordDocument = new WordDocument();
|
||||||
|
wordDocument.handleSimpleDoc();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenParsingOutputDocument_thenCorrect() throws Exception {
|
||||||
|
Path msWordPath = Paths.get(WordDocument.output);
|
||||||
|
XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
|
||||||
|
List<XWPFParagraph> paragraphs = document.getParagraphs();
|
||||||
|
document.close();
|
||||||
|
|
||||||
|
XWPFParagraph title = paragraphs.get(0);
|
||||||
|
XWPFRun titleRun = title.getRuns().get(0);
|
||||||
|
assertEquals("Build Your REST API with Spring", title.getText());
|
||||||
|
assertEquals("009933", titleRun.getColor());
|
||||||
|
assertTrue(titleRun.isBold());
|
||||||
|
assertEquals("Courier", titleRun.getFontFamily());
|
||||||
|
assertEquals(20, titleRun.getFontSize());
|
||||||
|
|
||||||
|
assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
|
||||||
|
assertEquals("What makes a good API?", paragraphs.get(3).getText());
|
||||||
|
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
|
||||||
|
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
|
||||||
|
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
|
||||||
|
}
|
||||||
|
}
|
@ -104,7 +104,8 @@
|
|||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<!-- <plugin>
|
<!--
|
||||||
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>2.10</version>
|
<version>2.10</version>
|
||||||
@ -113,18 +114,18 @@
|
|||||||
<useSystemClassLoader>true</useSystemClassLoader>
|
<useSystemClassLoader>true</useSystemClassLoader>
|
||||||
<forkMode>always</forkMode>
|
<forkMode>always</forkMode>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin> -->
|
</plugin>
|
||||||
|
-->
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<source.version>1.8</source.version>
|
<source.version>1.8</source.version>
|
||||||
<aspectj.version>1.6.11</aspectj.version>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<aspectj.version>1.8.9</aspectj.version>
|
<aspectj.version>1.8.9</aspectj.version>
|
||||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<logback.version>1.1.7</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -4,10 +4,10 @@ public class Account {
|
|||||||
int balance = 20;
|
int balance = 20;
|
||||||
|
|
||||||
public boolean withdraw(int amount) {
|
public boolean withdraw(int amount) {
|
||||||
if (balance - amount > 0) {
|
if (balance < amount) {
|
||||||
balance = balance - amount;
|
|
||||||
return true;
|
|
||||||
} else
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
balance = balance - amount;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,12 +16,11 @@ public aspect AccountAspect {
|
|||||||
}
|
}
|
||||||
|
|
||||||
boolean around(int amount, Account account) : callWithDraw(amount, account) {
|
boolean around(int amount, Account account) : callWithDraw(amount, account) {
|
||||||
if (account.balance - amount >= MIN_BALANCE)
|
if (account.balance < amount) {
|
||||||
return proceed(amount, account);
|
|
||||||
else {
|
|
||||||
logger.info("Withdrawal Rejected!");
|
logger.info("Withdrawal Rejected!");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
return proceed(amount, account);
|
||||||
}
|
}
|
||||||
|
|
||||||
after(int amount, Account balance) : callWithDraw(amount, balance) {
|
after(int amount, Account balance) : callWithDraw(amount, balance) {
|
||||||
|
@ -23,13 +23,13 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>3.5.1</version>
|
<version>${assertj-core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
@ -40,7 +40,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.3</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
@ -51,6 +51,11 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>19.0</guava.version>
|
||||||
|
<assertj-guava.version>3.1.0</assertj-guava.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<assertj-core.version>3.6.1</assertj-core.version>
|
||||||
|
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -2,15 +2,16 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>autovalue-tutorial</artifactId>
|
<artifactId>autovalue</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
<name>AutoValue</name>
|
<name>autovalue</name>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.3</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>7</source>
|
<source>7</source>
|
||||||
<target>7</target>
|
<target>7</target>
|
||||||
@ -19,19 +20,26 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.auto.value</groupId>
|
<groupId>com.google.auto.value</groupId>
|
||||||
<artifactId>auto-value</artifactId>
|
<artifactId>auto-value</artifactId>
|
||||||
<version>1.2</version>
|
<version>${auto-value.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.3</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<auto-value.version>1.3</auto-value.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -4,7 +4,7 @@ import static org.junit.Assert.*;
|
|||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class MoneyTest {
|
public class MoneyUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
MutableMoney m1 = new MutableMoney(10000, "USD");
|
11
cdi/pom.xml
11
cdi/pom.xml
@ -22,18 +22,18 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.aspectj</groupId>
|
<groupId>org.aspectj</groupId>
|
||||||
<artifactId>aspectjweaver</artifactId>
|
<artifactId>aspectjweaver</artifactId>
|
||||||
<version>1.8.9</version>
|
<version>${aspectjweaver.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.weld.se</groupId>
|
<groupId>org.jboss.weld.se</groupId>
|
||||||
<artifactId>weld-se-core</artifactId>
|
<artifactId>weld-se-core</artifactId>
|
||||||
<version>2.3.5.Final</version>
|
<version>${weld-se-core.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -97,7 +97,10 @@
|
|||||||
</profile>
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
<properties>
|
<properties>
|
||||||
<spring.version>4.3.1.RELEASE</spring.version>
|
<spring.version>4.3.4.RELEASE</spring.version>
|
||||||
|
<aspectjweaver.version>1.8.9</aspectjweaver.version>
|
||||||
|
<weld-se-core.version>2.4.1.Final</weld-se-core.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -3,3 +3,6 @@
|
|||||||
## Core Java 9 Examples
|
## Core Java 9 Examples
|
||||||
|
|
||||||
[Java 9 New Features](http://www.baeldung.com/new-java-9)
|
[Java 9 New Features](http://www.baeldung.com/new-java-9)
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
|
||||||
|
@ -76,9 +76,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<logback.version>1.0.13</logback.version>
|
|
||||||
|
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||||
|
2
core-java/.gitignore
vendored
2
core-java/.gitignore
vendored
@ -14,3 +14,5 @@
|
|||||||
|
|
||||||
# Files generated by integration tests
|
# Files generated by integration tests
|
||||||
*.txt
|
*.txt
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
@ -38,3 +38,11 @@
|
|||||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||||
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
|
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
|
||||||
|
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
|
||||||
|
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||||
|
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||||
|
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||||
|
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||||
|
- [Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||||
|
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
|
||||||
|
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sourceforge.collections</groupId>
|
<groupId>net.sourceforge.collections</groupId>
|
||||||
<artifactId>collections-generic</artifactId>
|
<artifactId>collections-generic</artifactId>
|
||||||
<version>4.01</version>
|
<version>${collections-generic.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
@ -25,13 +25,13 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>4.0</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>2.4</version>
|
<version>${commons-io.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -43,13 +43,25 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-math3</artifactId>
|
<artifactId>commons-math3</artifactId>
|
||||||
<version>3.3</version>
|
<version>${commons-math3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.bouncycastle</groupId>
|
<groupId>org.bouncycastle</groupId>
|
||||||
<artifactId>bcprov-jdk15on</artifactId>
|
<artifactId>bcprov-jdk15on</artifactId>
|
||||||
<version>1.55</version>
|
<version>${bouncycastle.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.unix4j</groupId>
|
||||||
|
<artifactId>unix4j-command</artifactId>
|
||||||
|
<version>${unix4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.grep4j</groupId>
|
||||||
|
<artifactId>grep4j</artifactId>
|
||||||
|
<version>${grep4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
@ -85,9 +97,22 @@
|
|||||||
<artifactId>log4j-over-slf4j</artifactId>
|
<artifactId>log4j-over-slf4j</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest-all</artifactId>
|
||||||
|
<version>1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
@ -122,8 +147,6 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
@ -134,7 +157,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-codec</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
<artifactId>commons-codec</artifactId>
|
<artifactId>commons-codec</artifactId>
|
||||||
<version>1.10</version>
|
<version>${commons-codec.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -170,6 +193,7 @@
|
|||||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
@ -238,8 +262,7 @@
|
|||||||
<configuration>
|
<configuration>
|
||||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||||
<transformers>
|
<transformers>
|
||||||
<transformer
|
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
</transformers>
|
</transformers>
|
||||||
@ -321,42 +344,36 @@
|
|||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- persistence -->
|
|
||||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
|
||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.7.8</jackson.version>
|
<jackson.version>2.8.5</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<logback.version>1.1.3</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- various -->
|
|
||||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>19.0</guava.version>
|
||||||
<commons-lang3.version>3.4</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
|
<commons-io.version>2.5</commons-io.version>
|
||||||
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
|
<unix4j.version>0.4</unix4j.version>
|
||||||
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
<testng.version>6.8</testng.version>
|
<testng.version>6.10</testng.version>
|
||||||
<assertj.version>3.5.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
|
||||||
<httpcore.version>4.4.1</httpcore.version>
|
|
||||||
<httpclient.version>4.5</httpclient.version>
|
|
||||||
|
|
||||||
<rest-assured.version>2.9.0</rest-assured.version>
|
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
|
||||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
|
||||||
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
2
core-java/src/main/java/com/baeldung/README.md
Normal file
2
core-java/src/main/java/com/baeldung/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||||
|
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||||
|
|
||||||
|
public class RunAlgorithm {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner in = new Scanner(System.in);
|
||||||
|
System.out.println("Run algorithm:");
|
||||||
|
System.out.println("1 - Simulated Annealing");
|
||||||
|
System.out.println("2 - Slope One");
|
||||||
|
int decision = in.nextInt();
|
||||||
|
switch (decision) {
|
||||||
|
case 1:
|
||||||
|
System.out.println(
|
||||||
|
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
SlopeOne.slopeOne(3);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
System.out.println("Unknown option");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
in.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.algorithms.annealing;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class City {
|
||||||
|
|
||||||
|
private int x;
|
||||||
|
private int y;
|
||||||
|
|
||||||
|
public City() {
|
||||||
|
this.x = (int) (Math.random() * 500);
|
||||||
|
this.y = (int) (Math.random() * 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
public double distanceToCity(City city) {
|
||||||
|
int x = Math.abs(getX() - city.getX());
|
||||||
|
int y = Math.abs(getY() - city.getY());
|
||||||
|
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.algorithms.annealing;
|
||||||
|
|
||||||
|
public class SimulatedAnnealing {
|
||||||
|
|
||||||
|
private static Travel travel = new Travel(10);
|
||||||
|
|
||||||
|
public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) {
|
||||||
|
System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate);
|
||||||
|
double t = startingTemperature;
|
||||||
|
travel.generateInitialTravel();
|
||||||
|
double bestDistance = travel.getDistance();
|
||||||
|
System.out.println("Initial distance of travel: " + bestDistance);
|
||||||
|
Travel bestSolution = travel;
|
||||||
|
Travel currentSolution = bestSolution;
|
||||||
|
|
||||||
|
for (int i = 0; i < numberOfIterations; i++) {
|
||||||
|
if (t > 0.1) {
|
||||||
|
currentSolution.swapCities();
|
||||||
|
double currentDistance = currentSolution.getDistance();
|
||||||
|
if (currentDistance < bestDistance) {
|
||||||
|
bestDistance = currentDistance;
|
||||||
|
} else if (Math.exp((bestDistance - currentDistance) / t) < Math.random()) {
|
||||||
|
currentSolution.revertSwap();
|
||||||
|
}
|
||||||
|
t *= coolingRate;
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (i % 100 == 0) {
|
||||||
|
System.out.println("Iteration #" + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestDistance;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package com.baeldung.algorithms.annealing;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class Travel {
|
||||||
|
|
||||||
|
private ArrayList<City> travel = new ArrayList<>();
|
||||||
|
private ArrayList<City> previousTravel = new ArrayList<>();
|
||||||
|
|
||||||
|
public Travel(int numberOfCities) {
|
||||||
|
for (int i = 0; i < numberOfCities; i++) {
|
||||||
|
travel.add(new City());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void generateInitialTravel() {
|
||||||
|
if (travel.isEmpty())
|
||||||
|
new Travel(10);
|
||||||
|
Collections.shuffle(travel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void swapCities() {
|
||||||
|
int a = generateRandomIndex();
|
||||||
|
int b = generateRandomIndex();
|
||||||
|
previousTravel = travel;
|
||||||
|
City x = travel.get(a);
|
||||||
|
City y = travel.get(b);
|
||||||
|
travel.set(a, y);
|
||||||
|
travel.set(b, x);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void revertSwap() {
|
||||||
|
travel = previousTravel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int generateRandomIndex() {
|
||||||
|
return (int) (Math.random() * travel.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
public City getCity(int index) {
|
||||||
|
return travel.get(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getDistance() {
|
||||||
|
int distance = 0;
|
||||||
|
for (int index = 0; index < travel.size(); index++) {
|
||||||
|
City starting = getCity(index);
|
||||||
|
City destination;
|
||||||
|
if (index + 1 < travel.size()) {
|
||||||
|
destination = getCity(index + 1);
|
||||||
|
} else {
|
||||||
|
destination = getCity(0);
|
||||||
|
}
|
||||||
|
distance += starting.distanceToCity(destination);
|
||||||
|
}
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.algorithms.slope_one;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class InputData {
|
||||||
|
|
||||||
|
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
||||||
|
new Item("Snacks"));
|
||||||
|
|
||||||
|
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||||
|
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||||
|
HashMap<Item, Double> newUser;
|
||||||
|
Set<Item> newRecommendationSet;
|
||||||
|
for (int i = 0; i < numberOfUsers; i++) {
|
||||||
|
newUser = new HashMap<Item, Double>();
|
||||||
|
newRecommendationSet = new HashSet<>();
|
||||||
|
for (int j = 0; j < 3; j++) {
|
||||||
|
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||||
|
}
|
||||||
|
for (Item item : newRecommendationSet) {
|
||||||
|
newUser.put(item, Math.random());
|
||||||
|
}
|
||||||
|
data.put(new User("User " + i), newUser);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.algorithms.slope_one;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class Item {
|
||||||
|
|
||||||
|
private String itemName;
|
||||||
|
}
|
@ -0,0 +1,124 @@
|
|||||||
|
package com.baeldung.algorithms.slope_one;
|
||||||
|
|
||||||
|
import java.text.DecimalFormat;
|
||||||
|
import java.text.NumberFormat;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Slope One algorithm implementation
|
||||||
|
*/
|
||||||
|
public class SlopeOne {
|
||||||
|
|
||||||
|
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||||
|
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||||
|
private static Map<User, HashMap<Item, Double>> inputData;
|
||||||
|
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||||
|
|
||||||
|
public static void slopeOne(int numberOfUsers) {
|
||||||
|
inputData = InputData.initializeData(numberOfUsers);
|
||||||
|
System.out.println("Slope One - Before the Prediction\n");
|
||||||
|
buildDifferencesMatrix(inputData);
|
||||||
|
System.out.println("\nSlope One - With Predictions\n");
|
||||||
|
predict(inputData);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Based on the available data, calculate the relationships between the
|
||||||
|
* items and number of occurences
|
||||||
|
*
|
||||||
|
* @param data
|
||||||
|
* existing user data and their items' ratings
|
||||||
|
*/
|
||||||
|
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||||
|
for (HashMap<Item, Double> user : data.values()) {
|
||||||
|
for (Entry<Item, Double> e : user.entrySet()) {
|
||||||
|
if (!diff.containsKey(e.getKey())) {
|
||||||
|
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||||
|
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||||
|
}
|
||||||
|
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||||
|
int oldCount = 0;
|
||||||
|
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
|
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||||
|
}
|
||||||
|
double oldDiff = 0.0;
|
||||||
|
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
|
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||||
|
}
|
||||||
|
double observedDiff = e.getValue() - e2.getValue();
|
||||||
|
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||||
|
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Item j : diff.keySet()) {
|
||||||
|
for (Item i : diff.get(j).keySet()) {
|
||||||
|
double oldValue = diff.get(j).get(i).doubleValue();
|
||||||
|
int count = freq.get(j).get(i).intValue();
|
||||||
|
diff.get(j).put(i, oldValue / count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printData(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Based on existing data predict all missing ratings. If prediction is not
|
||||||
|
* possible, the value will be equal to -1
|
||||||
|
*
|
||||||
|
* @param data
|
||||||
|
* existing user data and their items' ratings
|
||||||
|
*/
|
||||||
|
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||||
|
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||||
|
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||||
|
for (Item j : diff.keySet()) {
|
||||||
|
uFreq.put(j, 0);
|
||||||
|
uPred.put(j, 0.0);
|
||||||
|
}
|
||||||
|
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||||
|
for (Item j : e.getValue().keySet()) {
|
||||||
|
for (Item k : diff.keySet()) {
|
||||||
|
try {
|
||||||
|
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||||
|
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||||
|
uPred.put(k, uPred.get(k) + finalValue);
|
||||||
|
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||||
|
} catch (NullPointerException e1) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||||
|
for (Item j : uPred.keySet()) {
|
||||||
|
if (uFreq.get(j) > 0) {
|
||||||
|
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Item j : InputData.items) {
|
||||||
|
if (e.getValue().containsKey(j)) {
|
||||||
|
clean.put(j, e.getValue().get(j));
|
||||||
|
} else {
|
||||||
|
clean.put(j, -1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outputData.put(e.getKey(), clean);
|
||||||
|
}
|
||||||
|
printData(outputData);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||||
|
for (User user : data.keySet()) {
|
||||||
|
System.out.println(user.getUsername() + ":");
|
||||||
|
print(data.get(user));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void print(HashMap<Item, Double> hashMap) {
|
||||||
|
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||||
|
for (Item j : hashMap.keySet()) {
|
||||||
|
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.algorithms.slope_one;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.dirmonitoring;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
|
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||||
|
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||||
|
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||||
|
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||||
|
|
||||||
|
public class DirectoryMonitoringExample {
|
||||||
|
|
||||||
|
public static final int POLL_INTERVAL = 500;
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||||
|
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
|
||||||
|
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
|
||||||
|
@Override
|
||||||
|
public void onFileCreate(File file) {
|
||||||
|
System.out.println("File: " + file.getName() + " created");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onFileDelete(File file) {
|
||||||
|
System.out.println("File: " + file.getName() + " deleted");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onFileChange(File file) {
|
||||||
|
System.out.println("File: " + file.getName() + " changed");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
observer.addListener(listener);
|
||||||
|
monitor.addObserver(observer);
|
||||||
|
monitor.start();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
12
core-java/src/main/java/com/baeldung/generics/Building.java
Normal file
12
core-java/src/main/java/com/baeldung/generics/Building.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.generics;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class Building {
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
|
||||||
|
|
||||||
|
public void paint() {
|
||||||
|
LOGGER.info("Painting Building");
|
||||||
|
}
|
||||||
|
}
|
31
core-java/src/main/java/com/baeldung/generics/Generics.java
Normal file
31
core-java/src/main/java/com/baeldung/generics/Generics.java
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.generics;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class Generics {
|
||||||
|
|
||||||
|
// definition of a generic method
|
||||||
|
public static <T> List<T> fromArrayToList(T[] a) {
|
||||||
|
return Arrays.stream(a).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
// definition of a generic method
|
||||||
|
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
|
||||||
|
return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
// example of a generic method that has Number as an upper bound for T
|
||||||
|
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
|
||||||
|
return Arrays.stream(a).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
// example of a generic method with a wild card, this method can be used
|
||||||
|
// with a list of any subtype of Building
|
||||||
|
public static void paintAllBuildings(List<? extends Building> buildings) {
|
||||||
|
buildings.forEach(Building::paint);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
12
core-java/src/main/java/com/baeldung/generics/House.java
Normal file
12
core-java/src/main/java/com/baeldung/generics/House.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.generics;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class House extends Building {
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
|
||||||
|
|
||||||
|
public void paint() {
|
||||||
|
LOGGER.info("Painting House");
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.hashing;
|
package com.baeldung.hashing;
|
||||||
|
|
||||||
|
|
||||||
import com.google.common.hash.Hashing;
|
import com.google.common.hash.Hashing;
|
||||||
import org.apache.commons.codec.digest.DigestUtils;
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
import org.bouncycastle.util.encoders.Hex;
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
@ -11,17 +10,14 @@ import java.security.NoSuchAlgorithmException;
|
|||||||
|
|
||||||
public class SHA256Hashing {
|
public class SHA256Hashing {
|
||||||
|
|
||||||
public static String HashWithJavaMessageDigest(final String originalString)
|
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||||
throws NoSuchAlgorithmException {
|
|
||||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
final byte[] encodedhash = digest.digest(
|
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||||
originalString.getBytes(StandardCharsets.UTF_8));
|
|
||||||
return bytesToHex(encodedhash);
|
return bytesToHex(encodedhash);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String HashWithGuava(final String originalString) {
|
public static String HashWithGuava(final String originalString) {
|
||||||
final String sha256hex = Hashing.sha256().hashString(
|
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
|
||||||
originalString, StandardCharsets.UTF_8).toString();
|
|
||||||
return sha256hex;
|
return sha256hex;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -30,11 +26,9 @@ public class SHA256Hashing {
|
|||||||
return sha256hex;
|
return sha256hex;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String HashWithBouncyCastle(final String originalString)
|
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
|
||||||
throws NoSuchAlgorithmException {
|
|
||||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
final byte[] hash = digest.digest(
|
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||||
originalString.getBytes(StandardCharsets.UTF_8));
|
|
||||||
final String sha256hex = new String(Hex.encode(hash));
|
final String sha256hex = new String(Hex.encode(hash));
|
||||||
return sha256hex;
|
return sha256hex;
|
||||||
}
|
}
|
||||||
@ -43,7 +37,8 @@ public class SHA256Hashing {
|
|||||||
StringBuffer hexString = new StringBuffer();
|
StringBuffer hexString = new StringBuffer();
|
||||||
for (int i = 0; i < hash.length; i++) {
|
for (int i = 0; i < hash.length; i++) {
|
||||||
String hex = Integer.toHexString(0xff & hash[i]);
|
String hex = Integer.toHexString(0xff & hash[i]);
|
||||||
if(hex.length() == 1) hexString.append('0');
|
if (hex.length() == 1)
|
||||||
|
hexString.append('0');
|
||||||
hexString.append(hex);
|
hexString.append(hex);
|
||||||
}
|
}
|
||||||
return hexString.toString();
|
return hexString.toString();
|
||||||
|
59
core-java/src/main/java/com/baeldung/java/map/MyKey.java
Normal file
59
core-java/src/main/java/com/baeldung/java/map/MyKey.java
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.java.map;
|
||||||
|
|
||||||
|
public class MyKey {
|
||||||
|
private String name;
|
||||||
|
private int id;
|
||||||
|
|
||||||
|
public MyKey(int id, String name) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
System.out.println("Calling hashCode()");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "MyKey [name=" + name + ", id=" + id + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
System.out.println("Calling equals() for key: " + obj);
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
MyKey other = (MyKey) obj;
|
||||||
|
if (id != other.id)
|
||||||
|
return false;
|
||||||
|
if (name == null) {
|
||||||
|
if (other.name != null)
|
||||||
|
return false;
|
||||||
|
} else if (!name.equals(other.name))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.java.map;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
private static final int MAX_ENTRIES = 5;
|
||||||
|
|
||||||
|
|
||||||
|
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||||
|
super(initialCapacity, loadFactor, accessOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||||
|
return size() > MAX_ENTRIES;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||||
|
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
|
||||||
|
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
|
||||||
|
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)
|
@ -0,0 +1,2 @@
|
|||||||
|
###Relevant Articles:
|
||||||
|
- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.java.nio2.visitor;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
|
||||||
|
import static java.nio.file.FileVisitResult.CONTINUE;
|
||||||
|
import static java.nio.file.FileVisitResult.TERMINATE;
|
||||||
|
|
||||||
|
public class FileSearchExample implements FileVisitor<Path> {
|
||||||
|
private final String fileName;
|
||||||
|
private final Path startDir;
|
||||||
|
|
||||||
|
public FileSearchExample(String fileName, Path startingDir) {
|
||||||
|
this.fileName = fileName;
|
||||||
|
startDir = startingDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
if (this.fileName.equals(fileName)) {
|
||||||
|
System.out.println("File found: " + file.toString());
|
||||||
|
return TERMINATE;
|
||||||
|
}
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
|
||||||
|
System.out.println("Failed to access file: " + file.toString());
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||||
|
boolean finishedSearch = Files.isSameFile(dir, startDir);
|
||||||
|
if (finishedSearch) {
|
||||||
|
System.out.println("File:" + fileName + " not found");
|
||||||
|
return TERMINATE;
|
||||||
|
}
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
Path startingDir = Paths.get("C:/Users/new/Desktop");
|
||||||
|
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
|
||||||
|
Files.walkFileTree(startingDir, crawler);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.java.nio2.visitor;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.FileVisitor;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
|
||||||
|
public class FileVisitorImpl implements FileVisitor<Path> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFileFailed(Path file, IOException exc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.java.nio2.watcher;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardWatchEventKinds;
|
||||||
|
import java.nio.file.WatchEvent;
|
||||||
|
import java.nio.file.WatchKey;
|
||||||
|
import java.nio.file.WatchService;
|
||||||
|
|
||||||
|
public class DirectoryWatcherExample {
|
||||||
|
public static void main(String[] args) throws IOException, InterruptedException {
|
||||||
|
WatchService watchService = FileSystems.getDefault().newWatchService();
|
||||||
|
Path path = Paths.get(System.getProperty("user.home"));
|
||||||
|
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
|
||||||
|
WatchKey key;
|
||||||
|
while ((key = watchService.take()) != null) {
|
||||||
|
for (WatchEvent<?> event : key.pollEvents()) {
|
||||||
|
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
|
||||||
|
}
|
||||||
|
key.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
13
core-java/src/main/java/com/baeldung/optional/Modem.java
Normal file
13
core-java/src/main/java/com/baeldung/optional/Modem.java
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.optional;
|
||||||
|
|
||||||
|
public class Modem {
|
||||||
|
private Double price;
|
||||||
|
|
||||||
|
public Modem(Double price) {
|
||||||
|
this.price = price;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getPrice() {
|
||||||
|
return price;
|
||||||
|
}
|
||||||
|
}
|
39
core-java/src/main/java/com/baeldung/optional/Person.java
Normal file
39
core-java/src/main/java/com/baeldung/optional/Person.java
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package com.baeldung.optional;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
private String name;
|
||||||
|
private int age;
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
public Person(String name, int age) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<String> getName() {
|
||||||
|
return Optional.ofNullable(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Integer> getAge() {
|
||||||
|
return Optional.ofNullable(age);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<String> getPassword() {
|
||||||
|
return Optional.ofNullable(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
48
core-java/src/main/java/com/baeldung/scripting/Nashorn.java
Normal file
48
core-java/src/main/java/com/baeldung/scripting/Nashorn.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.scripting;
|
||||||
|
|
||||||
|
import javax.script.Bindings;
|
||||||
|
import javax.script.Invocable;
|
||||||
|
import javax.script.ScriptEngine;
|
||||||
|
import javax.script.ScriptEngineManager;
|
||||||
|
import javax.script.ScriptException;
|
||||||
|
|
||||||
|
public class Nashorn {
|
||||||
|
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
|
||||||
|
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||||
|
|
||||||
|
Object result = engine.eval(
|
||||||
|
"var greeting='hello world';" +
|
||||||
|
"print(greeting);" +
|
||||||
|
"greeting");
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
|
||||||
|
Bindings bindings = engine.createBindings();
|
||||||
|
bindings.put("count", 3);
|
||||||
|
bindings.put("name", "baeldung");
|
||||||
|
|
||||||
|
String script = "var greeting='Hello ';" +
|
||||||
|
"for(var i=count;i>0;i--) { " +
|
||||||
|
"greeting+=name + ' '" +
|
||||||
|
"}" +
|
||||||
|
"greeting";
|
||||||
|
|
||||||
|
Object bindingsResult = engine.eval(script, bindings);
|
||||||
|
System.out.println(bindingsResult);
|
||||||
|
|
||||||
|
engine.eval("function composeGreeting(name) {" +
|
||||||
|
"return 'Hello ' + name" +
|
||||||
|
"}");
|
||||||
|
Invocable invocable = (Invocable) engine;
|
||||||
|
|
||||||
|
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
|
||||||
|
System.out.println(funcResult);
|
||||||
|
|
||||||
|
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" +
|
||||||
|
"var map = new HashMap();" +
|
||||||
|
"map.put('hello', 'world');" +
|
||||||
|
"map");
|
||||||
|
|
||||||
|
System.out.println(map);
|
||||||
|
}
|
||||||
|
}
|
@ -16,10 +16,10 @@ public class ExitingExecutorServiceExample {
|
|||||||
|
|
||||||
public static void main(String... args) {
|
public static void main(String... args) {
|
||||||
|
|
||||||
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||||
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
final ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
executorService.submit(() -> {
|
executorService.submit((Runnable) () -> {
|
||||||
while (true) {
|
while (true) {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||||
|
|
||||||
|
public class SimulatedAnnealingTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSimulateAnnealing() {
|
||||||
|
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -14,11 +14,13 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static java.util.stream.Collectors.joining;
|
import static java.util.stream.Collectors.joining;
|
||||||
|
import static org.hamcrest.CoreMatchers.*;
|
||||||
|
|
||||||
public class EncoderDecoderUnitTest {
|
public class EncoderDecoderUnitTest {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
||||||
private static final String testUrl = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253#dummy+Fragment";
|
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||||
|
private static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||||
|
|
||||||
private String encodeValue(String value) {
|
private String encodeValue(String value) {
|
||||||
String encoded = null;
|
String encoded = null;
|
||||||
@ -42,13 +44,11 @@ public class EncoderDecoderUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
||||||
URI uri = new URI(testUrl);
|
URL url = new URL(testUrl);
|
||||||
|
|
||||||
Assert.assertThat(uri.getScheme(), CoreMatchers.is("http"));
|
Assert.assertThat(url.getProtocol(), is("http"));
|
||||||
Assert.assertThat(uri.getHost(), CoreMatchers.is("www.baeldung.com"));
|
Assert.assertThat(url.getHost(), is("www.baeldung.com"));
|
||||||
Assert.assertThat(uri.getRawPath(), CoreMatchers.is("/path+1"));
|
Assert.assertThat(url.getQuery(), is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
||||||
Assert.assertThat(uri.getRawQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
|
||||||
Assert.assertThat(uri.getRawFragment(), CoreMatchers.is("dummy+Fragment"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -58,35 +58,27 @@ public class EncoderDecoderUnitTest {
|
|||||||
requestParams.put("key2", "value@!$2");
|
requestParams.put("key2", "value@!$2");
|
||||||
requestParams.put("key3", "value%3");
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
String path = "path+1";
|
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||||
String fragment = "dummy Fragment";
|
|
||||||
|
|
||||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + getPath(path) + "?", "#" + encodeValue(fragment)));
|
Assert.assertThat(testUrl, is(encodedURL));
|
||||||
|
|
||||||
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
||||||
URI uri = new URI(testUrl);
|
URL url = new URL(testUrl);
|
||||||
|
|
||||||
String scheme = uri.getScheme();
|
String query = url.getQuery();
|
||||||
String host = uri.getHost();
|
|
||||||
String query = uri.getRawQuery();
|
|
||||||
String path = uri.getRawPath();
|
|
||||||
String fragment = uri.getRawFragment();
|
|
||||||
|
|
||||||
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
||||||
String decodedPath = Arrays.stream(path.split("/")).map(param -> getPath(param)).collect(joining("/"));
|
|
||||||
|
|
||||||
Assert.assertEquals("http://www.baeldung.com/path+1?key1=value 1&key2=value@!$2&key3=value%3#dummy Fragment", scheme + "://" + host + decodedPath + "?" + decodedQuery + "#" + decode(fragment));
|
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getPath(String path) {
|
private String encodePath(String path) {
|
||||||
try {
|
try {
|
||||||
path = new URI(null, null, path, null).getPath();
|
path = new URI(null, null, path, null).getPath();
|
||||||
} catch (URISyntaxException e) {
|
} catch (URISyntaxException e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||||
}
|
}
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
@ -98,4 +90,19 @@ public class EncoderDecoderUnitTest {
|
|||||||
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
|
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
|
||||||
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
|
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathAndRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
|
||||||
|
Map<String, String> requestParams = new HashMap<>();
|
||||||
|
requestParams.put("key1", "value 1");
|
||||||
|
requestParams.put("key2", "value@!$2");
|
||||||
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
|
String path = "path+1";
|
||||||
|
|
||||||
|
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
|
||||||
|
|
||||||
|
Assert.assertThat(testUrlWithPath, is(encodedURL));
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,12 @@
|
|||||||
package com.baeldung.file;
|
package com.baeldung.file;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import org.apache.commons.io.FileUtils;
|
||||||
import java.io.File;
|
import org.hamcrest.CoreMatchers;
|
||||||
import java.io.FileInputStream;
|
import org.hamcrest.Matchers;
|
||||||
import java.io.IOException;
|
import org.junit.Assert;
|
||||||
import java.io.InputStream;
|
import org.junit.Test;
|
||||||
import java.io.InputStreamReader;
|
|
||||||
|
import java.io.*;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.net.URLConnection;
|
import java.net.URLConnection;
|
||||||
@ -14,12 +15,6 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
|
||||||
import org.hamcrest.CoreMatchers;
|
|
||||||
import org.hamcrest.Matchers;
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class FileOperationsUnitTest {
|
public class FileOperationsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||||
String expectedData = "Baeldung";
|
String expectedData = "Example Domain";
|
||||||
|
|
||||||
URL urlObject = new URL("http://www.baeldung.com/");
|
URL urlObject = new URL("http://www.example.com/");
|
||||||
|
|
||||||
URLConnection urlConnection = urlObject.openConnection();
|
URLConnection urlConnection = urlObject.openConnection();
|
||||||
|
|
||||||
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.generics;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.hasItems;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
public class GenericsTest {
|
||||||
|
|
||||||
|
// testing the generic method with Integer
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
|
||||||
|
Integer[] intArray = { 1, 2, 3, 4, 5 };
|
||||||
|
List<Integer> list = Generics.fromArrayToList(intArray);
|
||||||
|
|
||||||
|
assertThat(list, hasItems(intArray));
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing the generic method with Integer and String type
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
|
||||||
|
Integer[] intArray = { 1, 2, 3, 4, 5 };
|
||||||
|
List<String> stringList = Generics.fromArrayToList(intArray, Object::toString);
|
||||||
|
assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing the generic method with String
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
|
||||||
|
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
|
||||||
|
List<String> list = Generics.fromArrayToList(stringArray);
|
||||||
|
|
||||||
|
assertThat(list, hasItems(stringArray));
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing the generic method with Number as upper bound with Integer
|
||||||
|
// if we test fromArrayToListWithUpperBound with any type that doesn't
|
||||||
|
// extend Number it will fail to compile
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
|
||||||
|
Integer[] intArray = { 1, 2, 3, 4, 5 };
|
||||||
|
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
|
||||||
|
|
||||||
|
assertThat(list, hasItems(intArray));
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing paintAllBuildings method with a subtype of Building, the method
|
||||||
|
// will work with all subtypes of Building
|
||||||
|
@Test
|
||||||
|
public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
|
||||||
|
try {
|
||||||
|
List<Building> subBuildingsList = new ArrayList<>();
|
||||||
|
subBuildingsList.add(new Building());
|
||||||
|
subBuildingsList.add(new House());
|
||||||
|
|
||||||
|
// prints
|
||||||
|
// Painting Building
|
||||||
|
// Painting House
|
||||||
|
Generics.paintAllBuildings(subBuildingsList);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.grep;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.unix4j.Unix4j;
|
||||||
|
import static org.unix4j.Unix4j.*;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import org.unix4j.line.Line;
|
||||||
|
import static org.unix4j.unix.Grep.*;
|
||||||
|
import static org.unix4j.unix.cut.CutOption.*;
|
||||||
|
|
||||||
|
public class GrepWithUnix4JTest {
|
||||||
|
|
||||||
|
private File fileToGrep;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
final String separator = File.separator;
|
||||||
|
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
|
||||||
|
fileToGrep = new File(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGrepWithSimpleString_thenCorrect() {
|
||||||
|
int expectedLineCount = 4;
|
||||||
|
|
||||||
|
// grep "NINETEEN" dictionary.txt
|
||||||
|
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
|
||||||
|
|
||||||
|
assertEquals(expectedLineCount, lines.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInverseGrepWithSimpleString_thenCorrect() {
|
||||||
|
int expectedLineCount = 178687;
|
||||||
|
|
||||||
|
// grep -v "NINETEEN" dictionary.txt
|
||||||
|
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
|
||||||
|
|
||||||
|
assertEquals(expectedLineCount, lines.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGrepWithRegex_thenCorrect() {
|
||||||
|
int expectedLineCount = 151;
|
||||||
|
|
||||||
|
// grep -c ".*?NINE.*?" dictionary.txt
|
||||||
|
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
|
||||||
|
|
||||||
|
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
|
||||||
|
}
|
||||||
|
}
|
@ -4,12 +4,10 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
|
||||||
public class SHA256HashingTest {
|
public class SHA256HashingTest {
|
||||||
|
|
||||||
private static String originalValue = "abc123";
|
private static String originalValue = "abc123";
|
||||||
private static String hashedValue =
|
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||||
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testHashWithJavaMessageDigest() throws Exception {
|
public void testHashWithJavaMessageDigest() throws Exception {
|
||||||
|
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)
|
@ -0,0 +1,2 @@
|
|||||||
|
Relevant Articles:
|
||||||
|
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)
|
@ -119,8 +119,7 @@ public class StringConversionTest {
|
|||||||
int afterConvCalendarDay = 03;
|
int afterConvCalendarDay = 03;
|
||||||
Month afterConvCalendarMonth = Month.DECEMBER;
|
Month afterConvCalendarMonth = Month.DECEMBER;
|
||||||
int afterConvCalendarYear = 2007;
|
int afterConvCalendarYear = 2007;
|
||||||
LocalDateTime afterConvDate
|
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||||
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
|
||||||
|
|
||||||
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
||||||
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
||||||
|
350
core-java/src/test/java/com/baeldung/java/map/MapTest.java
Normal file
350
core-java/src/test/java/com/baeldung/java/map/MapTest.java
Normal file
@ -0,0 +1,350 @@
|
|||||||
|
package com.baeldung.java.map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MapTest {
|
||||||
|
@Test
|
||||||
|
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
Set<String> keys = map.keySet();
|
||||||
|
|
||||||
|
assertEquals(2, keys.size());
|
||||||
|
assertTrue(keys.contains("name"));
|
||||||
|
assertTrue(keys.contains("type"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashMap_whenRetrievesValues_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
Collection<String> values = map.values();
|
||||||
|
|
||||||
|
assertEquals(2, values.size());
|
||||||
|
assertTrue(values.contains("baeldung"));
|
||||||
|
assertTrue(values.contains("blog"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
Set<Entry<String, String>> entries = map.entrySet();
|
||||||
|
|
||||||
|
assertEquals(2, entries.size());
|
||||||
|
for (Entry<String, String> e : entries) {
|
||||||
|
String key = e.getKey();
|
||||||
|
String val = e.getValue();
|
||||||
|
assertTrue(key.equals("name") || key.equals("type"));
|
||||||
|
assertTrue(val.equals("baeldung") || val.equals("blog"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
assertEquals(2, map.size());
|
||||||
|
|
||||||
|
Set<String> keys = map.keySet();
|
||||||
|
|
||||||
|
keys.remove("name");
|
||||||
|
assertEquals(1, map.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ConcurrentModificationException.class)
|
||||||
|
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
Set<String> keys = map.keySet();
|
||||||
|
Iterator<String> it = keys.iterator();
|
||||||
|
map.remove("type");
|
||||||
|
while (it.hasNext()) {
|
||||||
|
String key = it.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void givenIterator_whenRemoveWorks_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("name", "baeldung");
|
||||||
|
map.put("type", "blog");
|
||||||
|
|
||||||
|
Set<String> keys = map.keySet();
|
||||||
|
Iterator<String> it = keys.iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
it.next();
|
||||||
|
it.remove();
|
||||||
|
}
|
||||||
|
assertEquals(0, map.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenHashCodeIsCalledOnPut_thenCorrect() {
|
||||||
|
MyKey key = new MyKey(1, "name");
|
||||||
|
Map<MyKey, String> map = new HashMap<>();
|
||||||
|
map.put(key, "val");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenHashCodeIsCalledOnGet_thenCorrect() {
|
||||||
|
MyKey key = new MyKey(1, "name");
|
||||||
|
Map<MyKey, String> map = new HashMap<>();
|
||||||
|
map.put(key, "val");
|
||||||
|
map.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetWorks_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("key", "val");
|
||||||
|
|
||||||
|
String val = map.get("key");
|
||||||
|
|
||||||
|
assertEquals("val", val);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
|
||||||
|
String rtnVal = map.put("key1", "val1");
|
||||||
|
|
||||||
|
assertNull(rtnVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
|
||||||
|
String rtnVal = map.get("key1");
|
||||||
|
|
||||||
|
assertNull(rtnVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
|
||||||
|
String rtnVal = map.put("key1", null);
|
||||||
|
|
||||||
|
assertNull(rtnVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullKeyAndVal_whenAccepts_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
|
||||||
|
map.put(null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullVal_whenRetrieves_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("key", null);
|
||||||
|
|
||||||
|
String val = map.get("key");
|
||||||
|
|
||||||
|
assertNull(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenContainsDistinguishesNullValues_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
|
||||||
|
String val1 = map.get("key");
|
||||||
|
boolean valPresent = map.containsKey("key");
|
||||||
|
|
||||||
|
assertNull(val1);
|
||||||
|
assertFalse(valPresent);
|
||||||
|
|
||||||
|
map.put("key", null);
|
||||||
|
String val = map.get("key");
|
||||||
|
valPresent = map.containsKey("key");
|
||||||
|
|
||||||
|
assertNull(val);
|
||||||
|
assertTrue(valPresent);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPutReturnsPrevValue_thenCorrect() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("key1", "val1");
|
||||||
|
String rtnVal = map.put("key1", "val2");
|
||||||
|
|
||||||
|
assertEquals("val1", rtnVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||||
|
HashMap<MyKey, String> map = new HashMap<>();
|
||||||
|
MyKey k1 = new MyKey(1, "firstKey");
|
||||||
|
MyKey k2 = new MyKey(2, "secondKey");
|
||||||
|
MyKey k3 = new MyKey(2, "thirdKey");
|
||||||
|
|
||||||
|
System.out.println("storing value for k1");
|
||||||
|
map.put(k1, "firstValue");
|
||||||
|
|
||||||
|
System.out.println("storing value for k2");
|
||||||
|
map.put(k2, "secondValue");
|
||||||
|
|
||||||
|
System.out.println("storing value for k3");
|
||||||
|
map.put(k3, "thirdValue");
|
||||||
|
|
||||||
|
System.out.println("retrieving value for k1");
|
||||||
|
String v1 = map.get(k1);
|
||||||
|
|
||||||
|
System.out.println("retrieving value for k2");
|
||||||
|
String v2 = map.get(k2);
|
||||||
|
|
||||||
|
System.out.println("retrieving value for k3");
|
||||||
|
String v3 = map.get(k3);
|
||||||
|
|
||||||
|
assertEquals("firstValue", v1);
|
||||||
|
assertEquals("secondValue", v2);
|
||||||
|
assertEquals("thirdValue", v3);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() {
|
||||||
|
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
|
||||||
|
map.put(1, null);
|
||||||
|
map.put(2, null);
|
||||||
|
map.put(3, null);
|
||||||
|
map.put(4, null);
|
||||||
|
map.put(5, null);
|
||||||
|
Set<Integer> keys = map.keySet();
|
||||||
|
Integer[] arr = keys.toArray(new Integer[0]);
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
assertEquals(new Integer(i + 1), arr[i]);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() {
|
||||||
|
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
|
||||||
|
map.put(1, null);
|
||||||
|
map.put(2, null);
|
||||||
|
map.put(3, null);
|
||||||
|
map.put(4, null);
|
||||||
|
map.put(5, null);
|
||||||
|
Set<Integer> keys = map.keySet();
|
||||||
|
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||||
|
map.get(4);
|
||||||
|
assertEquals("[1, 2, 3, 5, 4]", keys.toString());
|
||||||
|
map.get(1);
|
||||||
|
assertEquals("[2, 3, 5, 4, 1]", keys.toString());
|
||||||
|
map.get(3);
|
||||||
|
assertEquals("[2, 5, 4, 1, 3]", keys.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() {
|
||||||
|
LinkedHashMap<Integer, String> map = new MyLinkedHashMap<>(16, .75f, true);
|
||||||
|
map.put(1, null);
|
||||||
|
map.put(2, null);
|
||||||
|
map.put(3, null);
|
||||||
|
map.put(4, null);
|
||||||
|
map.put(5, null);
|
||||||
|
Set<Integer> keys = map.keySet();
|
||||||
|
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||||
|
map.put(6, null);
|
||||||
|
assertEquals("[2, 3, 4, 5, 6]", keys.toString());
|
||||||
|
map.put(7, null);
|
||||||
|
assertEquals("[3, 4, 5, 6, 7]", keys.toString());
|
||||||
|
map.put(8, null);
|
||||||
|
assertEquals("[4, 5, 6, 7, 8]", keys.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
|
||||||
|
TreeMap<Integer, String> map = new TreeMap<>();
|
||||||
|
map.put(3, "val");
|
||||||
|
map.put(2, "val");
|
||||||
|
map.put(1, "val");
|
||||||
|
map.put(5, "val");
|
||||||
|
map.put(4, "val");
|
||||||
|
assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() {
|
||||||
|
TreeMap<String, String> map = new TreeMap<>();
|
||||||
|
map.put("c", "val");
|
||||||
|
map.put("b", "val");
|
||||||
|
map.put("a", "val");
|
||||||
|
map.put("e", "val");
|
||||||
|
map.put("d", "val");
|
||||||
|
|
||||||
|
assertEquals("[a, b, c, d, e]", map.keySet().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||||
|
TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compare(Integer o1, Integer o2) {
|
||||||
|
return o2 - o1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
map.put(3, "val");
|
||||||
|
map.put(2, "val");
|
||||||
|
map.put(1, "val");
|
||||||
|
map.put(5, "val");
|
||||||
|
map.put(4, "val");
|
||||||
|
|
||||||
|
assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTreeMap_whenPerformsQueries_thenCorrect() {
|
||||||
|
TreeMap<Integer, String> map = new TreeMap<>();
|
||||||
|
map.put(3, "val");
|
||||||
|
map.put(2, "val");
|
||||||
|
map.put(1, "val");
|
||||||
|
map.put(5, "val");
|
||||||
|
map.put(4, "val");
|
||||||
|
|
||||||
|
Integer highestKey = map.lastKey();
|
||||||
|
Integer lowestKey = map.firstKey();
|
||||||
|
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||||
|
Set<Integer> keysGreaterThanEqTo3 = map.tailMap(3).keySet();
|
||||||
|
|
||||||
|
assertEquals(new Integer(5), highestKey);
|
||||||
|
assertEquals(new Integer(1), lowestKey);
|
||||||
|
assertEquals("[1, 2]", keysLessThan3.toString());
|
||||||
|
assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,122 +0,0 @@
|
|||||||
package com.baeldung.java.networking.interfaces;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.InterfaceAddress;
|
|
||||||
import java.net.NetworkInterface;
|
|
||||||
import java.net.SocketException;
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.Enumeration;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class NetworkInterfaceTest {
|
|
||||||
@Test
|
|
||||||
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
|
||||||
assertNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
|
||||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
|
||||||
assertNotNull(nif);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
|
||||||
InetAddress address = addressEnum.nextElement();
|
|
||||||
assertEquals("127.0.0.1", address.getHostAddress());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
|
|
||||||
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
|
||||||
InterfaceAddress address = addressEnum.get(0);
|
|
||||||
InetAddress localAddress = address.getAddress();
|
|
||||||
InetAddress broadCastAddress = address.getBroadcast();
|
|
||||||
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
|
||||||
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertTrue(nif.isLoopback());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertTrue(nif.isUp());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertFalse(nif.isPointToPoint());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertFalse(nif.isVirtual());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
assertTrue(nif.supportsMulticast());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
|
||||||
byte[] bytes = nif.getHardwareAddress();
|
|
||||||
assertNotNull(bytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
|
||||||
NetworkInterface nif = NetworkInterface.getByName("net0");
|
|
||||||
int mtu = nif.getMTU();
|
|
||||||
assertEquals(1500, mtu);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,64 +1,72 @@
|
|||||||
package com.baeldung.java.nio2;
|
package com.baeldung.java.nio2;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.DirectoryNotEmptyException;
|
|
||||||
import java.nio.file.FileAlreadyExistsException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.NoSuchFileException;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class FileTest {
|
public class FileTest {
|
||||||
private static final String HOME = System.getProperty("user.home");
|
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString());
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() throws IOException {
|
||||||
|
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() throws IOException {
|
||||||
|
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
// checking file or dir
|
// checking file or dir
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||||
Path p = Paths.get(HOME + "/inexistent_file.txt");
|
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
|
||||||
assertTrue(Files.notExists(p));
|
assertTrue(Files.notExists(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertFalse(Files.isRegularFile(p));
|
assertFalse(Files.isRegularFile(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.isReadable(p));
|
assertTrue(Files.isReadable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(System.getProperty("user.home"));
|
||||||
assertTrue(Files.isWritable(p));
|
assertTrue(Files.isWritable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(System.getProperty("user.home"));
|
||||||
assertTrue(Files.isExecutable(p));
|
assertTrue(Files.isExecutable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||||
Path p1 = Paths.get(HOME);
|
Path p1 = Paths.get(TEMP_DIR);
|
||||||
Path p2 = Paths.get(HOME);
|
Path p2 = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.isSameFile(p1, p2));
|
assertTrue(Files.isSameFile(p1, p2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,7 +75,7 @@ public class FileTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||||
Path p = Paths.get(HOME + "/" + fileName);
|
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createFile(p);
|
Files.createFile(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
@ -77,7 +85,7 @@ public class FileTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
@ -89,7 +97,7 @@ public class FileTest {
|
|||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
|
|
||||||
@ -97,7 +105,7 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||||
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
|
||||||
Path subdir = dir.resolve("subdir");
|
Path subdir = dir.resolve("subdir");
|
||||||
assertFalse(Files.exists(dir));
|
assertFalse(Files.exists(dir));
|
||||||
assertFalse(Files.exists(subdir));
|
assertFalse(Files.exists(subdir));
|
||||||
@ -110,7 +118,7 @@ public class FileTest {
|
|||||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||||
String prefix = "log_";
|
String prefix = "log_";
|
||||||
String suffix = ".txt";
|
String suffix = ".txt";
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(TEMP_DIR + "/");
|
||||||
p = Files.createTempFile(p, prefix, suffix);
|
p = Files.createTempFile(p, prefix, suffix);
|
||||||
// like log_8821081429012075286.txt
|
// like log_8821081429012075286.txt
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
@ -119,7 +127,7 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(TEMP_DIR + "/");
|
||||||
p = Files.createTempFile(p, null, null);
|
p = Files.createTempFile(p, null, null);
|
||||||
// like 8600179353689423985.tmp
|
// like 8600179353689423985.tmp
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
@ -136,7 +144,7 @@ public class FileTest {
|
|||||||
// delete file
|
// delete file
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/fileToDelete.txt");
|
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createFile(p);
|
Files.createFile(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
@ -147,7 +155,7 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test(expected = DirectoryNotEmptyException.class)
|
@Test(expected = DirectoryNotEmptyException.class)
|
||||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||||
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
|
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir);
|
Files.createDirectory(dir);
|
||||||
assertTrue(Files.exists(dir));
|
assertTrue(Files.exists(dir));
|
||||||
Path file = dir.resolve("file.txt");
|
Path file = dir.resolve("file.txt");
|
||||||
@ -160,7 +168,7 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.delete(p);
|
Files.delete(p);
|
||||||
|
|
||||||
@ -168,7 +176,7 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.deleteIfExists(p);
|
Files.deleteIfExists(p);
|
||||||
|
|
||||||
@ -177,8 +185,8 @@ public class FileTest {
|
|||||||
// copy file
|
// copy file
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
@ -193,8 +201,8 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
@ -210,8 +218,8 @@ public class FileTest {
|
|||||||
// moving files
|
// moving files
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
@ -227,8 +235,8 @@ public class FileTest {
|
|||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -1,195 +0,0 @@
|
|||||||
package com.baeldung.java.nio2;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.nio.file.NoSuchFileException;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class PathTest {
|
|
||||||
|
|
||||||
private static final String HOME = System.getProperty("user.home");
|
|
||||||
|
|
||||||
// creating a path
|
|
||||||
@Test
|
|
||||||
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles/baeldung");
|
|
||||||
assertEquals("\\articles\\baeldung", p.toString());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles", "baeldung");
|
|
||||||
assertEquals("\\articles\\baeldung", p.toString());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// retrieving path info
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles/baeldung/logs");
|
|
||||||
assertEquals("logs", p.getFileName().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles/baeldung/logs");
|
|
||||||
assertEquals("articles", p.getName(0).toString());
|
|
||||||
assertEquals("baeldung", p.getName(1).toString());
|
|
||||||
assertEquals("logs", p.getName(2).toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenCountsParts_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles/baeldung/logs");
|
|
||||||
assertEquals(3, p.getNameCount());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
|
||||||
Path p = Paths.get("/articles/baeldung/logs");
|
|
||||||
assertEquals("articles", p.subpath(0, 1).toString());
|
|
||||||
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
|
||||||
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
|
||||||
assertEquals("baeldung", p.subpath(1, 2).toString());
|
|
||||||
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
|
|
||||||
assertEquals("logs", p.subpath(2, 3).toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRetrievesParent_thenCorrect() {
|
|
||||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
|
||||||
Path p2 = Paths.get("/articles/baeldung");
|
|
||||||
Path p3 = Paths.get("/articles");
|
|
||||||
Path p4 = Paths.get("/");
|
|
||||||
|
|
||||||
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
|
||||||
assertEquals("\\articles", p2.getParent().toString());
|
|
||||||
assertEquals("\\", p3.getParent().toString());
|
|
||||||
assertEquals(null, p4.getParent());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
|
||||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
|
||||||
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
|
||||||
|
|
||||||
assertEquals("\\", p1.getRoot().toString());
|
|
||||||
assertEquals("c:\\", p2.getRoot().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// removing redundancies from path
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
|
|
||||||
Path p = Paths.get("/home/./baeldung/articles");
|
|
||||||
p = p.normalize();
|
|
||||||
assertEquals("\\home\\baeldung\\articles", p.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
|
|
||||||
Path p = Paths.get("/home/baeldung/../articles");
|
|
||||||
p = p.normalize();
|
|
||||||
assertEquals("\\home\\articles", p.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// converting a path
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
|
||||||
Path p = Paths.get("/home/baeldung/articles.html");
|
|
||||||
URI uri = p.toUri();
|
|
||||||
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
|
||||||
Path p = Paths.get("/home/baeldung/articles.html");
|
|
||||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
|
||||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
|
||||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
|
||||||
Path p = Paths.get(HOME);
|
|
||||||
assertEquals(HOME, p.toRealPath().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = NoSuchFileException.class)
|
|
||||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
|
||||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
|
||||||
|
|
||||||
p.toRealPath();
|
|
||||||
}
|
|
||||||
|
|
||||||
// joining paths
|
|
||||||
@Test
|
|
||||||
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
|
||||||
Path p = Paths.get("/baeldung/articles");
|
|
||||||
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
|
||||||
Path p = Paths.get("/baeldung/articles");
|
|
||||||
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
|
||||||
Path p = Paths.get("/baeldung/articles");
|
|
||||||
assertEquals("\\java", p.resolve("/java").toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// creating a path between 2 paths
|
|
||||||
@Test
|
|
||||||
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
|
||||||
Path p1 = Paths.get("articles");
|
|
||||||
Path p2 = Paths.get("authors");
|
|
||||||
assertEquals("..\\authors", p1.relativize(p2).toString());
|
|
||||||
assertEquals("..\\articles", p2.relativize(p1).toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
|
||||||
Path p1 = Paths.get("/baeldung");
|
|
||||||
Path p2 = Paths.get("/baeldung/authors/articles");
|
|
||||||
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
|
||||||
assertEquals("..\\..", p2.relativize(p1).toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// comparing 2 paths
|
|
||||||
@Test
|
|
||||||
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
|
||||||
Path p1 = Paths.get("/baeldung/articles");
|
|
||||||
Path p2 = Paths.get("/baeldung/articles");
|
|
||||||
Path p3 = Paths.get("/baeldung/authors");
|
|
||||||
|
|
||||||
assertTrue(p1.equals(p2));
|
|
||||||
assertFalse(p1.equals(p3));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenInspectsStart_thenCorrect() {
|
|
||||||
Path p1 = Paths.get("/baeldung/articles");
|
|
||||||
assertTrue(p1.startsWith("/baeldung"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPath_whenInspectsEnd_thenCorrect() {
|
|
||||||
Path p1 = Paths.get("/baeldung/articles");
|
|
||||||
assertTrue(p1.endsWith("articles"));
|
|
||||||
}
|
|
||||||
}
|
|
3
core-java/src/test/java/com/baeldung/java/nio2/README.md
Normal file
3
core-java/src/test/java/com/baeldung/java/nio2/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||||
|
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class AsyncEchoClient {
|
||||||
|
private AsynchronousSocketChannel client;
|
||||||
|
private Future<Void> future;
|
||||||
|
private static AsyncEchoClient instance;
|
||||||
|
|
||||||
|
private AsyncEchoClient() {
|
||||||
|
try {
|
||||||
|
client = AsynchronousSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
future = client.connect(hostAddress);
|
||||||
|
start();
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AsyncEchoClient getInstance() {
|
||||||
|
if (instance == null)
|
||||||
|
instance = new AsyncEchoClient();
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void start() {
|
||||||
|
try {
|
||||||
|
future.get();
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sendMessage(String message) {
|
||||||
|
byte[] byteMsg = message.getBytes();
|
||||||
|
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
|
||||||
|
Future<Integer> writeResult = client.write(buffer);
|
||||||
|
|
||||||
|
try {
|
||||||
|
writeResult.get();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
buffer.flip();
|
||||||
|
Future<Integer> readResult = client.read(buffer);
|
||||||
|
try {
|
||||||
|
readResult.get();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
String echo = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
return echo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
try {
|
||||||
|
client.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
AsyncEchoClient client = AsyncEchoClient.getInstance();
|
||||||
|
client.start();
|
||||||
|
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||||
|
String line;
|
||||||
|
System.out.println("Message to server:");
|
||||||
|
while ((line = br.readLine()) != null) {
|
||||||
|
String response = client.sendMessage(line);
|
||||||
|
System.out.println("response from server: " + response);
|
||||||
|
System.out.println("Message to server:");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class AsyncEchoServer {
|
||||||
|
private AsynchronousServerSocketChannel serverChannel;
|
||||||
|
private Future<AsynchronousSocketChannel> acceptResult;
|
||||||
|
private AsynchronousSocketChannel clientChannel;
|
||||||
|
|
||||||
|
public AsyncEchoServer() {
|
||||||
|
try {
|
||||||
|
serverChannel = AsynchronousServerSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
serverChannel.bind(hostAddress);
|
||||||
|
acceptResult = serverChannel.accept();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void runServer() {
|
||||||
|
try {
|
||||||
|
clientChannel = acceptResult.get();
|
||||||
|
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||||
|
while (true) {
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
Future<Integer> readResult = clientChannel.read(buffer);
|
||||||
|
|
||||||
|
// do some computation
|
||||||
|
|
||||||
|
readResult.get();
|
||||||
|
|
||||||
|
buffer.flip();
|
||||||
|
String message = new String(buffer.array()).trim();
|
||||||
|
if (message.equals("bye")) {
|
||||||
|
break; // while loop
|
||||||
|
}
|
||||||
|
buffer = ByteBuffer.wrap(new String(message).getBytes());
|
||||||
|
Future<Integer> writeResult = clientChannel.write(buffer);
|
||||||
|
|
||||||
|
// do some computation
|
||||||
|
writeResult.get();
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
} // while()
|
||||||
|
|
||||||
|
clientChannel.close();
|
||||||
|
serverChannel.close();
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch (InterruptedException | ExecutionException | IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AsyncEchoServer server = new AsyncEchoServer();
|
||||||
|
server.runServer();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Process start() throws IOException, InterruptedException {
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
String classpath = System.getProperty("java.class.path");
|
||||||
|
String className = AsyncEchoServer.class.getCanonicalName();
|
||||||
|
|
||||||
|
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
|
||||||
|
return builder.start();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.nio.channels.CompletionHandler;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class AsyncEchoServer2 {
|
||||||
|
private AsynchronousServerSocketChannel serverChannel;
|
||||||
|
private AsynchronousSocketChannel clientChannel;
|
||||||
|
|
||||||
|
public AsyncEchoServer2() {
|
||||||
|
try {
|
||||||
|
serverChannel = AsynchronousServerSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
serverChannel.bind(hostAddress);
|
||||||
|
while (true) {
|
||||||
|
|
||||||
|
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(AsynchronousSocketChannel result, Object attachment) {
|
||||||
|
if (serverChannel.isOpen())
|
||||||
|
serverChannel.accept(null, this);
|
||||||
|
clientChannel = result;
|
||||||
|
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||||
|
ReadWriteHandler handler = new ReadWriteHandler();
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
Map<String, Object> readInfo = new HashMap<>();
|
||||||
|
readInfo.put("action", "read");
|
||||||
|
readInfo.put("buffer", buffer);
|
||||||
|
clientChannel.read(buffer, readInfo, handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, Object attachment) {
|
||||||
|
// process error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
System.in.read();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, Map<String, Object> attachment) {
|
||||||
|
Map<String, Object> actionInfo = attachment;
|
||||||
|
String action = (String) actionInfo.get("action");
|
||||||
|
if ("read".equals(action)) {
|
||||||
|
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||||
|
buffer.flip();
|
||||||
|
actionInfo.put("action", "write");
|
||||||
|
clientChannel.write(buffer, actionInfo, this);
|
||||||
|
buffer.clear();
|
||||||
|
} else if ("write".equals(action)) {
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
actionInfo.put("action", "read");
|
||||||
|
actionInfo.put("buffer", buffer);
|
||||||
|
clientChannel.read(buffer, actionInfo, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, Map<String, Object> attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new AsyncEchoServer2();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Process start() throws IOException, InterruptedException {
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
String classpath = System.getProperty("java.class.path");
|
||||||
|
String className = AsyncEchoServer2.class.getCanonicalName();
|
||||||
|
|
||||||
|
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
|
||||||
|
return builder.start();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class AsyncEchoTest {
|
||||||
|
|
||||||
|
Process server;
|
||||||
|
AsyncEchoClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException, InterruptedException {
|
||||||
|
server = AsyncEchoServer2.start();
|
||||||
|
client = AsyncEchoClient.getInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
|
||||||
|
String resp1 = client.sendMessage("hello");
|
||||||
|
String resp2 = client.sendMessage("world");
|
||||||
|
assertEquals("hello", resp1);
|
||||||
|
assertEquals("world", resp2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void teardown() throws IOException {
|
||||||
|
server.destroy();
|
||||||
|
client.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,126 @@
|
|||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousFileChannel;
|
||||||
|
import java.nio.channels.CompletionHandler;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class AsyncFileTest {
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||||
|
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||||
|
|
||||||
|
operation.get();
|
||||||
|
|
||||||
|
String fileContent = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
assertEquals(fileContent, "baeldung.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||||
|
Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString()));
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, ByteBuffer attachment) {
|
||||||
|
// result is number of bytes read
|
||||||
|
// attachment is the buffer
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||||
|
String fileName = "temp";
|
||||||
|
Path path = Paths.get(fileName);
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
long position = 0;
|
||||||
|
|
||||||
|
buffer.put("hello world".getBytes());
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
operation.get();
|
||||||
|
|
||||||
|
String content = readContent(path);
|
||||||
|
assertEquals("hello world", content);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||||
|
String fileName = UUID.randomUUID().toString();
|
||||||
|
Path path = Paths.get(fileName);
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
buffer.put("hello world".getBytes());
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, ByteBuffer attachment) {
|
||||||
|
// result is number of bytes written
|
||||||
|
// attachment is the buffer
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||||
|
AsynchronousFileChannel fileChannel = null;
|
||||||
|
try {
|
||||||
|
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||||
|
} catch (IOException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||||
|
|
||||||
|
operation.get();
|
||||||
|
|
||||||
|
String fileContent = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
return fileContent;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.java.nio2.attributes;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributeView;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.nio.file.attribute.FileTime;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class BasicAttribsTest {
|
||||||
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
private static BasicFileAttributes basicAttribs;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() throws IOException {
|
||||||
|
Path home = Paths.get(HOME);
|
||||||
|
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
|
||||||
|
basicAttribs = basicView.readAttributes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileTimes_whenComparesThem_ThenCorrect() {
|
||||||
|
FileTime created = basicAttribs.creationTime();
|
||||||
|
FileTime modified = basicAttribs.lastModifiedTime();
|
||||||
|
FileTime accessed = basicAttribs.lastAccessTime();
|
||||||
|
|
||||||
|
System.out.println("Created: " + created);
|
||||||
|
System.out.println("Modified: " + modified);
|
||||||
|
System.out.println("Accessed: " + accessed);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenGetsFileSize_thenCorrect() {
|
||||||
|
long size = basicAttribs.size();
|
||||||
|
assertTrue(size > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfDirectory_thenCorrect() {
|
||||||
|
boolean isDir = basicAttribs.isDirectory();
|
||||||
|
assertTrue(isDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfFile_thenCorrect() {
|
||||||
|
boolean isFile = basicAttribs.isRegularFile();
|
||||||
|
assertFalse(isFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfSymLink_thenCorrect() {
|
||||||
|
boolean isSymLink = basicAttribs.isSymbolicLink();
|
||||||
|
assertFalse(isSymLink);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfOther_thenCorrect() {
|
||||||
|
boolean isOther = basicAttribs.isOther();
|
||||||
|
assertFalse(isOther);
|
||||||
|
}
|
||||||
|
}
|
@ -4,6 +4,7 @@ import com.google.common.collect.Lists;
|
|||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.hasSize;
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
@ -16,7 +17,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
|
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
|
||||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||||
final List<Integer> listWithoutNulls = list.parallelStream().filter(i -> i != null).collect(Collectors.toList());
|
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||||
|
|
||||||
assertThat(listWithoutNulls, hasSize(3));
|
assertThat(listWithoutNulls, hasSize(3));
|
||||||
}
|
}
|
||||||
@ -24,7 +25,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
|
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
|
||||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||||
final List<Integer> listWithoutNulls = list.stream().filter(i -> i != null).collect(Collectors.toList());
|
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||||
|
|
||||||
assertThat(listWithoutNulls, hasSize(3));
|
assertThat(listWithoutNulls, hasSize(3));
|
||||||
}
|
}
|
||||||
@ -32,7 +33,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||||
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||||
listWithoutNulls.removeIf(p -> p == null);
|
listWithoutNulls.removeIf(Objects::isNull);
|
||||||
|
|
||||||
assertThat(listWithoutNulls, hasSize(3));
|
assertThat(listWithoutNulls, hasSize(3));
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class JavaFileSizeUnitTest {
|
||||||
|
private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11;
|
||||||
|
private String filePath;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
final String separator = File.separator;
|
||||||
|
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetFileSize_thenCorrect() {
|
||||||
|
final File file = new File(filePath);
|
||||||
|
|
||||||
|
final long size = getFileSize(file);
|
||||||
|
|
||||||
|
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
|
||||||
|
final Path path = Paths.get(this.filePath);
|
||||||
|
final FileChannel fileChannel = FileChannel.open(path);
|
||||||
|
|
||||||
|
final long fileSize = fileChannel.size();
|
||||||
|
|
||||||
|
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
|
||||||
|
final File file = new File(filePath);
|
||||||
|
|
||||||
|
final long size = FileUtils.sizeOf(file);
|
||||||
|
|
||||||
|
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetReadableFileSize_thenCorrect() {
|
||||||
|
final File file = new File(filePath);
|
||||||
|
|
||||||
|
final long size = getFileSize(file);
|
||||||
|
|
||||||
|
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getFileSize(final File file) {
|
||||||
|
final long length = file.length();
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
}
|
@ -8,7 +8,7 @@ import java.io.StringWriter;
|
|||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
|
|
||||||
public class JavaTryWithResourcesUnitTest {
|
public class JavaTryWithResourcesLongRunningUnitTest {
|
||||||
|
|
||||||
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
||||||
private Date resource1Date, resource2Date;
|
private Date resource1Date, resource2Date;
|
@ -0,0 +1,235 @@
|
|||||||
|
package com.baeldung.java8.optional;
|
||||||
|
|
||||||
|
import com.baeldung.optional.Modem;
|
||||||
|
import com.baeldung.optional.Person;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class OptionalTest {
|
||||||
|
// creating Optional
|
||||||
|
@Test
|
||||||
|
public void whenCreatesEmptyOptional_thenCorrect() {
|
||||||
|
Optional<String> empty = Optional.empty();
|
||||||
|
assertFalse(empty.isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
|
||||||
|
String name = "baeldung";
|
||||||
|
Optional.of(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
|
||||||
|
String name = null;
|
||||||
|
Optional<String> opt = Optional.of(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonNull_whenCreatesOptional_thenCorrect() {
|
||||||
|
String name = "baeldung";
|
||||||
|
Optional<String> opt = Optional.of(name);
|
||||||
|
assertEquals("Optional[baeldung]", opt.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonNull_whenCreatesNullable_thenCorrect() {
|
||||||
|
String name = "baeldung";
|
||||||
|
Optional<String> opt = Optional.ofNullable(name);
|
||||||
|
assertEquals("Optional[baeldung]", opt.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNull_whenCreatesNullable_thenCorrect() {
|
||||||
|
String name = null;
|
||||||
|
Optional<String> opt = Optional.ofNullable(name);
|
||||||
|
assertEquals("Optional.empty", opt.toString());
|
||||||
|
}
|
||||||
|
// Checking Value With isPresent()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenIsPresentWorks_thenCorrect() {
|
||||||
|
Optional<String> opt = Optional.of("Baeldung");
|
||||||
|
assertTrue(opt.isPresent());
|
||||||
|
|
||||||
|
opt = Optional.ofNullable(null);
|
||||||
|
assertFalse(opt.isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Condition Action With ifPresent()
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenIfPresentWorks_thenCorrect() {
|
||||||
|
Optional<String> opt = Optional.of("baeldung");
|
||||||
|
opt.ifPresent(name -> System.out.println(name.length()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// returning Value With get()
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenGetsValue_thenCorrect() {
|
||||||
|
Optional<String> opt = Optional.of("baeldung");
|
||||||
|
String name = opt.get();
|
||||||
|
assertEquals("baeldung", name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchElementException.class)
|
||||||
|
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
|
||||||
|
Optional<String> opt = Optional.ofNullable(null);
|
||||||
|
String name = opt.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conditional Return With filter()
|
||||||
|
@Test
|
||||||
|
public void whenOptionalFilterWorks_thenCorrect() {
|
||||||
|
Integer year = 2016;
|
||||||
|
Optional<Integer> yearOptional = Optional.of(year);
|
||||||
|
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
|
||||||
|
assertTrue(is2016);
|
||||||
|
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
|
||||||
|
assertFalse(is2017);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFiltersWithoutOptional_thenCorrect() {
|
||||||
|
assertTrue(priceIsInRange1(new Modem(10.0)));
|
||||||
|
assertFalse(priceIsInRange1(new Modem(9.9)));
|
||||||
|
assertFalse(priceIsInRange1(new Modem(null)));
|
||||||
|
assertFalse(priceIsInRange1(new Modem(15.5)));
|
||||||
|
assertFalse(priceIsInRange1(null));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFiltersWithOptional_thenCorrect() {
|
||||||
|
assertTrue(priceIsInRange2(new Modem(10.0)));
|
||||||
|
assertFalse(priceIsInRange2(new Modem(9.9)));
|
||||||
|
assertFalse(priceIsInRange2(new Modem(null)));
|
||||||
|
assertFalse(priceIsInRange2(new Modem(15.5)));
|
||||||
|
assertFalse(priceIsInRange1(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean priceIsInRange1(Modem modem) {
|
||||||
|
boolean isInRange = false;
|
||||||
|
if (modem != null && modem.getPrice() != null && (modem.getPrice() >= 10 && modem.getPrice() <= 15)) {
|
||||||
|
isInRange = true;
|
||||||
|
}
|
||||||
|
return isInRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean priceIsInRange2(Modem modem2) {
|
||||||
|
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transforming Value With map()
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenMapWorks_thenCorrect() {
|
||||||
|
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
|
||||||
|
Optional<List<String>> listOptional = Optional.of(companyNames);
|
||||||
|
|
||||||
|
int size = listOptional.map(List::size).orElse(0);
|
||||||
|
assertEquals(6, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenMapWorks_thenCorrect2() {
|
||||||
|
String name = "baeldung";
|
||||||
|
Optional<String> nameOptional = Optional.of(name);
|
||||||
|
|
||||||
|
int len = nameOptional.map(String::length).orElse(0);
|
||||||
|
assertEquals(8, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
|
||||||
|
String password = " password ";
|
||||||
|
Optional<String> passOpt = Optional.of(password);
|
||||||
|
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
|
||||||
|
assertFalse(correctPassword);
|
||||||
|
|
||||||
|
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
|
||||||
|
assertTrue(correctPassword);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transforming Value With flatMap()
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
|
||||||
|
Person person = new Person("john", 26);
|
||||||
|
Optional<Person> personOptional = Optional.of(person);
|
||||||
|
|
||||||
|
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getName);
|
||||||
|
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
|
||||||
|
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
|
||||||
|
assertEquals("john", name1);
|
||||||
|
|
||||||
|
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
|
||||||
|
assertEquals("john", name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
|
||||||
|
Person person = new Person("john", 26);
|
||||||
|
person.setPassword("password");
|
||||||
|
Optional<Person> personOptional = Optional.of(person);
|
||||||
|
|
||||||
|
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
|
||||||
|
assertEquals("password", password);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default Value With orElse
|
||||||
|
@Test
|
||||||
|
public void whenOrElseWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElse("john");
|
||||||
|
assertEquals("john", name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default Value With orElseGet
|
||||||
|
@Test
|
||||||
|
public void whenOrElseGetWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
|
||||||
|
assertEquals("john", name);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
|
||||||
|
String text = null;
|
||||||
|
System.out.println("Using orElseGet:");
|
||||||
|
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
||||||
|
assertEquals("Default Value", defaultText);
|
||||||
|
|
||||||
|
System.out.println("Using orElse:");
|
||||||
|
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
||||||
|
assertEquals("Default Value", defaultText);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
|
||||||
|
String text = "Text present";
|
||||||
|
System.out.println("Using orElseGet:");
|
||||||
|
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
||||||
|
assertEquals("Text present", defaultText);
|
||||||
|
|
||||||
|
System.out.println("Using orElse:");
|
||||||
|
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
||||||
|
assertEquals("Text present", defaultText);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exceptions With orElseThrow
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void whenOrElseThrowWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMyDefault() {
|
||||||
|
System.out.println("Getting default value...");
|
||||||
|
return "Default Value";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,135 @@
|
|||||||
|
package org.baeldung.java.collections;
|
||||||
|
|
||||||
|
import com.google.common.collect.Iterables;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.CollectionUtils;
|
||||||
|
import org.apache.commons.collections4.IterableUtils;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
|
||||||
|
public class CollectionsConcatenateUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
Collection<String> collectionC = asList("W", "X");
|
||||||
|
|
||||||
|
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
|
||||||
|
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
|
||||||
|
|
||||||
|
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
|
||||||
|
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
|
||||||
|
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
|
||||||
|
|
||||||
|
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
|
||||||
|
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
|
||||||
|
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
|
||||||
|
|
||||||
|
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
|
||||||
|
Iterable<String> combinedIterables = concat(collectionA, collectionB);
|
||||||
|
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
|
||||||
|
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E> Iterable<E> concat(Iterable<? extends E> i1, Iterable<? extends E> i2) {
|
||||||
|
return new Iterable<E>() {
|
||||||
|
public Iterator<E> iterator() {
|
||||||
|
return new Iterator<E>() {
|
||||||
|
Iterator<? extends E> listIterator = i1.iterator();
|
||||||
|
Boolean checkedHasNext;
|
||||||
|
E nextValue;
|
||||||
|
private boolean startTheSecond;
|
||||||
|
|
||||||
|
void theNext() {
|
||||||
|
if (listIterator.hasNext()) {
|
||||||
|
checkedHasNext = true;
|
||||||
|
nextValue = listIterator.next();
|
||||||
|
} else if (startTheSecond)
|
||||||
|
checkedHasNext = false;
|
||||||
|
else {
|
||||||
|
startTheSecond = true;
|
||||||
|
listIterator = i2.iterator();
|
||||||
|
theNext();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasNext() {
|
||||||
|
if (checkedHasNext == null)
|
||||||
|
theNext();
|
||||||
|
return checkedHasNext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public E next() {
|
||||||
|
if (!hasNext())
|
||||||
|
throw new NoSuchElementException();
|
||||||
|
checkedHasNext = null;
|
||||||
|
return nextValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void remove() {
|
||||||
|
listIterator.remove();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
|
||||||
|
List<E> list = new ArrayList<>();
|
||||||
|
for (E item : iter) {
|
||||||
|
list.add(item);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingApacheCommons_whenConcatenatingUsingUnion_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
|
||||||
|
Iterable<String> combinedIterables = CollectionUtils.union(collectionA, collectionB);
|
||||||
|
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
|
||||||
|
|
||||||
|
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingApacheCommons_whenConcatenatingUsingChainedIterable_thenCorrect() {
|
||||||
|
Collection<String> collectionA = asList("S", "T");
|
||||||
|
Collection<String> collectionB = asList("U", "V");
|
||||||
|
|
||||||
|
Iterable<String> combinedIterables = IterableUtils.chainedIterable(collectionA, collectionB);
|
||||||
|
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
|
||||||
|
|
||||||
|
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,154 @@
|
|||||||
|
package org.baeldung.java.collections;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class JoinSplitCollectionsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoiningTwoArrays_thenJoined() {
|
||||||
|
String[] animals1 = new String[] { "Dog", "Cat" };
|
||||||
|
String[] animals2 = new String[] { "Bird", "Cow" };
|
||||||
|
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
|
||||||
|
|
||||||
|
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoiningTwoCollections_thenJoined() {
|
||||||
|
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
|
||||||
|
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
|
||||||
|
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
|
||||||
|
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
|
||||||
|
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
|
||||||
|
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertArrayToString_thenConverted() {
|
||||||
|
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" };
|
||||||
|
String result = Arrays.stream(animals).collect(Collectors.joining(", "));
|
||||||
|
|
||||||
|
assertEquals(result, "Dog, Cat, Bird, Cow");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertCollectionToString_thenConverted() {
|
||||||
|
Collection<String> animals = Arrays.asList("Dog", "Cat", "Bird", "Cow");
|
||||||
|
String result = animals.stream().collect(Collectors.joining(", "));
|
||||||
|
|
||||||
|
assertEquals(result, "Dog, Cat, Bird, Cow");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertMapToString_thenConverted() {
|
||||||
|
Map<Integer, String> animals = new HashMap<>();
|
||||||
|
animals.put(1, "Dog");
|
||||||
|
animals.put(2, "Cat");
|
||||||
|
animals.put(3, "Cow");
|
||||||
|
|
||||||
|
String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
|
||||||
|
|
||||||
|
assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertNestedCollectionToString_thenConverted() {
|
||||||
|
Collection<List<String>> nested = new ArrayList<>();
|
||||||
|
nested.add(Arrays.asList("Dog", "Cat"));
|
||||||
|
nested.add(Arrays.asList("Cow", "Pig"));
|
||||||
|
|
||||||
|
String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
|
||||||
|
|
||||||
|
assertEquals(result, "Dog-Cat; Cow-Pig");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
|
||||||
|
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
|
||||||
|
String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
|
||||||
|
|
||||||
|
assertEquals(result, "Dog, Cat, Moose");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSplitCollectionHalf_thenConverted() {
|
||||||
|
Collection<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
|
||||||
|
Collection<String> result1 = new ArrayList<>();
|
||||||
|
Collection<String> result2 = new ArrayList<>();
|
||||||
|
AtomicInteger count = new AtomicInteger();
|
||||||
|
int midpoint = Math.round(animals.size() / 2);
|
||||||
|
|
||||||
|
animals.forEach(next -> {
|
||||||
|
int index = count.getAndIncrement();
|
||||||
|
if (index < midpoint) {
|
||||||
|
result1.add(next);
|
||||||
|
} else {
|
||||||
|
result2.add(next);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
assertTrue(result1.equals(Arrays.asList("Dog", "Cat", "Cow")));
|
||||||
|
assertTrue(result2.equals(Arrays.asList("Bird", "Moose", "Pig")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSplitArrayByWordLength_thenConverted() {
|
||||||
|
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" };
|
||||||
|
Map<Integer, List<String>> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length));
|
||||||
|
|
||||||
|
assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));
|
||||||
|
assertTrue(result.get(4).equals(Arrays.asList("Bird")));
|
||||||
|
assertTrue(result.get(5).equals(Arrays.asList("Moose")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertStringToArray_thenConverted() {
|
||||||
|
String animals = "Dog, Cat, Bird, Cow";
|
||||||
|
String[] result = animals.split(", ");
|
||||||
|
|
||||||
|
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertStringToCollection_thenConverted() {
|
||||||
|
String animals = "Dog, Cat, Bird, Cow";
|
||||||
|
Collection<String> result = Arrays.asList(animals.split(", "));
|
||||||
|
|
||||||
|
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertStringToMap_thenConverted() {
|
||||||
|
String animals = "1 = Dog, 2 = Cat, 3 = Bird";
|
||||||
|
|
||||||
|
Map<Integer, String> result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
|
||||||
|
|
||||||
|
assertEquals(result.get(1), "Dog");
|
||||||
|
assertEquals(result.get(2), "Cat");
|
||||||
|
assertEquals(result.get(3), "Bird");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
|
||||||
|
String animals = "Dog. , Cat, Bird. Cow";
|
||||||
|
|
||||||
|
Collection<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,9 @@
|
|||||||
package org.baeldung.java.io;
|
package org.baeldung.java.io;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
import org.apache.commons.io.FileUtils;
|
||||||
import static org.junit.Assert.assertTrue;
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@ -9,17 +11,28 @@ import java.nio.file.FileSystemException;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class JavaFileUnitTest {
|
public class JavaFileUnitTest {
|
||||||
|
|
||||||
// create a file
|
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() throws IOException {
|
||||||
|
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanup() throws IOException {
|
||||||
|
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
final File newFile = new File("src/test/resources/newFile_jdk6.txt");
|
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
|
||||||
final boolean success = newFile.createNewFile();
|
final boolean success = newFile.createNewFile();
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
@ -27,48 +40,48 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
|
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
|
||||||
Files.createFile(newFilePath);
|
Files.createFile(newFilePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||||
com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt"));
|
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// move a file
|
// move a file
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
|
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
|
||||||
fileToMove.createNewFile();// .exists();
|
fileToMove.createNewFile();// .exists();
|
||||||
final File destDir = new File("src/test/resources/");
|
final File destDir = new File(TEMP_DIR + "/");
|
||||||
destDir.mkdir();
|
destDir.mkdir();
|
||||||
|
|
||||||
final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
|
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
|
||||||
if (!isMoved) {
|
if (!isMoved) {
|
||||||
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
|
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
|
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||||
final Path targetPath = Paths.get("src/main/resources/");
|
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||||
|
|
||||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final File fileToMove = new File("src/test/resources/fileToMove.txt");
|
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
|
||||||
fileToMove.createNewFile();
|
fileToMove.createNewFile();
|
||||||
final File destDir = new File("src/main/resources/");
|
final File destDir = new File(TEMP_DIR + "/temp");
|
||||||
final File targetFile = new File(destDir, fileToMove.getName());
|
final File targetFile = new File(destDir, fileToMove.getName());
|
||||||
com.google.common.io.Files.createParentDirs(targetFile);
|
com.google.common.io.Files.createParentDirs(targetFile);
|
||||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||||
@ -76,23 +89,24 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||||
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
|
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
|
||||||
|
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// delete a file
|
// delete a file
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
||||||
new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();
|
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
|
||||||
|
|
||||||
final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
|
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
|
||||||
final boolean success = fileToDelete.delete();
|
final boolean success = fileToDelete.delete();
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
@ -100,17 +114,17 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
||||||
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
|
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
|
||||||
|
|
||||||
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
|
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
|
||||||
Files.delete(fileToDeletePath);
|
Files.delete(fileToDeletePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
|
||||||
|
|
||||||
final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
|
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
|
||||||
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
@ -118,9 +132,9 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
|
||||||
|
|
||||||
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
|
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,55 @@
|
|||||||
|
package org.baeldung.java.sorting;
|
||||||
|
|
||||||
|
public class Employee implements Comparable {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private int age;
|
||||||
|
private double salary;
|
||||||
|
|
||||||
|
public Employee(String name, int age, double salary) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
this.salary = salary;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getSalary() {
|
||||||
|
return salary;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSalary(double salary) {
|
||||||
|
this.salary = salary;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
return ((Employee) obj).getName().equals(getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Object o) {
|
||||||
|
Employee e = (Employee) o;
|
||||||
|
return getName().compareTo(e.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,186 @@
|
|||||||
|
package org.baeldung.java.sorting;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
|
public class JavaSorting {
|
||||||
|
|
||||||
|
private int[] toSort;
|
||||||
|
private int[] sortedInts;
|
||||||
|
private int[] sortedRangeInts;
|
||||||
|
// private Integer [] integers;
|
||||||
|
// private Integer [] sortedIntegers;
|
||||||
|
// private List<Integer> integersList;
|
||||||
|
// private List<Integer> sortedIntegersList;
|
||||||
|
private Employee[] employees;
|
||||||
|
private Employee[] employeesSorted;
|
||||||
|
private Employee[] employeesSortedByAge;
|
||||||
|
private HashMap<Integer, String> map;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initVariables() {
|
||||||
|
|
||||||
|
toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
|
||||||
|
sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 };
|
||||||
|
sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 };
|
||||||
|
|
||||||
|
// integers = new Integer[]
|
||||||
|
// { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
|
||||||
|
// sortedIntegers = new Integer[]
|
||||||
|
// {1, 5, 7, 66, 88, 89, 123, 200, 255};
|
||||||
|
//
|
||||||
|
// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 });
|
||||||
|
// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255});
|
||||||
|
|
||||||
|
employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) };
|
||||||
|
employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) };
|
||||||
|
employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) };
|
||||||
|
|
||||||
|
HashMap<Integer, String> map = new HashMap<>();
|
||||||
|
map.put(55, "John");
|
||||||
|
map.put(22, "Apple");
|
||||||
|
map.put(66, "Earl");
|
||||||
|
map.put(77, "Pearl");
|
||||||
|
map.put(12, "George");
|
||||||
|
map.put(6, "Rocky");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenUsingSort_thenSortedArray() {
|
||||||
|
Arrays.sort(toSort);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(toSort, sortedInts));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_whenUsingSort_thenSortedArray() {
|
||||||
|
Integer[] integers = ArrayUtils.toObject(toSort);
|
||||||
|
Arrays.sort(integers, new Comparator<Integer>() {
|
||||||
|
@Override
|
||||||
|
public int compare(Integer a, Integer b) {
|
||||||
|
return a - b;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArray_whenUsingSortWithLambdas_thenSortedArray() {
|
||||||
|
Integer[] integersToSort = ArrayUtils.toObject(toSort);
|
||||||
|
Arrays.sort(integersToSort, (a, b) -> {
|
||||||
|
return a - b;
|
||||||
|
});
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() {
|
||||||
|
Arrays.sort(employees);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(employees, employeesSorted));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() {
|
||||||
|
Arrays.sort(toSort, 3, 7);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(toSort, sortedRangeInts));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenUsingParallelSort_thenArraySorted() {
|
||||||
|
Arrays.parallelSort(toSort);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(toSort, sortedInts));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() {
|
||||||
|
List<Employee> employeesList = Arrays.asList(employees);
|
||||||
|
|
||||||
|
employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName));
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_whenUsingSort_thenSortedList() {
|
||||||
|
List<Integer> toSortList = Ints.asList(toSort);
|
||||||
|
Collections.sort(toSortList);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenSortingByKeys_thenSortedMap() {
|
||||||
|
Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 };
|
||||||
|
|
||||||
|
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
|
||||||
|
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
|
||||||
|
@Override
|
||||||
|
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
|
||||||
|
return o1.getKey().compareTo(o2.getKey());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<Integer, String> entry : entries) {
|
||||||
|
sortedMap.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenSortingByValues_thenSortedMap() {
|
||||||
|
String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" };
|
||||||
|
|
||||||
|
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
|
||||||
|
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
|
||||||
|
@Override
|
||||||
|
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
|
||||||
|
return o1.getValue().compareTo(o2.getValue());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<Integer, String> entry : entries) {
|
||||||
|
sortedMap.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSet_whenUsingSort_thenSortedSet() {
|
||||||
|
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
|
||||||
|
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 }));
|
||||||
|
|
||||||
|
ArrayList<Integer> list = new ArrayList<Integer>(integersSet);
|
||||||
|
Collections.sort(list, (i1, i2) -> {
|
||||||
|
return i2 - i1;
|
||||||
|
});
|
||||||
|
integersSet = new LinkedHashSet<>(list);
|
||||||
|
|
||||||
|
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
178691
core-java/src/test/resources/dictionary.in
Normal file
178691
core-java/src/test/resources/dictionary.in
Normal file
File diff suppressed because it is too large
Load Diff
1
core-java/src/test/resources/file.txt
Normal file
1
core-java/src/test/resources/file.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
baeldung.com
|
@ -79,10 +79,10 @@
|
|||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>2.3.2</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.7</source>
|
<source>${java.version}</source>
|
||||||
<target>1.7</target>
|
<target>${java.version}</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -100,14 +100,15 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>1.7</java.version>
|
<java.version>1.8</java.version>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<couchbase.client.version>2.2.6</couchbase.client.version>
|
<couchbase.client.version>2.3.6</couchbase.client.version>
|
||||||
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
|
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
|
||||||
<logback.version>1.1.3</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<junit.version>4.11</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<commons-lang3.version>3.4</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -25,17 +25,22 @@
|
|||||||
resources, i.e. build is platform dependent! -->
|
resources, i.e. build is platform dependent! -->
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
|
||||||
|
<slf4j.version>1.7.21</slf4j.version>
|
||||||
|
<querydsl.version>3.7.4</querydsl.version>
|
||||||
|
<deltaspike.version>1.7.2</deltaspike.version>
|
||||||
|
|
||||||
<!-- JBoss dependency versions -->
|
<!-- JBoss dependency versions -->
|
||||||
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
|
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
|
||||||
|
|
||||||
<!-- Define the version of the JBoss BOMs we want to import to specify
|
<!-- Define the version of the JBoss BOMs we want to import to specify
|
||||||
tested stacks. -->
|
tested stacks. -->
|
||||||
<version.jboss.bom>8.2.1.Final</version.jboss.bom>
|
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
|
||||||
|
|
||||||
<!-- other plugin versions -->
|
<!-- other plugin versions -->
|
||||||
<version.compiler.plugin>3.1</version.compiler.plugin>
|
<version.compiler.plugin>3.6.0</version.compiler.plugin>
|
||||||
<version.surefire.plugin>2.16</version.surefire.plugin>
|
<surefire.plugin.version>2.19.1</surefire.plugin.version>
|
||||||
<version.war.plugin>2.5</version.war.plugin>
|
<war.plugin.version>2.6</war.plugin.version>
|
||||||
|
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
|
||||||
|
|
||||||
<!-- maven-compiler-plugin -->
|
<!-- maven-compiler-plugin -->
|
||||||
<maven.compiler.target>1.7</maven.compiler.target>
|
<maven.compiler.target>1.7</maven.compiler.target>
|
||||||
@ -56,14 +61,14 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.wildfly.bom</groupId>
|
<groupId>org.wildfly.bom</groupId>
|
||||||
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
||||||
<version>${version.jboss.bom}</version>
|
<version>${jboss.bom.version}</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.wildfly.bom</groupId>
|
<groupId>org.wildfly.bom</groupId>
|
||||||
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
|
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
|
||||||
<version>${version.jboss.bom}</version>
|
<version>${jboss.bom.version}</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
@ -187,14 +192,14 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.deltaspike.modules</groupId>
|
<groupId>org.apache.deltaspike.modules</groupId>
|
||||||
<artifactId>deltaspike-data-module-api</artifactId>
|
<artifactId>deltaspike-data-module-api</artifactId>
|
||||||
<version>1.7.1</version>
|
<version>${deltaspike.version}</version>
|
||||||
<scope>compile</scope>
|
<scope>compile</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.deltaspike.modules</groupId>
|
<groupId>org.apache.deltaspike.modules</groupId>
|
||||||
<artifactId>deltaspike-data-module-impl</artifactId>
|
<artifactId>deltaspike-data-module-impl</artifactId>
|
||||||
<version>1.7.1</version>
|
<version>${deltaspike.version}</version>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
@ -202,20 +207,20 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.mysema.querydsl</groupId>
|
<groupId>com.mysema.querydsl</groupId>
|
||||||
<artifactId>querydsl-apt</artifactId>
|
<artifactId>querydsl-apt</artifactId>
|
||||||
<version>3.7.4</version>
|
<version>${querydsl.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.mysema.querydsl</groupId>
|
<groupId>com.mysema.querydsl</groupId>
|
||||||
<artifactId>querydsl-jpa</artifactId>
|
<artifactId>querydsl-jpa</artifactId>
|
||||||
<version>3.7.4</version>
|
<version>${querydsl.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-log4j12</artifactId>
|
<artifactId>slf4j-log4j12</artifactId>
|
||||||
<version>1.6.1</version>
|
<version>${slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -226,7 +231,7 @@
|
|||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-war-plugin</artifactId>
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
<version>${version.war.plugin}</version>
|
<version>${war.plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
|
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
|
||||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
@ -235,7 +240,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>com.mysema.maven</groupId>
|
<groupId>com.mysema.maven</groupId>
|
||||||
<artifactId>apt-maven-plugin</artifactId>
|
<artifactId>apt-maven-plugin</artifactId>
|
||||||
<version>1.0.9</version>
|
<version>${apt-maven-plugin.version}</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
@ -253,7 +258,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.wildfly.plugins</groupId>
|
<groupId>org.wildfly.plugins</groupId>
|
||||||
<artifactId>wildfly-maven-plugin</artifactId>
|
<artifactId>wildfly-maven-plugin</artifactId>
|
||||||
<version>${version.wildfly.maven.plugin}</version>
|
<version>${wildfly.maven.plugin.version}</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
@ -272,7 +277,7 @@
|
|||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>${version.surefire.plugin}</version>
|
<version>${surefire.plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<skip>true</skip>
|
<skip>true</skip>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
@ -13,7 +13,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.3</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>7</source>
|
<source>7</source>
|
||||||
<target>7</target>
|
<target>7</target>
|
||||||
@ -26,33 +26,41 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>1.7.5</version>
|
<version>${slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>1.7.5</version>
|
<version>${slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>3.2.1</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sf.dozer</groupId>
|
<groupId>net.sf.dozer</groupId>
|
||||||
<artifactId>dozer</artifactId>
|
<artifactId>dozer</artifactId>
|
||||||
<version>5.5.1</version>
|
<version>${dozer.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.3</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<slf4j.version>1.7.21</slf4j.version>
|
||||||
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
<dozer.version>5.5.1</dozer.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
54
ejb/ejb-client/pom.xml
Executable file
54
ejb/ejb-client/pom.xml
Executable file
@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>ejb-client</artifactId>
|
||||||
|
<name>ejb-client</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.ejb</groupId>
|
||||||
|
<artifactId>ejb</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.wildfly</groupId>
|
||||||
|
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.baeldung.ejb</groupId>
|
||||||
|
<artifactId>ejb-remote</artifactId>
|
||||||
|
<type>ejb</type>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*EJBSetupTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
|
</properties>
|
||||||
|
</project>
|
70
ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java
Executable file
70
ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java
Executable file
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.ejb.client;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.naming.Context;
|
||||||
|
import javax.naming.InitialContext;
|
||||||
|
import javax.naming.NamingException;
|
||||||
|
|
||||||
|
import com.baeldung.ejb.tutorial.HelloWorld;
|
||||||
|
|
||||||
|
public class EJBClient {
|
||||||
|
|
||||||
|
public EJBClient() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private Context context = null;
|
||||||
|
|
||||||
|
public String getEJBRemoteMessage() {
|
||||||
|
EJBClient main = new EJBClient();
|
||||||
|
try {
|
||||||
|
// 1. Obtaining Context
|
||||||
|
main.createInitialContext();
|
||||||
|
// 2. Generate JNDI Lookup name and caste
|
||||||
|
HelloWorld helloWorld = main.lookup();
|
||||||
|
return helloWorld.getHelloWorld();
|
||||||
|
} catch (NamingException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return "";
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
main.closeContext();
|
||||||
|
} catch (NamingException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public HelloWorld lookup() throws NamingException {
|
||||||
|
|
||||||
|
// The app name is the EAR name of the deployed EJB without .ear suffix.
|
||||||
|
// Since we haven't deployed the application as a .ear, the app name for
|
||||||
|
// us will be an empty string
|
||||||
|
final String appName = "";
|
||||||
|
final String moduleName = "remote";
|
||||||
|
final String distinctName = "";
|
||||||
|
final String beanName = "HelloWorld";
|
||||||
|
final String viewClassName = HelloWorld.class.getName();
|
||||||
|
final String toLookup = String.format("ejb:%s/%s/%s/%s!%s", appName, moduleName, distinctName, beanName, viewClassName);
|
||||||
|
return (HelloWorld) context.lookup(toLookup);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createInitialContext() throws NamingException {
|
||||||
|
Properties prop = new Properties();
|
||||||
|
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
|
||||||
|
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
|
||||||
|
prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
|
||||||
|
prop.put(Context.SECURITY_PRINCIPAL, "testUser");
|
||||||
|
prop.put(Context.SECURITY_CREDENTIALS, "admin1234!");
|
||||||
|
prop.put("jboss.naming.client.ejb.context", false);
|
||||||
|
|
||||||
|
context = new InitialContext(prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void closeContext() throws NamingException {
|
||||||
|
if (context != null) {
|
||||||
|
context.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
8
ejb/ejb-client/src/main/resources/jboss-ejb-client.properties
Executable file
8
ejb/ejb-client/src/main/resources/jboss-ejb-client.properties
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
remote.connections=default
|
||||||
|
remote.connection.default.host=127.0.0.1
|
||||||
|
remote.connection.default.port=8080
|
||||||
|
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
|
||||||
|
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
|
||||||
|
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
|
||||||
|
remote.connection.default.username=testUser
|
||||||
|
remote.connection.default.password=admin1234!
|
16
ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java
Executable file
16
ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java
Executable file
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.ejb.setup.test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.baeldung.ejb.client.EJBClient;
|
||||||
|
import com.baeldung.ejb.tutorial.HelloWorldBean;
|
||||||
|
|
||||||
|
public class EJBSetupTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEJBClient() {
|
||||||
|
EJBClient ejbClient = new EJBClient();
|
||||||
|
HelloWorldBean bean = new HelloWorldBean();
|
||||||
|
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user