maven fix and small formatting work

This commit is contained in:
eugenp 2016-12-17 15:24:36 +02:00
parent b4ac6c6ec5
commit d66d9fb2c0
11 changed files with 449 additions and 481 deletions

View File

@ -1,307 +1,313 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId> <artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>core-java</name> <name>core-java</name>
<dependencies> <dependencies>
<!-- utils --> <!-- utils -->
<dependency> <dependency>
<groupId>net.sourceforge.collections</groupId> <groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId> <artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version> <version>${collections-generic.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</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>${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-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>1.8.7</version>
</dependency> </dependency>
<!-- web -->
<!-- marshalling --> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>commons-io</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>commons-io</artifactId>
<version>${jackson.version}</version> <version>${commons-io.version}</version>
</dependency> </dependency>
<!-- logging --> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.apache.commons</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>commons-math3</artifactId>
<version>${org.slf4j.version}</version> <version>${commons-math3.version}</version>
</dependency> </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>1.16.12</version>
<scope>provided</scope>
</dependency>
<!-- test scoped --> <dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.unix4j</groupId>
<artifactId>junit</artifactId> <artifactId>unix4j-command</artifactId>
<version>${junit.version}</version> <version>0.4</version>
<scope>test</scope> </dependency>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>com.googlecode.grep4j</groupId>
<artifactId>hamcrest-core</artifactId> <artifactId>grep4j</artifactId>
<version>${org.hamcrest.version}</version> <version>1.8.7</version>
<scope>test</scope> </dependency>
</dependency> <!-- web -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency> <!-- marshalling -->
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>testng</artifactId> <artifactId>jackson-databind</artifactId>
<version>${testng.version}</version> <version>${jackson.version}</version>
<scope>test</scope> </dependency>
</dependency>
<dependency> <!-- logging -->
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>org.slf4j</groupId>
<artifactId>commons-codec</artifactId> <artifactId>slf4j-api</artifactId>
<version>${commons-codec.version}</version> <version>${org.slf4j.version}</version>
</dependency> </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>1.16.12</version>
<scope>provided</scope>
</dependency>
</dependencies> <!-- test scoped -->
<build> <dependency>
<finalName>core-java</finalName> <groupId>org.hamcrest</groupId>
<resources> <artifactId>hamcrest-all</artifactId>
<resource> <version>1.3</version>
<directory>src/main/resources</directory> <scope>test</scope>
<filtering>true</filtering> </dependency>
</resource>
</resources>
<plugins> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<plugin> <dependency>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.hamcrest</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>hamcrest-core</artifactId>
<version>${maven-compiler-plugin.version}</version> <version>${org.hamcrest.version}</version>
<configuration> <scope>test</scope>
<source>1.8</source> </dependency>
<target>1.8</target> <dependency>
</configuration> <groupId>org.hamcrest</groupId>
</plugin> <artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<plugin> <dependency>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.assertj</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>assertj-core</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${assertj.version}</version>
<configuration> <scope>test</scope>
<excludes> </dependency>
<exclude>**/*IntegrationTest.java</exclude>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<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>
<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>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude> <exclude>**/*ManualTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>copy-dependencies</id> <id>copy-dependencies</id>
<phase>prepare-package</phase> <phase>prepare-package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory> <outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix> <classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>single</goal> <goal>single</goal>
</goals> </goals>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest> </manifest>
</archive> </archive>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs> </descriptorRefs>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<shadedArtifactAttached>true</shadedArtifactAttached> <shadedArtifactAttached>true</shadedArtifactAttached>
<transformers> <transformers>
<transformer <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> </transformer>
</transformer> </transformers>
</transformers> </configuration>
</configuration> </execution>
</execution> </executions>
</executions> </plugin>
</plugin>
<plugin> <plugin>
<groupId>com.jolira</groupId> <groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId> <artifactId>onejar-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<configuration> <configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild> <attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename> <filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration> </configuration>
<goals> <goals>
<goal>one-jar</goal> <goal>one-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>repackage</goal> <goal>repackage</goal>
</goals> </goals>
<configuration> <configuration>
<classifier>spring-boot</classifier> <classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins>
</build> </plugins>
<profiles> </build>
<profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
<build> <build>
@ -336,35 +342,35 @@
</profile> </profile>
</profiles> </profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>19.0</guava.version> <guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<commons-io.version>2.5</commons-io.version> <commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version> <mockito.version>1.10.19</mockito.version>
<testng.version>6.10</testng.version> <testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<!-- maven plugins --> <!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-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-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -5,18 +5,18 @@ import lombok.Data;
@Data @Data
public class City { public class City {
private int x; private int x;
private int y; private int y;
public City() { public City() {
this.x = (int) (Math.random() * 500); this.x = (int) (Math.random() * 500);
this.y = (int) (Math.random() * 500); this.y = (int) (Math.random() * 500);
} }
public double distanceToCity(City city) { public double distanceToCity(City city) {
int x = Math.abs(getX() - city.getX()); int x = Math.abs(getX() - city.getX());
int y = Math.abs(getY() - city.getY()); int y = Math.abs(getY() - city.getY());
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
} }
} }

View File

@ -2,40 +2,39 @@ package com.baeldung.algorithms;
public class SimulatedAnnealing { public class SimulatedAnnealing {
private static Travel travel = new Travel(10); 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++) { public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) {
if (t > 0.1) { System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate);
currentSolution.swapCities(); double t = startingTemperature;
double currentDistance = currentSolution.getDistance(); travel.generateInitialTravel();
if (currentDistance == 0) double bestDistance = travel.getDistance();
continue; System.out.println("Initial distance of travel: " + bestDistance);
if (currentDistance < bestDistance) { Travel bestSolution = travel;
bestDistance = currentDistance; Travel currentSolution = bestSolution;
} else if (Math.exp((currentDistance - bestDistance) / t) < Math.random()) {
currentSolution.revertSwap();
}
t *= coolingRate;
}
if (i % 100 == 0) {
System.out.println("Iteration #" + i);
}
}
return bestDistance;
}
public static void main(String[] args) { for (int i = 0; i < numberOfIterations; i++) {
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9)); if (t > 0.1) {
} currentSolution.swapCities();
double currentDistance = currentSolution.getDistance();
if (currentDistance == 0)
continue;
if (currentDistance < bestDistance) {
bestDistance = currentDistance;
} else if (Math.exp((currentDistance - bestDistance) / t) < Math.random()) {
currentSolution.revertSwap();
}
t *= coolingRate;
}
if (i % 100 == 0) {
System.out.println("Iteration #" + i);
}
}
return bestDistance;
}
public static void main(String[] args) {
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9));
}
} }

