Merge branch 'master' into pr/949-yasser-handler-mapping
This commit is contained in:
commit
0e04878e1e
|
@ -15,7 +15,7 @@
|
|||
|
||||
<properties>
|
||||
<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>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -13,6 +13,11 @@
|
|||
|
||||
<artifactId>annotation-user</artifactId>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
|
@ -24,7 +29,7 @@
|
|||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
@ -37,7 +42,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
## Relevant Articles:
|
||||
- [Introduction to Apache CXF Aegis Data Binding](http://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
|
@ -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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-introduction</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -24,7 +27,7 @@
|
|||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<version>${surefire.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
|
@ -33,6 +36,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
|
|
|
@ -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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-jaxrs-implementation</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<cxf.version>3.1.7</cxf.version>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<httpclient.version>4.5.2</httpclient.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -26,7 +29,7 @@
|
|||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<version>${surefire.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
|
@ -35,6 +38,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
|
|
|
@ -33,7 +33,7 @@
|
|||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -41,7 +41,7 @@
|
|||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
|
@ -66,7 +66,7 @@
|
|||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>1.4.19</version>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>tomcat8x</containerId>
|
||||
|
@ -121,9 +121,13 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<cxf.version>3.1.8</cxf.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>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -5,19 +5,29 @@
|
|||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
<module>cxf-spring</module>
|
||||
<module>cxf-jaxrs-implementation</module>
|
||||
<module>cxf-aegis</module>
|
||||
</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>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
|
@ -25,7 +35,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
@ -34,7 +44,7 @@
|
|||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.5.0</version>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
|
|
|
@ -67,7 +67,7 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>fop</artifactId>
|
||||
<version>1.1</version>
|
||||
<version>${fop.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.avalon.framework</groupId>
|
||||
|
@ -83,18 +83,18 @@
|
|||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-api</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>dbdoclet</artifactId>
|
||||
<version>8.0.2</version>
|
||||
<version>${dbdoclet.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -108,7 +108,7 @@
|
|||
<dependency>
|
||||
<groupId>net.sf.jtidy</groupId>
|
||||
<artifactId>jtidy</artifactId>
|
||||
<version>r938</version>
|
||||
<version>${jtidy.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
@ -187,40 +187,22 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.7.2</jackson.version>
|
||||
|
||||
<fop.version>1.1</fop.version>
|
||||
<avalon-framework.version>4.3</avalon-framework.version>
|
||||
<dbdoclet.version>8.0.2</dbdoclet.version>
|
||||
<jtidy.version>r938</jtidy.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.9</org.slf4j.version>
|
||||
<logback.version>1.1.2</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>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.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-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-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>
|
||||
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
*.docx
|
|
@ -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,91 @@
|
|||
package com.baeldung.poi.word;
|
||||
|
||||
import org.apache.poi.util.Units;
|
||||
import org.apache.poi.xwpf.usermodel.*;
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 782 B |
|
@ -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.
|
|
@ -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.
|
|
@ -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.
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -98,13 +98,14 @@
|
|||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- <plugin>
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.10</version>
|
||||
|
@ -113,18 +114,18 @@
|
|||
<useSystemClassLoader>true</useSystemClassLoader>
|
||||
<forkMode>always</forkMode>
|
||||
</configuration>
|
||||
</plugin> -->
|
||||
</plugin>
|
||||
-->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>1.8</source.version>
|
||||
<aspectj.version>1.6.11</aspectj.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<aspectj.version>1.8.9</aspectj.version>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.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>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -4,10 +4,10 @@ public class Account {
|
|||
int balance = 20;
|
||||
|
||||
public boolean withdraw(int amount) {
|
||||
if (balance - amount > 0) {
|
||||
balance = balance - amount;
|
||||
return true;
|
||||
} else
|
||||
if (balance < amount) {
|
||||
return false;
|
||||
}
|
||||
balance = balance - amount;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,12 +16,11 @@ public aspect AccountAspect {
|
|||
}
|
||||
|
||||
boolean around(int amount, Account account) : callWithDraw(amount, account) {
|
||||
if (account.balance - amount >= MIN_BALANCE)
|
||||
return proceed(amount, account);
|
||||
else {
|
||||
if (account.balance < amount) {
|
||||
logger.info("Withdrawal Rejected!");
|
||||
return false;
|
||||
}
|
||||
return proceed(amount, account);
|
||||
}
|
||||
|
||||
after(int amount, Account balance) : callWithDraw(amount, balance) {
|
||||
|
|
|
@ -23,13 +23,13 @@
|
|||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
@ -40,7 +40,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
@ -51,6 +51,11 @@
|
|||
|
||||
<properties>
|
||||
<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>
|
||||
|
||||
</project>
|
|
@ -2,15 +2,16 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>autovalue-tutorial</artifactId>
|
||||
<artifactId>autovalue</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>AutoValue</name>
|
||||
<name>autovalue</name>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>7</source>
|
||||
<target>7</target>
|
||||
|
@ -19,19 +20,26 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.auto.value</groupId>
|
||||
<artifactId>auto-value</artifactId>
|
||||
<version>1.2</version>
|
||||
<version>${auto-value.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.3</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</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>
|
||||
|
|
|
@ -4,7 +4,7 @@ import static org.junit.Assert.*;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MoneyTest {
|
||||
public class MoneyUnitTest {
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
|
@ -0,0 +1,44 @@
|
|||
<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>aws-lambda</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>aws-lambda</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.5</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>2.3</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
|
||||
public class LambdaMethodHandler {
|
||||
public String handleRequest(String input, Context context) {
|
||||
context.getLogger().log("Input: " + input);
|
||||
return "Hello World - " + input;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
|
||||
public class LambdaRequestHandler implements RequestHandler<String, String> {
|
||||
public String handleRequest(String input, Context context) {
|
||||
context.getLogger().log("Input: " + input);
|
||||
return "Hello World - " + input;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class LambdaRequestStreamHandler implements RequestStreamHandler {
|
||||
|
||||
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
|
||||
String input = IOUtils.toString(inputStream, "UTF-8");
|
||||
outputStream.write(("Hello World - " + input).getBytes());
|
||||
}
|
||||
}
|
11
cdi/pom.xml
11
cdi/pom.xml
|
@ -22,18 +22,18 @@
|
|||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>1.8.9</version>
|
||||
<version>${aspectjweaver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>2.3.5.Final</version>
|
||||
<version>${weld-se-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -97,7 +97,10 @@
|
|||
</profile>
|
||||
</profiles>
|
||||
<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>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -3,3 +3,6 @@
|
|||
## Core Java 9 Examples
|
||||
|
||||
[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>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||
|
|
|
@ -14,3 +14,5 @@
|
|||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
/bin/
|
||||
/temp
|
||||
|
|
|
@ -38,3 +38,11 @@
|
|||
- [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 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)
|
||||
|
|
|
@ -1,291 +1,314 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java</name>
|
||||
<name>core-java</name>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>4.01</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>3.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<!-- logging -->
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>${testng.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>${testng.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<finalName>core-java</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</dependencies>
|
||||
|
||||
<plugins>
|
||||
<build>
|
||||
<finalName>core-java</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<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>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<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>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
|
@ -320,46 +343,38 @@
|
|||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.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>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<testng.version>6.10</testng.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<testng.version>6.8</testng.version>
|
||||
<assertj.version>3.5.1</assertj.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.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>
|
||||
|
||||
</project>
|
|
@ -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();
|
||||
|
||||
}
|
||||
}
|
|
@ -1,5 +1,12 @@
|
|||
package com.baeldung.generics;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Building {
|
||||
public void paint() {
|
||||
}
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
|
||||
|
||||
public void paint() {
|
||||
LOGGER.info("Painting Building");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,30 +1,31 @@
|
|||
import java.util.ArrayList;
|
||||
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) {
|
||||
List<T> list = new ArrayList<>();
|
||||
Arrays.stream(a).forEach(list::add);
|
||||
return list;
|
||||
}
|
||||
// definition of a generic method
|
||||
public static <T> List<T> fromArrayToList(T[] a) {
|
||||
return Arrays.stream(a).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) {
|
||||
List<T> list = new ArrayList<>();
|
||||
Arrays.stream(a).forEach(list::add);
|
||||
return list;
|
||||
}
|
||||
// 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 with a wild card, this method can be used
|
||||
// with a list of any subtype of Building
|
||||
public static boolean paintAllBuildings(List<? extends Building> buildings) {
|
||||
for (Building building : buildings) {
|
||||
building.paint();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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,4 +0,0 @@
|
|||
|
||||
public class SubBuilding extends Building {
|
||||
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
|
||||
import com.google.common.hash.Hashing;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
@ -11,17 +10,14 @@ import java.security.NoSuchAlgorithmException;
|
|||
|
||||
public class SHA256Hashing {
|
||||
|
||||
public static String HashWithJavaMessageDigest(final String originalString)
|
||||
throws NoSuchAlgorithmException {
|
||||
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final byte[] encodedhash = digest.digest(
|
||||
originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String HashWithGuava(final String originalString) {
|
||||
final String sha256hex = Hashing.sha256().hashString(
|
||||
originalString, StandardCharsets.UTF_8).toString();
|
||||
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
|
||||
return sha256hex;
|
||||
}
|
||||
|
||||
|
@ -30,11 +26,9 @@ public class SHA256Hashing {
|
|||
return sha256hex;
|
||||
}
|
||||
|
||||
public static String HashWithBouncyCastle(final String originalString)
|
||||
throws NoSuchAlgorithmException {
|
||||
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final byte[] hash = digest.digest(
|
||||
originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final String sha256hex = new String(Hex.encode(hash));
|
||||
return sha256hex;
|
||||
}
|
||||
|
@ -43,7 +37,8 @@ public class SHA256Hashing {
|
|||
StringBuffer hexString = new StringBuffer();
|
||||
for (int i = 0; i < hash.length; 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);
|
||||
}
|
||||
return hexString.toString();
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.jmx;
|
||||
|
||||
public class Game implements GameMBean {
|
||||
|
||||
private String playerName;
|
||||
|
||||
@Override
|
||||
public void playFootball(String clubName) {
|
||||
System.out.println(this.playerName + " playing football for " + clubName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerName() {
|
||||
System.out.println("Return playerName " + this.playerName);
|
||||
return playerName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerName(String playerName) {
|
||||
System.out.println("Set playerName to value " + playerName);
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.jmx;
|
||||
|
||||
public interface GameMBean {
|
||||
|
||||
public void playFootball(String clubName);
|
||||
|
||||
public String getPlayerName();
|
||||
|
||||
public void setPlayerName(String playerName);
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.jmx;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import javax.management.InstanceAlreadyExistsException;
|
||||
import javax.management.MBeanRegistrationException;
|
||||
import javax.management.MBeanServer;
|
||||
import javax.management.MalformedObjectNameException;
|
||||
import javax.management.NotCompliantMBeanException;
|
||||
import javax.management.ObjectName;
|
||||
|
||||
public class JMXTutorialMainlauncher {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
System.out.println("This is basic JMX tutorial");
|
||||
ObjectName objectName = null;
|
||||
try {
|
||||
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
|
||||
} catch (MalformedObjectNameException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
|
||||
Game gameObj = new Game();
|
||||
try {
|
||||
server.registerMBean(gameObj, objectName);
|
||||
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("Registration for Game mbean with the platform server is successfull");
|
||||
System.out.println("Please open jconsole to access Game mbean");
|
||||
while (true) {
|
||||
// to ensure application does not terminate
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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)
|
|
@ -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) {
|
||||
|
||||
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||
final ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||
|
||||
executorService.submit(() -> {
|
||||
executorService.submit((Runnable) () -> {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
|
@ -42,96 +42,136 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toList());
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toList());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
final Set<String> result = givenList
|
||||
.stream()
|
||||
.collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||
givenList
|
||||
.stream()
|
||||
.collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList.stream().collect(joining());
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining());
|
||||
|
||||
assertThat(result).isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" "));
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" "));
|
||||
|
||||
assertThat(result).isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||
final Map<Boolean, List<String>> result = givenList
|
||||
.stream()
|
||||
.collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
assertThat(result)
|
||||
.containsKeys(true, false)
|
||||
.satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList.stream().collect(counting());
|
||||
final Long result = givenList
|
||||
.stream()
|
||||
.collect(counting());
|
||||
|
||||
assertThat(result).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||
final DoubleSummaryStatistics result = givenList
|
||||
.stream()
|
||||
.collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage()).isEqualTo(2);
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
|
@ -142,37 +182,55 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList.stream().collect(summingDouble(String::length));
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.filter(i -> true)
|
||||
.collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||
final Optional<String> result = givenList
|
||||
.stream()
|
||||
.collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result).isPresent().hasValue("dd");
|
||||
assertThat(result)
|
||||
.isPresent()
|
||||
.hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||
final Map<Integer, Set<String>> result = givenList
|
||||
.stream()
|
||||
.collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||
assertThat(result)
|
||||
.containsEntry(1, newHashSet("a"))
|
||||
.containsEntry(2, newHashSet("bb", "dd"))
|
||||
.containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||
final ImmutableSet<String> result = givenList
|
||||
.stream()
|
||||
.collect(toImmutableSet());
|
||||
|
||||
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||
assertThat(result)
|
||||
.isInstanceOf(ImmutableSet.class)
|
||||
.contains("a", "bb", "ccc", "dd");
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -7,20 +7,20 @@ import org.slf4j.Logger;
|
|||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
public class EncoderDecoderUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
||||
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) {
|
||||
String encoded = null;
|
||||
|
@ -46,9 +46,9 @@ public class EncoderDecoderUnitTest {
|
|||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
||||
URL url = new URL(testUrl);
|
||||
|
||||
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
|
||||
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
|
||||
Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
||||
Assert.assertThat(url.getProtocol(), is("http"));
|
||||
Assert.assertThat(url.getHost(), is("www.baeldung.com"));
|
||||
Assert.assertThat(url.getQuery(), is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -60,7 +60,7 @@ public class EncoderDecoderUnitTest {
|
|||
|
||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||
|
||||
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
||||
Assert.assertThat(testUrl, is(encodedURL));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -74,4 +74,35 @@ public class EncoderDecoderUnitTest {
|
|||
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||
}
|
||||
|
||||
private String encodePath(String path) {
|
||||
try {
|
||||
path = new URI(null, null, path, null).getPath();
|
||||
} catch (URISyntaxException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
|
||||
URI uri = new URI(null, null, "/Path 1/Path+2", null);
|
||||
|
||||
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
|
||||
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;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
@ -14,12 +15,6 @@ import java.nio.file.Path;
|
|||
import java.nio.file.Paths;
|
||||
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 {
|
||||
|
||||
@Test
|
||||
|
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
|
|||
|
||||
@Test
|
||||
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();
|
||||
|
||||
|
|
|
@ -1,55 +1,69 @@
|
|||
import static org.hamcrest.CoreMatchers.hasItems;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
package com.baeldung.generics;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
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);
|
||||
// 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));
|
||||
}
|
||||
assertThat(list, hasItems(intArray));
|
||||
}
|
||||
|
||||
// testing the generic method with String
|
||||
@Test
|
||||
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
|
||||
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
|
||||
List<String> list = Generics.fromArrayToList(stringArray);
|
||||
// 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"));
|
||||
}
|
||||
|
||||
assertThat(list, hasItems(stringArray));
|
||||
}
|
||||
// testing the generic method with String
|
||||
@Test
|
||||
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
|
||||
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
|
||||
List<String> list = Generics.fromArrayToList(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(stringArray));
|
||||
}
|
||||
|
||||
assertThat(list, hasItems(intArray));
|
||||
}
|
||||
// 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);
|
||||
|
||||
// testing paintAllBuildings method with a subtype of Building, the method
|
||||
// will work with all subtypes of Building
|
||||
@Test
|
||||
public void givenSubTypeOfAwildCardBoundedGenericMethod() {
|
||||
assertThat(list, hasItems(intArray));
|
||||
}
|
||||
|
||||
List<SubBuilding> subBuildingsList = new ArrayList<>();
|
||||
subBuildingsList.add(new SubBuilding());
|
||||
subBuildingsList.add(new SubBuilding());
|
||||
// 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());
|
||||
|
||||
boolean result = Generics.paintAllBuildings(subBuildingsList);
|
||||
assertTrue(result);
|
||||
|
||||
}
|
||||
// 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.*;
|
||||
|
||||
|
||||
public class SHA256HashingTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue =
|
||||
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||
|
||||
@Test
|
||||
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;
|
||||
Month afterConvCalendarMonth = Month.DECEMBER;
|
||||
int afterConvCalendarYear = 2007;
|
||||
LocalDateTime afterConvDate
|
||||
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
|
||||
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
||||
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
||||
|
|
|
@ -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,64 +1,72 @@
|
|||
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.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 {
|
||||
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
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get(HOME);
|
||||
Path p2 = Paths.get(HOME);
|
||||
Path p1 = Paths.get(TEMP_DIR);
|
||||
Path p2 = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
|
@ -67,7 +75,7 @@ public class FileTest {
|
|||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(HOME + "/" + fileName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -77,7 +85,7 @@ public class FileTest {
|
|||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -89,7 +97,7 @@ public class FileTest {
|
|||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
||||
|
@ -97,7 +105,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
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");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
|
@ -110,7 +118,7 @@ public class FileTest {
|
|||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -119,7 +127,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -136,7 +144,7 @@ public class FileTest {
|
|||
// delete file
|
||||
@Test
|
||||
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));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -147,7 +155,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
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);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
|
@ -160,7 +168,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
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));
|
||||
Files.delete(p);
|
||||
|
||||
|
@ -168,7 +176,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
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));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
|
@ -177,8 +185,8 @@ public class FileTest {
|
|||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -193,8 +201,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -210,8 +218,8 @@ public class FileTest {
|
|||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -227,8 +235,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
|
|
@ -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 java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
@ -16,7 +17,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||
@Test
|
||||
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
|
||||
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));
|
||||
}
|
||||
|
@ -24,7 +25,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||
@Test
|
||||
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
|
||||
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));
|
||||
}
|
||||
|
@ -32,7 +33,7 @@ public class Java8CollectionCleanupUnitTest {
|
|||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||
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));
|
||||
}
|
||||
|
|
|
@ -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.Scanner;
|
||||
|
||||
public class JavaTryWithResourcesUnitTest {
|
||||
public class JavaTryWithResourcesLongRunningUnitTest {
|
||||
|
||||
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
||||
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;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
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;
|
||||
|
@ -9,17 +11,28 @@ import java.nio.file.FileSystemException;
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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
|
||||
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();
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -27,48 +40,48 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
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
|
||||
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
|
||||
|
||||
@Test
|
||||
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();
|
||||
final File destDir = new File("src/test/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/");
|
||||
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) {
|
||||
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
|
||||
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get("src/main/resources/");
|
||||
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||
|
||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
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();
|
||||
final File destDir = new File("src/main/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/temp");
|
||||
final File targetFile = new File(destDir, fileToMove.getName());
|
||||
com.google.common.io.Files.createParentDirs(targetFile);
|
||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||
|
@ -76,23 +89,24 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
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
|
||||
|
||||
@Test
|
||||
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();
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -100,17 +114,17 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -118,9 +132,9 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
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()));
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1 @@
|
|||
baeldung.com
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue