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"
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>${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>${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>
<!-- 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>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</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>1.16.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>0.4</version>
</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>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>1.8.7</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!-- logging -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</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>1.16.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- test scoped -->
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<plugins>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<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>
<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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<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>**/*ManualTest.java</exclude>
</excludes>
</configuration>
</plugin>
</excludes>
</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>
</plugins>
<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>
</build>
<profiles>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
@ -336,35 +342,35 @@
</profile>
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</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.21</org.slf4j.version>
<logback.version>1.1.7</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>
<!-- 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>
<!-- 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>
<!-- 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>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.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>
</properties>
</properties>
</project>

View File

@ -5,18 +5,18 @@ import lombok.Data;
@Data
public class City {
private int x;
private int y;
private int x;
private int y;
public City() {
this.x = (int) (Math.random() * 500);
this.y = (int) (Math.random() * 500);
}
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));
}
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));
}
}

View File

@ -2,40 +2,39 @@ package com.baeldung.algorithms;
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;
private static Travel travel = new Travel(10);
for (int i = 0; i < numberOfIterations; i++) {
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 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;
public static void main(String[] args) {
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9));
}
for (int i = 0; i < numberOfIterations; i++) {
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
public class Travel {
private ArrayList<City> travel = new ArrayList<>();
private ArrayList<City> previousTravel = new ArrayList<>();
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 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 generateInitialTravel() {
if (travel.isEmpty())
new Travel(10);
Collections.shuffle(travel);
}
public void swapCities() {
int a = generateRandomIndex();
int b = generateRandomIndex();
previousTravel = travel;
travel.set(a, travel.get(b));
}
public void swapCities() {
int a = generateRandomIndex();
int b = generateRandomIndex();
previousTravel = travel;
travel.set(a, travel.get(b));
}
public void revertSwap() {
travel = previousTravel;
}
public void revertSwap() {
travel = previousTravel;
}
private int generateRandomIndex() {
return (int) (Math.random() * travel.size());
}
private int generateRandomIndex() {
return (int) (Math.random() * travel.size());
}
public City getCity(int index) {
return travel.get(index);
}
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;
}
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;
}
}

View File

@ -5,9 +5,9 @@ import org.junit.Test;
public class SimulatedAnnealingTest {
@Test
public void testSimulateAnnealing() {
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
}
@Test
public void testSimulateAnnealing() {
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 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;
try {
@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest {
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String encodedURL = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com?", ""));
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
Assert.assertThat(testUrl, is(encodedURL));
}
@ -103,12 +100,9 @@ public class EncoderDecoderUnitTest {
String path = "path+1";
String encodedURL = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
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));
}
}

View File

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

View File

@ -18,13 +18,13 @@ public class JavaFileSizeUnitTest {
@Before
public void init() {
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
public void whenGetFileSize_thenCorrect() {
final File file = new File(filePath);
final long size = getFileSize(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
@ -34,16 +34,16 @@ public class JavaFileSizeUnitTest {
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);
@ -52,9 +52,9 @@ public class JavaFileSizeUnitTest {
@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));
}

View File

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

View File

@ -13,46 +13,43 @@ import static org.unix4j.unix.Grep.*;
import static org.unix4j.unix.cut.CutOption.*;
public class GrepWithUnix4JTest {
private File fileToGrep;
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"});
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 whenGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 4;
// grep "NINETEEN" dictionary.txt
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
@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));
}
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));
}
}

View File

@ -15,8 +15,7 @@ public class JoinSplitCollectionsUnitTest {
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);
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@ -25,9 +24,7 @@ public class JoinSplitCollectionsUnitTest {
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());
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
}
@ -36,10 +33,7 @@ public class JoinSplitCollectionsUnitTest {
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());
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")));
}
@ -67,9 +61,7 @@ public class JoinSplitCollectionsUnitTest {
animals.put(2, "Cat");
animals.put(3, "Cow");
String result = animals.entrySet().stream()
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining(", "));
String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
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("Cow", "Pig"));
String result = nested.stream().map(
nextList -> nextList.stream()
.collect(Collectors.joining("-")))
.collect(Collectors.joining("; "));
String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
assertEquals(result, "Dog-Cat; Cow-Pig");
}
@ -91,17 +80,14 @@ public class JoinSplitCollectionsUnitTest {
@Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
String result = animals.stream()
.filter(Objects::nonNull)
.collect(Collectors.joining(", "));
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> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>();
Collection<String> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
@ -122,9 +108,8 @@ public class JoinSplitCollectionsUnitTest {
@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));
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")));
@ -151,9 +136,7 @@ public class JoinSplitCollectionsUnitTest {
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]));
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");
@ -164,10 +147,7 @@ public class JoinSplitCollectionsUnitTest {
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());
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")));
}