View File

@ -8,53 +8,53 @@ import lombok.Data;
@Data @Data
public class Travel { public class Travel {
private ArrayList<City> travel = new ArrayList<>(); private ArrayList<City> travel = new ArrayList<>();
private ArrayList<City> previousTravel = new ArrayList<>(); private ArrayList<City> previousTravel = new ArrayList<>();
public Travel(int numberOfCities) { public Travel(int numberOfCities) {
for (int i = 0; i < numberOfCities; i++) { for (int i = 0; i < numberOfCities; i++) {
travel.add(new City()); travel.add(new City());
} }
} }
public void generateInitialTravel() { public void generateInitialTravel() {
if (travel.isEmpty()) if (travel.isEmpty())
new Travel(10); new Travel(10);
Collections.shuffle(travel); Collections.shuffle(travel);
} }
public void swapCities() { public void swapCities() {
int a = generateRandomIndex(); int a = generateRandomIndex();
int b = generateRandomIndex(); int b = generateRandomIndex();
previousTravel = travel; previousTravel = travel;
travel.set(a, travel.get(b)); travel.set(a, travel.get(b));
} }
public void revertSwap() { public void revertSwap() {
travel = previousTravel; travel = previousTravel;
} }
private int generateRandomIndex() { private int generateRandomIndex() {
return (int) (Math.random() * travel.size()); return (int) (Math.random() * travel.size());
} }
public City getCity(int index) { public City getCity(int index) {
return travel.get(index); return travel.get(index);
} }
public int getDistance() { public int getDistance() {
int distance = 0; int distance = 0;
for (int index = 0; index < travel.size(); index++) { for (int index = 0; index < travel.size(); index++) {
City starting = getCity(index); City starting = getCity(index);
City destination; City destination;
if (index + 1 < travel.size()) { if (index + 1 < travel.size()) {
destination = getCity(index + 1); destination = getCity(index + 1);
} else { } else {
destination = getCity(0); destination = getCity(0);
} }
distance += starting.distanceToCity(destination); distance += starting.distanceToCity(destination);
} }
return distance; return distance;
} }
} }

View File

@ -5,9 +5,9 @@ import org.junit.Test;
public class SimulatedAnnealingTest { public class SimulatedAnnealingTest {
@Test @Test
public void testSimulateAnnealing() { public void testSimulateAnnealing() {
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0); Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
} }
} }

View File

@ -22,7 +22,6 @@ public class EncoderDecoderUnitTest {
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; 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 static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
private String encodeValue(String value) { private String encodeValue(String value) {
String encoded = null; String encoded = null;
try { try {
@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest {
requestParams.put("key2", "value@!$2"); requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3"); requestParams.put("key3", "value%3");
String encodedURL = requestParams.keySet().stream() String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com?", ""));
Assert.assertThat(testUrl, is(encodedURL)); Assert.assertThat(testUrl, is(encodedURL));
} }
@ -103,12 +100,9 @@ public class EncoderDecoderUnitTest {
String path = "path+1"; String path = "path+1";
String encodedURL = requestParams.keySet().stream() String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
Assert.assertThat(testUrlWithPath, is(encodedURL)); Assert.assertThat(testUrlWithPath, is(encodedURL));
} }
} }

View File

@ -17,9 +17,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() { public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.parallelStream() final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
.filter(Objects::nonNull)
.collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3)); assertThat(listWithoutNulls, hasSize(3));
} }
@ -27,9 +25,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() { public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.stream() final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
.filter(Objects::nonNull)
.collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3)); assertThat(listWithoutNulls, hasSize(3));
} }
@ -45,9 +41,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() { public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3); final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream() final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream().distinct().collect(Collectors.toList());
.distinct()
.collect(Collectors.toList());
assertThat(listWithoutDuplicates, hasSize(3)); assertThat(listWithoutDuplicates, hasSize(3));
} }

View File

@ -18,13 +18,13 @@ public class JavaFileSizeUnitTest {
@Before @Before
public void init() { public void init() {
final String separator = File.separator; final String separator = File.separator;
filePath = String.join(separator, new String[] {"src", "test", "resources", "testFolder", "sample_file_1.in"}); filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
} }
@Test @Test
public void whenGetFileSize_thenCorrect() { public void whenGetFileSize_thenCorrect() {
final File file = new File(filePath); final File file = new File(filePath);
final long size = getFileSize(file); final long size = getFileSize(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size); assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
@ -34,16 +34,16 @@ public class JavaFileSizeUnitTest {
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException { public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
final Path path = Paths.get(this.filePath); final Path path = Paths.get(this.filePath);
final FileChannel fileChannel = FileChannel.open(path); final FileChannel fileChannel = FileChannel.open(path);
final long fileSize = fileChannel.size(); final long fileSize = fileChannel.size();
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize); assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
} }
@Test @Test
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() { public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
final File file = new File(filePath); final File file = new File(filePath);
final long size = FileUtils.sizeOf(file); final long size = FileUtils.sizeOf(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size); assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
@ -52,9 +52,9 @@ public class JavaFileSizeUnitTest {
@Test @Test
public void whenGetReadableFileSize_thenCorrect() { public void whenGetReadableFileSize_thenCorrect() {
final File file = new File(filePath); final File file = new File(filePath);
final long size = getFileSize(file); final long size = getFileSize(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size)); assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
} }

View File

@ -93,6 +93,7 @@ public class OptionalTest {
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
assertFalse(is2017); assertFalse(is2017);
} }
@Test @Test
public void whenFiltersWithoutOptional_thenCorrect() { public void whenFiltersWithoutOptional_thenCorrect() {
assertTrue(priceIsInRange1(new Modem(10.0))); assertTrue(priceIsInRange1(new Modem(10.0)));
@ -121,12 +122,9 @@ public class OptionalTest {
} }
public boolean priceIsInRange2(Modem modem2) { public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2) return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
} }
// Transforming Value With map() // Transforming Value With map()
@Test @Test
public void givenOptional_whenMapWorks_thenCorrect() { public void givenOptional_whenMapWorks_thenCorrect() {

View File

@ -13,46 +13,43 @@ import static org.unix4j.unix.Grep.*;
import static org.unix4j.unix.cut.CutOption.*; import static org.unix4j.unix.cut.CutOption.*;
public class GrepWithUnix4JTest { public class GrepWithUnix4JTest {
private File fileToGrep; private File fileToGrep;
@Before @Before
public void init() { public void init() {
final String separator = File.separator; final String separator = File.separator;
final String filePath = String.join(separator, new String[] {"src", "test", "resources", "dictionary.in"}); final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
fileToGrep = new File(filePath); 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 @Test
public void whenInverseGrepWithSimpleString_thenCorrect() { public void whenGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 178687; int expectedLineCount = 4;
//grep -v "NINETEEN" dictionary.txt
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).
toLineList();
assertEquals(expectedLineCount, lines.size());
}
// grep "NINETEEN" dictionary.txt
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
@Test assertEquals(expectedLineCount, lines.size());
public void whenGrepWithRegex_thenCorrect() { }
int expectedLineCount = 151;
@Test
//grep -c ".*?NINE.*?" dictionary.txt public void whenInverseGrepWithSimpleString_thenCorrect() {
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep). int expectedLineCount = 178687;
cut(fields, ":", 1).toStringResult();
// grep -v "NINETEEN" dictionary.txt
assertEquals(expectedLineCount, Integer.parseInt(patternCount)); 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));
}
} }

View File

@ -15,8 +15,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoArrays_thenJoined() { public void whenJoiningTwoArrays_thenJoined() {
String[] animals1 = new String[] { "Dog", "Cat" }; String[] animals1 = new String[] { "Dog", "Cat" };
String[] animals2 = new String[] { "Bird", "Cow" }; String[] animals2 = new String[] { "Bird", "Cow" };
String[] result = Stream.concat( String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
} }
@ -25,9 +24,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoCollections_thenJoined() { public void whenJoiningTwoCollections_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat"); Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose"); Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat( Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
collection1.stream(), collection2.stream())
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
} }
@ -36,10 +33,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoCollectionsWithFilter_thenJoined() { public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat"); Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose"); Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat( Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList());
collection1.stream(), collection2.stream())
.filter(e -> e.length() == 3)
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));
} }
@ -67,9 +61,7 @@ public class JoinSplitCollectionsUnitTest {
animals.put(2, "Cat"); animals.put(2, "Cat");
animals.put(3, "Cow"); animals.put(3, "Cow");
String result = animals.entrySet().stream() String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining(", "));
assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow"); assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");
} }
@ -80,10 +72,7 @@ public class JoinSplitCollectionsUnitTest {
nested.add(Arrays.asList("Dog", "Cat")); nested.add(Arrays.asList("Dog", "Cat"));
nested.add(Arrays.asList("Cow", "Pig")); nested.add(Arrays.asList("Cow", "Pig"));
String result = nested.stream().map( String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
nextList -> nextList.stream()
.collect(Collectors.joining("-")))
.collect(Collectors.joining("; "));
assertEquals(result, "Dog-Cat; Cow-Pig"); assertEquals(result, "Dog-Cat; Cow-Pig");
} }
@ -91,17 +80,14 @@ public class JoinSplitCollectionsUnitTest {
@Test @Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() { public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose"); Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
String result = animals.stream() String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
.filter(Objects::nonNull)
.collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Moose"); assertEquals(result, "Dog, Cat, Moose");
} }
@Test @Test
public void whenSplitCollectionHalf_thenConverted() { public void whenSplitCollectionHalf_thenConverted() {
Collection<String> animals = Arrays.asList( Collection<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
"Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>(); Collection<String> result1 = new ArrayList<>();
Collection<String> result2 = new ArrayList<>(); Collection<String> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger(); AtomicInteger count = new AtomicInteger();
@ -122,9 +108,8 @@ public class JoinSplitCollectionsUnitTest {
@Test @Test
public void whenSplitArrayByWordLength_thenConverted() { public void whenSplitArrayByWordLength_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose"}; String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" };
Map<Integer, List<String>> result = Arrays.stream(animals) Map<Integer, List<String>> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length));
.collect(Collectors.groupingBy(String::length));
assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig"))); assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));
assertTrue(result.get(4).equals(Arrays.asList("Bird"))); assertTrue(result.get(4).equals(Arrays.asList("Bird")));
@ -151,9 +136,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenConvertStringToMap_thenConverted() { public void whenConvertStringToMap_thenConverted() {
String animals = "1 = Dog, 2 = Cat, 3 = Bird"; String animals = "1 = Dog, 2 = Cat, 3 = Bird";
Map<Integer, String> result = Arrays.stream( Map<Integer, String> result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
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(1), "Dog");
assertEquals(result.get(2), "Cat"); assertEquals(result.get(2), "Cat");
@ -164,10 +147,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() { public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
String animals = "Dog. , Cat, Bird. Cow"; String animals = "Dog. , Cat, Bird. Cow";
Collection<String> result = Arrays.stream(animals.split("[,|.]")) Collection<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
.map(String::trim)
.filter(next -> !next.isEmpty())
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
} }