Resolved merge conflicts

This commit is contained in:
iaforek 2017-05-11 11:00:16 +01:00
commit 1e8794140f
2492 changed files with 267395 additions and 3729 deletions

2
.gitignore vendored
View File

@ -31,3 +31,5 @@ spring-openid/src/main/resources/application.properties
.recommenders/ .recommenders/
/spring-hibernate4/nbproject/ /spring-hibernate4/nbproject/
spring-security-openid/src/main/resources/application.properties spring-security-openid/src/main/resources/application.properties
spring-all/*.log

View File

@ -1,6 +1,6 @@
language: java language: java
install: travis_wait 60 mvn -q test install: travis_wait 60 mvn -q test -fae
before_script: before_script:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc

View File

@ -6,6 +6,13 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>

View File

@ -8,6 +8,12 @@
<name>Twitter4J</name> <name>Twitter4J</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

View File

@ -5,3 +5,4 @@
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization) - [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java) - [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)

View File

@ -13,6 +13,12 @@
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
</properties> </properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
@ -39,7 +45,6 @@
</dependencies> </dependencies>
<build> <build>
<defaultGoal>install</defaultGoal>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
@ -56,6 +61,17 @@
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version> <version>${exec-maven-plugin.version}</version>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
</build> </build>

View File

@ -0,0 +1,22 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
public class AntColonyOptimizationLongRunningUnitTest {
@Test
public void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
}
@Test
public void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.solve());
}
}

View File

@ -1,22 +0,0 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
public class AntColonyOptimizationTest {
@Test
public void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
}
@Test
public void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.solve());
}
}

View File

@ -0,0 +1,16 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmLongRunningUnitTest {
@Test
public void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}

View File

@ -1,16 +0,0 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmUnitTest {
@Test
public void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}

View File

@ -11,7 +11,7 @@ import java.util.List;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class DijkstraAlgorithmTest { public class DijkstraAlgorithmLongRunningUnitTest {
@Test @Test
public void whenSPPSolved_thenCorrect() { public void whenSPPSolved_thenCorrect() {
@ -56,19 +56,29 @@ public class DijkstraAlgorithmTest {
for (Node node : graph.getNodes()) { for (Node node : graph.getNodes()) {
switch (node.getName()) { switch (node.getName()) {
case "B": case "B":
assertTrue(node.getShortestPath().equals(shortestPathForNodeB)); assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeB));
break; break;
case "C": case "C":
assertTrue(node.getShortestPath().equals(shortestPathForNodeC)); assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeC));
break; break;
case "D": case "D":
assertTrue(node.getShortestPath().equals(shortestPathForNodeD)); assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeD));
break; break;
case "E": case "E":
assertTrue(node.getShortestPath().equals(shortestPathForNodeE)); assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeE));
break; break;
case "F": case "F":
assertTrue(node.getShortestPath().equals(shortestPathForNodeF)); assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeF));
break; break;
} }
} }

View File

@ -1,28 +1,27 @@
package algorithms; package algorithms;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.automata.*; import com.baeldung.automata.*;
import org.junit.Test;
/** import static org.junit.Assert.assertTrue;
* Tests for {@link RtFiniteStateMachine}
*/ public final class RtFiniteStateMachineLongRunningUnitTest {
public final class RtFiniteStateMachineTest {
@Test @Test
public void acceptsSimplePair() { public void acceptsSimplePair() {
String json = "{\"key\":\"value\"}"; String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
assertTrue(machine.canStop()); assertTrue(machine.canStop());
} }
@Test @Test
public void acceptsMorePairs() { public void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
assertTrue(machine.canStop()); assertTrue(machine.canStop());
@ -32,7 +31,7 @@ public final class RtFiniteStateMachineTest {
public void missingColon() { public void missingColon() {
String json = "{\"key\"\"value\"}"; String json = "{\"key\"\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
} }
@ -56,20 +55,12 @@ public final class RtFiniteStateMachineTest {
second.with(new RtTransition("\"", third)); second.with(new RtTransition("\"", third));
//Add transitions with chars 0-9 and a-z //Add transitions with chars 0-9 and a-z
for (int i = 0; i < 26; i++) { for (int i = 0; i < 26; i++) {
if(i<10) { if (i < 10) {
third = third.with( third = third.with(new RtTransition(String.valueOf(i), third));
new RtTransition(String.valueOf(i), third) sixth = sixth.with(new RtTransition(String.valueOf(i), sixth));
);
sixth = sixth.with(
new RtTransition(String.valueOf(i), sixth)
);
} }
third = third.with( third = third.with(new RtTransition(String.valueOf((char) ('a' + i)), third));
new RtTransition(String.valueOf((char) ('a' + i)), third) sixth = sixth.with(new RtTransition(String.valueOf((char) ('a' + i)), sixth));
);
sixth = sixth.with(
new RtTransition(String.valueOf((char) ('a' + i)), sixth)
);
} }
third.with(new RtTransition("\"", fourth)); third.with(new RtTransition("\"", fourth));
fourth.with(new RtTransition(":", fifth)); fourth.with(new RtTransition(":", fifth));

View File

@ -5,7 +5,7 @@ import org.junit.Test;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
public class SimulatedAnnealingTest { public class SimulatedAnnealingLongRunningUnitTest {
@Test @Test
public void testSimulateAnnealing() { public void testSimulateAnnealing() {

View File

@ -1,28 +0,0 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class BigIntegerPrimeCheckerTest {
BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13l));
assertTrue(primeChecker.isPrime(1009L));
assertTrue(primeChecker.isPrime(74207281L));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50L));
assertTrue(!primeChecker.isPrime(1001L));
assertTrue(!primeChecker.isPrime(74207282L));
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
import static org.junit.Assert.*;
public class BruteForcePrimeCheckerTest {
BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class OptimisedPrimeCheckerTest {
OptimisedPrimeChecker primeChecker = new OptimisedPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PrimeCheckerTest {
private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
@Test
public void whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13l));
assertTrue(primeChecker.isPrime(1009L));
assertTrue(primeChecker.isPrime(74207281L));
}
@Test
public void whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50L));
assertTrue(!primeChecker.isPrime(1001L));
assertTrue(!primeChecker.isPrime(74207282L));
}
private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
@Test
public void whenBFCheckIsPrime_thenTrue(){
assertTrue(bfPrimeChecker.isPrime(13));
assertTrue(bfPrimeChecker.isPrime(1009));
}
@Test
public void whenBFCheckIsPrime_thenFalse(){
assertFalse(bfPrimeChecker.isPrime(50));
assertFalse(bfPrimeChecker.isPrime(1001));
}
private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker();
@Test
public void whenOptCheckIsPrime_thenTrue(){
assertTrue(optimisedPrimeChecker.isPrime(13));
assertTrue(optimisedPrimeChecker.isPrime(1009));
}
@Test
public void whenOptCheckIsPrime_thenFalse(){
assertFalse(optimisedPrimeChecker.isPrime(50));
assertFalse(optimisedPrimeChecker.isPrime(1001));
}
private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker();
@Test
public void whenPrimesCheckIsPrime_thenTrue() {
assertTrue(primesPrimeChecker.isPrime(13));
assertTrue(primesPrimeChecker.isPrime(1009));
}
@Test
public void whenPrimesCheckIsPrime_thenFalse() {
assertFalse(primesPrimeChecker.isPrime(50));
assertFalse(primesPrimeChecker.isPrime(1001));
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.PrimeChecker;
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
public class PrimesPrimeCheckerTest {
PrimesPrimeChecker primeChecker = new PrimesPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue() {
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() {
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -5,6 +5,11 @@
<artifactId>apache-bval</artifactId> <artifactId>apache-bval</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.bval</groupId> <groupId>org.apache.bval</groupId>

View File

@ -3,8 +3,10 @@ package com.baeldung.cxf.aegis;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@ -90,4 +92,12 @@ public class BaeldungTest {
xmlReader.close(); xmlReader.close();
return courseRepo; return courseRepo;
} }
@After
public void cleanup(){
File testFile = new File(fileName);
if (testFile.exists()) {
testFile.delete();
}
}
} }

View File

@ -54,6 +54,12 @@
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>${httpclient.version}</version> <version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -24,6 +24,12 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>

View File

@ -6,6 +6,12 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules> <modules>
<module>cxf-introduction</module> <module>cxf-introduction</module>
<module>cxf-spring</module> <module>cxf-spring</module>

View File

@ -7,6 +7,12 @@
<name>apache-fop</name> <name>apache-fop</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies> <dependencies>
<!-- logging --> <!-- logging -->
@ -28,11 +34,6 @@
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl --> <!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency> </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>
<!-- test scoped --> <!-- test scoped -->
@ -78,6 +79,10 @@
<groupId>org.apache.avalon.framework</groupId> <groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-impl</artifactId> <artifactId>avalon-framework-impl</artifactId>
</exclusion> </exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
@ -90,6 +95,12 @@
<groupId>avalon-framework</groupId> <groupId>avalon-framework</groupId>
<artifactId>avalon-framework-impl</artifactId> <artifactId>avalon-framework-impl</artifactId>
<version>${avalon-framework.version}</version> <version>${avalon-framework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -5,6 +5,12 @@
<artifactId>apache-poi</artifactId> <artifactId>apache-poi</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
@ -42,6 +48,12 @@
<groupId>org.jxls</groupId> <groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId> <artifactId>jxls-jexcel</artifactId>
<version>${jexcel.version}</version> <version>${jexcel.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -19,6 +19,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.junit.Before; import org.junit.Before;
import org.junit.After;
public class JExcelTest { public class JExcelTest {
@ -53,4 +54,11 @@ public class JExcelTest {
.get(1)); .get(1));
} }
@After
public void cleanup(){
File testFile = new File(fileLocation);
if (testFile.exists()) {
testFile.delete();
}
}
} }

View File

@ -16,6 +16,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.junit.Before; import org.junit.Before;
import org.junit.After;
public class ExcelTest { public class ExcelTest {
@ -50,4 +51,11 @@ public class ExcelTest {
.get(1)); .get(1));
} }
@After
public void cleanup(){
File testFile = new File(fileLocation);
if (testFile.exists()) {
testFile.delete();
}
}
} }

Binary file not shown.

Binary file not shown.

View File

@ -7,6 +7,12 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<name>apache-solrj</name> <name>apache-solrj</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

View File

@ -6,6 +6,12 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<java.versin>1.8</java.versin> <java.versin>1.8</java.versin>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
@ -19,6 +25,12 @@
<groupId>org.apache.thrift</groupId> <groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId> <artifactId>libthrift</artifactId>
<version>${thrift.version}</version> <version>${thrift.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -9,6 +9,12 @@
<packaging>war</packaging> <packaging>war</packaging>
<name>apache-velocity</name> <name>apache-velocity</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<jdk.version>1.8</jdk.version> <jdk.version>1.8</jdk.version>
<jstl.version>1.2</jstl.version> <jstl.version>1.2</jstl.version>
@ -55,6 +61,12 @@
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>${org.apache.httpcomponents.version}</version> <version>${org.apache.httpcomponents.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)

View File

@ -1,138 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>aspectj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aspectj</name>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- utils -->
<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>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- unit test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>aspectj</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>${source.version}</source>
<target>${source.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>${source.version}</complianceLevel>
<source>${source.version}</source>
<target>${source.version}</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving -->
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
</plugins>
</build>
<properties>
<source.version>1.8</source.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.6.0</maven-compiler-plugin.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [AssertJs Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)

View File

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>assertj</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<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>
<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>

View File

@ -6,6 +6,12 @@
<version>1.0</version> <version>1.0</version>
<name>autovalue</name> <name>autovalue</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>

View File

@ -7,6 +7,12 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<name>aws</name> <name>aws</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties> <properties>
<commons-io.version>2.5</commons-io.version> <commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version> <aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
@ -19,12 +25,24 @@
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId> <artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version> <version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId> <artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version> <version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -7,6 +7,12 @@
<artifactId>cdi</artifactId> <artifactId>cdi</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>

View File

@ -12,3 +12,4 @@
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) - [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)

View File

@ -92,3 +92,12 @@
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) - [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) - [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) - [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)

View File

@ -8,6 +8,12 @@
<name>core-java</name> <name>core-java</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies> <dependencies>
<!-- utils --> <!-- utils -->
@ -92,11 +98,6 @@
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl --> <!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency> </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> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
@ -104,6 +105,13 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <dependency>
@ -140,13 +148,6 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
@ -171,12 +172,29 @@
<artifactId>moneta</artifactId> <artifactId>moneta</artifactId>
<version>1.1</version> <version>1.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.owasp.esapi</groupId> <groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId> <artifactId>esapi</artifactId>
<version>2.1.0.1</version> <version>2.1.0.1</version>
</dependency> <exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
@ -190,7 +208,6 @@
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@ -200,7 +217,6 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
@ -209,11 +225,11 @@
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude> <exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude> <exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
</excludes> </excludes>
<testFailureIgnore>true</testFailureIgnore> <testFailureIgnore>true</testFailureIgnore>
</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>
@ -244,7 +260,6 @@
</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>
@ -268,7 +283,6 @@
</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>
@ -289,7 +303,6 @@
</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>
@ -306,7 +319,6 @@
</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>
@ -322,7 +334,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
@ -370,6 +381,9 @@
<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>
<!-- mysql -->
<mysql.version>6.0.6</mysql.version>
<!-- util --> <!-- util -->
<guava.version>21.0</guava.version> <guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
@ -387,7 +401,6 @@
<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>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>

View File

@ -0,0 +1,27 @@
package com.baeldung.concurrent.phaser;
import java.util.concurrent.Phaser;
class LongRunningAction implements Runnable {
private String threadName;
private Phaser ph;
LongRunningAction(String threadName, Phaser ph) {
this.threadName = threadName;
this.ph = ph;
ph.register();
}
@Override
public void run() {
System.out.println("This is phase " + ph.getPhase());
System.out.println("Thread " + threadName + " before long running action");
ph.arriveAndAwaitAdvance();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
ph.arriveAndDeregister();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
public class Event {
private final ZonedDateTime eventTime;
private final String content;
public Event(ZonedDateTime eventTime, String content) {
this.eventTime = eventTime;
this.content = content;
}
public ZonedDateTime getEventTime() {
return eventTime;
}
public String getContent() {
return content;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
import java.util.Comparator;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class EventWindowSort {
private final ConcurrentSkipListMap<ZonedDateTime, String> events
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
public void acceptEvent(Event event) {
events.put(event.getEventTime(), event.getContent());
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
return events.tailMap(ZonedDateTime
.now()
.minusMinutes(1));
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
.now()
.minusMinutes(1));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.concurrent.sleepwait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* Example of waking up a waiting thread
*/
public class ThreadA {
private static final Logger LOG = LoggerFactory.getLogger(ThreadA.class);
private static final ThreadB b = new ThreadB();
public static void main(String... args) throws InterruptedException {
b.start();
synchronized (b) {
while (b.sum == 0) {
LOG.debug("Waiting for ThreadB to complete...");
b.wait();
}
LOG.debug("ThreadB has completed. Sum from that thread is: " + b.sum);
}
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.sleepwait;
/***
* Example of waking up a waiting thread
*/
class ThreadB extends Thread {
int sum;
@Override
public void run() {
synchronized (this) {
int i = 0;
while (i < 100000) {
sum += i;
i++;
}
notify();
}
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.concurrent.sleepwait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* Example of wait() and sleep() methods
*/
public class WaitSleepExample {
private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class);
private static final Object LOCK = new Object();
public static void main(String... args) throws InterruptedException {
sleepWaitInSyncronizedBlocks();
}
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
Thread.sleep(1000); // called on the thread
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
synchronized (LOCK) {
LOCK.wait(1000); // called on the object, synchronization required
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
}
}
}

View File

@ -1,14 +1,19 @@
package com.baeldung.dirmonitoring; package com.baeldung.dirmonitoring;
import java.io.File;
import org.apache.commons.io.monitor.FileAlterationListener; import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver; import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DirectoryMonitoringExample { public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
public static final int POLL_INTERVAL = 500; public static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@ -17,17 +22,17 @@ public class DirectoryMonitoringExample {
FileAlterationListener listener = new FileAlterationListenerAdaptor() { FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override @Override
public void onFileCreate(File file) { public void onFileCreate(File file) {
System.out.println("File: " + file.getName() + " created"); LOG.debug("File: " + file.getName() + " created");
} }
@Override @Override
public void onFileDelete(File file) { public void onFileDelete(File file) {
System.out.println("File: " + file.getName() + " deleted"); LOG.debug("File: " + file.getName() + " deleted");
} }
@Override @Override
public void onFileChange(File file) { public void onFileChange(File file) {
System.out.println("File: " + file.getName() + " changed"); LOG.debug("File: " + file.getName() + " changed");
} }
}; };
observer.addListener(listener); observer.addListener(listener);

View File

@ -1,9 +1,14 @@
package com.baeldung.doublecolon; package com.baeldung.doublecolon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Function; import java.util.function.Function;
public class MacbookPro extends Computer { public class MacbookPro extends Computer {
private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class);
public MacbookPro(int age, String color) { public MacbookPro(int age, String color) {
super(age, color); super(age, color);
} }
@ -14,12 +19,12 @@ public class MacbookPro extends Computer {
@Override @Override
public void turnOnPc() { public void turnOnPc() {
System.out.println("MacbookPro turned on"); LOG.debug("MacbookPro turned on");
} }
@Override @Override
public void turnOffPc() { public void turnOffPc() {
System.out.println("MacbookPro turned off"); LOG.debug("MacbookPro turned off");
} }
@Override @Override
@ -27,7 +32,7 @@ public class MacbookPro extends Computer {
Function<Double, Double> function = super::calculateValue; Function<Double, Double> function = super::calculateValue;
final Double pcValue = function.apply(initialValue); final Double pcValue = function.apply(initialValue);
System.out.println("First value is:" + pcValue); LOG.debug("First value is:" + pcValue);
return pcValue + (initialValue / 10); return pcValue + (initialValue / 10);
} }

View File

@ -0,0 +1,19 @@
package com.baeldung.dynamicproxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.info("Invoked method: {}", method.getName());
return 42;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimingDynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
private final Map<String, Method> methods = new HashMap<>();
private Object target;
public TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
this.methods.put(method.getName(), method);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
Object result = methods.get(method.getName()).invoke(target, args);
long elapsed = System.nanoTime() - start;
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
return result;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.http;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class ParameterStringBuilder {
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
}

View File

@ -1,6 +1,11 @@
package com.baeldung.java.map; package com.baeldung.java.map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyKey { public class MyKey {
private static final Logger LOG = LoggerFactory.getLogger(MyKey.class);
private String name; private String name;
private int id; private int id;
@ -27,7 +32,7 @@ public class MyKey {
@Override @Override
public int hashCode() { public int hashCode() {
System.out.println("Calling hashCode()"); LOG.debug("Calling hashCode()");
return id; return id;
} }
@ -38,7 +43,7 @@ public class MyKey {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
System.out.println("Calling equals() for key: " + obj); LOG.debug("Calling equals() for key: " + obj);
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)

View File

@ -0,0 +1,21 @@
package com.baeldung.java.reflection;
public class Operations {
public double publicSum(int a, double b) {
return a + b;
}
public static double publicStaticMultiply(float a, long b) {
return a * b;
}
private boolean privateAnd(boolean a, boolean b) {
return a && b;
}
protected int protectedMax(int a, int b) {
return a > b ? a : b;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jdbc;
public class Employee {
private int id;
private String name;
private String position;
private double salary;
public Employee() {
}
public Employee(int id, String name, double salary, String position) {
this.id = id;
this.name = name;
this.salary = salary;
this.position = position;
}
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}

View File

@ -1,23 +1,28 @@
package com.baeldung.jmx; package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Game implements GameMBean { public class Game implements GameMBean {
private static final Logger LOG = LoggerFactory.getLogger(Game.class);
private String playerName; private String playerName;
@Override @Override
public void playFootball(String clubName) { public void playFootball(String clubName) {
System.out.println(this.playerName + " playing football for " + clubName); LOG.debug(this.playerName + " playing football for " + clubName);
} }
@Override @Override
public String getPlayerName() { public String getPlayerName() {
System.out.println("Return playerName " + this.playerName); LOG.debug("Return playerName " + this.playerName);
return playerName; return playerName;
} }
@Override @Override
public void setPlayerName(String playerName) { public void setPlayerName(String playerName) {
System.out.println("Set playerName to value " + playerName); LOG.debug("Set playerName to value " + playerName);
this.playerName = playerName; this.playerName = playerName;
} }

View File

@ -1,19 +1,20 @@
package com.baeldung.jmx; package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
import java.lang.management.ManagementFactory; 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 class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) { public static void main(String[] args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
System.out.println("This is basic JMX tutorial"); LOG.debug("This is basic JMX tutorial");
ObjectName objectName = null; ObjectName objectName = null;
try { try {
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
@ -27,8 +28,8 @@ public class JMXTutorialMainlauncher {
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
e.printStackTrace(); e.printStackTrace();
} }
System.out.println("Registration for Game mbean with the platform server is successfull"); LOG.debug("Registration for Game mbean with the platform server is successfull");
System.out.println("Please open jconsole to access Game mbean"); LOG.debug("Please open jconsole to access Game mbean");
while (true) { while (true) {
// to ensure application does not terminate // to ensure application does not terminate
} }

View File

@ -1,9 +1,16 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
public class EchoClient { public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
private Socket clientSocket; private Socket clientSocket;
private PrintWriter out; private PrintWriter out;
private BufferedReader in; private BufferedReader in;
@ -14,7 +21,7 @@ public class EchoClient {
out = new PrintWriter(clientSocket.getOutputStream(), true); out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) { } catch (IOException e) {
System.out.print(e); LOG.debug("Error when initializing connection", e);
} }
} }
@ -34,7 +41,7 @@ public class EchoClient {
out.close(); out.close();
clientSocket.close(); clientSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug("error when closing", e);
} }
} }

View File

@ -1,9 +1,15 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
public class EchoMultiServer { public class EchoMultiServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private ServerSocket serverSocket; private ServerSocket serverSocket;
public void start(int port) { public void start(int port) {
@ -57,7 +63,7 @@ public class EchoMultiServer {
clientSocket.close(); clientSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }
} }

View File

@ -1,9 +1,15 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
public class EchoServer { public class EchoServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
private ServerSocket serverSocket; private ServerSocket serverSocket;
private Socket clientSocket; private Socket clientSocket;
private PrintWriter out; private PrintWriter out;
@ -24,7 +30,7 @@ public class EchoServer {
out.println(inputLine); out.println(inputLine);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }
@ -36,7 +42,7 @@ public class EchoServer {
clientSocket.close(); clientSocket.close();
serverSocket.close(); serverSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }

View File

@ -1,5 +1,8 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -7,6 +10,9 @@ import java.io.PrintWriter;
import java.net.Socket; import java.net.Socket;
public class GreetClient { public class GreetClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private Socket clientSocket; private Socket clientSocket;
private PrintWriter out; private PrintWriter out;
private BufferedReader in; private BufferedReader in;
@ -17,7 +23,7 @@ public class GreetClient {
out = new PrintWriter(clientSocket.getOutputStream(), true); out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) { } catch (IOException e) {
LOG.debug(e.getMessage());
} }
} }
@ -37,7 +43,7 @@ public class GreetClient {
out.close(); out.close();
clientSocket.close(); clientSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }

View File

@ -1,9 +1,15 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
public class GreetServer { public class GreetServer {
private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class);
private ServerSocket serverSocket; private ServerSocket serverSocket;
private Socket clientSocket; private Socket clientSocket;
private PrintWriter out; private PrintWriter out;
@ -21,7 +27,7 @@ public class GreetServer {
else else
out.println("unrecognised greeting"); out.println("unrecognised greeting");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }
@ -33,7 +39,7 @@ public class GreetServer {
clientSocket.close(); clientSocket.close();
serverSocket.close(); serverSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LOG.debug(e.getMessage());
} }
} }

View File

@ -0,0 +1,8 @@
package com.baeldung.stackoverflowerror;
public class AccountHolder {
private String firstName;
private String lastName;
AccountHolder jointAccountHolder = new AccountHolder();
}

View File

@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassOne {
private int oneValue;
private ClassTwo clsTwoInstance = null;
public ClassOne() {
oneValue = 0;
clsTwoInstance = new ClassTwo();
}
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
this.oneValue = oneValue;
this.clsTwoInstance = clsTwoInstance;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassTwo {
private int twoValue;
private ClassOne clsOneInstance = null;
public ClassTwo() {
twoValue = 10;
clsOneInstance = new ClassOne();
}
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
this.twoValue = twoValue;
this.clsOneInstance = clsOneInstance;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class InfiniteRecursionWithTerminationCondition {
public int calculateFactorial(final int number) {
return number == 1 ? 1 : number * calculateFactorial(number - 1);
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class RecursionWithCorrectTerminationCondition {
public static int calculateFactorial(final int number) {
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {
return number * calculateFactorial(number - 1);
}
}

View File

@ -1,9 +1,15 @@
package com.baeldung.stream; package com.baeldung.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Stream; import java.util.stream.Stream;
public class InfiniteStreams { public class InfiniteStreams {
private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class);
public static void main(String[] args) { public static void main(String[] args) {
doWhileOldWay(); doWhileOldWay();
@ -15,7 +21,7 @@ public class InfiniteStreams {
int i = 0; int i = 0;
while (i < 10) { while (i < 10) {
System.out.println(i); LOG.debug("{}", i);
i++; i++;
} }
} }

View File

@ -1,7 +1,11 @@
package com.baeldung.threadlocal; package com.baeldung.threadlocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadLocalWithUserContext implements Runnable { public class ThreadLocalWithUserContext implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalWithUserContext.class);
private static final ThreadLocal<Context> userContext = new ThreadLocal<>(); private static final ThreadLocal<Context> userContext = new ThreadLocal<>();
private final Integer userId; private final Integer userId;
private UserRepository userRepository = new UserRepository(); private UserRepository userRepository = new UserRepository();
@ -15,6 +19,6 @@ public class ThreadLocalWithUserContext implements Runnable {
public void run() { public void run() {
String userName = userRepository.getUserNameForUserId(userId); String userName = userRepository.getUserNameForUserId(userId);
userContext.set(new Context(userName)); userContext.set(new Context(userName));
System.out.println("thread context for given userId: " + userId + " is: " + userContext.get()); LOG.debug("thread context for given userId: " + userId + " is: " + userContext.get());
} }
} }

View File

@ -0,0 +1,42 @@
package com.baeldung.transferqueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue;
private final String name;
private final int numberOfMessagesToConsume;
public final AtomicInteger numberOfConsumedMessages = new AtomicInteger();
public Consumer(TransferQueue<String> transferQueue, String name, int numberOfMessagesToConsume) {
this.transferQueue = transferQueue;
this.name = name;
this.numberOfMessagesToConsume = numberOfMessagesToConsume;
}
@Override
public void run() {
for (int i = 0; i < numberOfMessagesToConsume; i++) {
try {
LOG.debug("Consumer: " + name + " is waiting to take element...");
String element = transferQueue.take();
longProcessing(element);
LOG.debug("Consumer: " + name + " received element: " + element);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void longProcessing(String element) throws InterruptedException {
numberOfConsumedMessages.incrementAndGet();
Thread.sleep(500);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.transferqueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Producer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Producer.class);
private final TransferQueue<String> transferQueue;
private final String name;
private final Integer numberOfMessagesToProduce;
public final AtomicInteger numberOfProducedMessages = new AtomicInteger();
public Producer(TransferQueue<String> transferQueue, String name, Integer numberOfMessagesToProduce) {
this.transferQueue = transferQueue;
this.name = name;
this.numberOfMessagesToProduce = numberOfMessagesToProduce;
}
@Override
public void run() {
for (int i = 0; i < numberOfMessagesToProduce; i++) {
try {
LOG.debug("Producer: " + name + " is waiting to transfer...");
boolean added = transferQueue.tryTransfer("A" + i, 4000, TimeUnit.MILLISECONDS);
if (added) {
numberOfProducedMessages.incrementAndGet();
LOG.debug("Producer: " + name + " transferred element: A" + i);
} else {
LOG.debug("can not add an element due to the timeout");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<!-- JDO tutorial "unit" -->
<persistence-unit name="Tutorial">
<exclude-unlisted-classes/>
<properties>
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
<property name="javax.jdo.option.ConnectionPassword" value=""/>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -1,14 +1,15 @@
package com.baeldung; package com.baeldung;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
/**
*
* @author paulo.motta
*/
public class PrimitiveConversionsJUnitTest { public class PrimitiveConversionsJUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class);
@Test @Test
public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() { public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
int myInt = 127; int myInt = 127;
@ -60,36 +61,36 @@ public class PrimitiveConversionsJUnitTest {
@Test @Test
public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){ public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
byte myLargeValueByte = (byte) 130; //0b10000010 byte myLargeValueByte = (byte) 130; //0b10000010
System.out.println(myLargeValueByte); //0b10000010 -126 LOG.debug("{}", myLargeValueByte); //0b10000010 -126
assertEquals( -126, myLargeValueByte); assertEquals( -126, myLargeValueByte);
int myLargeValueInt = myLargeValueByte; int myLargeValueInt = myLargeValueByte;
System.out.println(myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126 LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
assertEquals( -126, myLargeValueInt); assertEquals( -126, myLargeValueInt);
char myLargeValueChar = (char) myLargeValueByte; char myLargeValueChar = (char) myLargeValueByte;
System.out.println(myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82 LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
assertEquals(0xFF82, myLargeValueChar); assertEquals(0xFF82, myLargeValueChar);
myLargeValueInt = myLargeValueChar; myLargeValueInt = myLargeValueChar;
System.out.println(myLargeValueInt); //0b11111111 10000010 65410 LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410
assertEquals(65410, myLargeValueInt); assertEquals(65410, myLargeValueInt);
byte myOtherByte = (byte) myLargeValueInt; byte myOtherByte = (byte) myLargeValueInt;
System.out.println(myOtherByte); //0b10000010 -126 LOG.debug("{}", myOtherByte); //0b10000010 -126
assertEquals( -126, myOtherByte); assertEquals( -126, myOtherByte);
char myLargeValueChar2 = 130; //This is an int not a byte! char myLargeValueChar2 = 130; //This is an int not a byte!
System.out.println(myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082 LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082
assertEquals(0x0082, myLargeValueChar2); assertEquals(0x0082, myLargeValueChar2);
int myLargeValueInt2 = myLargeValueChar2; int myLargeValueInt2 = myLargeValueChar2;
System.out.println(myLargeValueInt2); //0b00000000 10000010 130 LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130
assertEquals(130, myLargeValueInt2); assertEquals(130, myLargeValueInt2);
byte myOtherByte2 = (byte) myLargeValueInt2; byte myOtherByte2 = (byte) myLargeValueInt2;
System.out.println(myOtherByte2); //0b10000010 -126 LOG.debug("{}", myOtherByte2); //0b10000010 -126
assertEquals( -126, myOtherByte2); assertEquals( -126, myOtherByte2);
} }

View File

@ -1,20 +1,21 @@
package com.baeldung.completablefuture; package com.baeldung.completablefuture;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
public class CompletableFutureUnitTest { public class CompletableFutureUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class);
@Test @Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync(); Future<String> completableFuture = calculateAsync();
@ -72,7 +73,7 @@ public class CompletableFutureUnitTest {
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); CompletableFuture<Void> future = completableFuture.thenAccept(s -> LOG.debug("Computation returned: " + s));
future.get(); future.get();
} }
@ -81,7 +82,7 @@ public class CompletableFutureUnitTest {
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); CompletableFuture<Void> future = completableFuture.thenRun(() -> LOG.debug("Computation finished."));
future.get(); future.get();
} }
@ -111,7 +112,7 @@ public class CompletableFutureUnitTest {
@Test @Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
} }
@Test @Test

View File

@ -0,0 +1,42 @@
package com.baeldung.concurrent.accumulator;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;
import static junit.framework.TestCase.assertEquals;
public class LongAccumulatorTest {
@Test
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(accumulator.get(), 20200);
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.concurrent.adder;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
import static com.jayway.awaitility.Awaitility.await;
import static junit.framework.TestCase.assertEquals;
public class LongAdderTest {
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThem() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
}
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThemAndResetAdderAfterward() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sumThenReset(), numberOfIncrements * numberOfThreads);
await().until(() -> assertEquals(counter.sum(), 0));
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.concurrent.copyonwrite;
import org.junit.Test;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.assertj.core.api.Assertions.assertThat;
public class CopyOnWriteArrayListTest {
@Test
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
numbers.add(10);
//then
List<Integer> result = new LinkedList<>();
iterator.forEachRemaining(result::add);
assertThat(result).containsOnly(1, 3, 5, 8);
//and
Iterator<Integer> iterator2 = numbers.iterator();
List<Integer> result2 = new LinkedList<>();
iterator2.forEachRemaining(result2::add);
//then
assertThat(result2).containsOnly(1, 3, 5, 8, 10);
}
@Test(expected = UnsupportedOperationException.class)
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
iterator.remove();
}
}
}

View File

@ -1,22 +1,22 @@
package com.baeldung.concurrent.future; package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TestName; import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SquareCalculatorIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class);
public class SquareCalculatorUnitTest {
@Rule @Rule
public TestName name = new TestName(); public TestName name = new TestName();
@ -33,7 +33,7 @@ public class SquareCalculatorUnitTest {
Future<Integer> result2 = squareCalculator.calculate(1000); Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) { while (!result1.isDone() || !result2.isDone()) {
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300); Thread.sleep(300);
} }
@ -59,7 +59,7 @@ public class SquareCalculatorUnitTest {
Future<Integer> result2 = squareCalculator.calculate(1000); Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) { while (!result1.isDone() || !result2.isDone()) {
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300); Thread.sleep(300);
} }
@ -89,6 +89,6 @@ public class SquareCalculatorUnitTest {
@After @After
public void end() { public void end() {
System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); LOG.debug(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start));
} }
} }

View File

@ -0,0 +1,41 @@
package com.baeldung.concurrent.phaser;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserTest {
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
ExecutorService executorService = Executors.newCachedThreadPool();
Phaser ph = new Phaser(1);
assertEquals(0, ph.getPhase());
//when
executorService.submit(new LongRunningAction("thread-1", ph));
executorService.submit(new LongRunningAction("thread-2", ph));
executorService.submit(new LongRunningAction("thread-3", ph));
//then
ph.arriveAndAwaitAdvance();
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
ph.arriveAndAwaitAdvance();
assertEquals(2, ph.getPhase());
ph.arriveAndDeregister();
}
}

View File

@ -1,6 +1,8 @@
package com.baeldung.concurrent.priorityblockingqueue; package com.baeldung.concurrent.priorityblockingqueue;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.PriorityBlockingQueue;
@ -9,7 +11,10 @@ import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.Lists.newArrayList;
public class PriorityBlockingQueueUnitTest { public class PriorityBlockingQueueIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(PriorityBlockingQueueIntegrationTest.class);
@Test @Test
public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException {
@ -32,11 +37,11 @@ public class PriorityBlockingQueueUnitTest {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
final Thread thread = new Thread(() -> { final Thread thread = new Thread(() -> {
System.out.println("Polling..."); LOG.debug("Polling...");
while (true) { while (true) {
try { try {
Integer poll = queue.take(); Integer poll = queue.take();
System.out.println("Polled: " + poll); LOG.debug("Polled: " + poll);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
@ -44,7 +49,7 @@ public class PriorityBlockingQueueUnitTest {
thread.start(); thread.start();
Thread.sleep(TimeUnit.SECONDS.toMillis(5)); Thread.sleep(TimeUnit.SECONDS.toMillis(5));
System.out.println("Adding to queue"); LOG.debug("Adding to queue");
queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7));
Thread.sleep(TimeUnit.SECONDS.toMillis(1)); Thread.sleep(TimeUnit.SECONDS.toMillis(1));

View File

@ -0,0 +1,120 @@
package com.baeldung.concurrent.skiplist;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConcurrentSkipListSetIntegrationTest {
@Test
public void givenThreadsProducingEvents_whenGetForEventsFromLastMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(3);
EventWindowSort eventWindowSort = new EventWindowSort();
int numberOfThreads = 2;
//when
Runnable producer = () -> IntStream
.rangeClosed(0, 100)
.forEach(index -> eventWindowSort.acceptEvent(new Event(ZonedDateTime
.now()
.minusSeconds(index), UUID
.randomUUID()
.toString())));
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(producer);
}
Thread.sleep(500);
ConcurrentNavigableMap<ZonedDateTime, String> eventsFromLastMinute = eventWindowSort.getEventsFromLastMinute();
long eventsOlderThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isBefore(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
assertEquals(eventsOlderThanOneMinute, 0);
long eventYoungerThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isAfter(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
//then
assertTrue(eventYoungerThanOneMinute > 0);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenThreadsProducingEvents_whenGetForEventsOlderThanOneMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(3);
EventWindowSort eventWindowSort = new EventWindowSort();
int numberOfThreads = 2;
//when
Runnable producer = () -> IntStream
.rangeClosed(0, 100)
.forEach(index -> eventWindowSort.acceptEvent(new Event(ZonedDateTime
.now()
.minusSeconds(index), UUID
.randomUUID()
.toString())));
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(producer);
}
Thread.sleep(500);
ConcurrentNavigableMap<ZonedDateTime, String> eventsFromLastMinute = eventWindowSort.getEventsOlderThatOneMinute();
long eventsOlderThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isBefore(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
assertTrue(eventsOlderThanOneMinute > 0);
long eventYoungerThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isAfter(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
//then
assertEquals(eventYoungerThanOneMinute, 0);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.dateapi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
public class JavaDurationTest {
@Test
public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
Duration duration = Duration.between(start, end);
assertFalse(duration.isNegative());
assertEquals(60, duration.getSeconds());
assertEquals(1, duration.toMinutes());
Duration fromDays = Duration.ofDays(1);
assertEquals(86400, fromDays.getSeconds());
Duration fromMinutes = Duration.ofMinutes(60);
assertEquals(1, fromMinutes.toHours());
assertEquals(120, duration.plusSeconds(60).getSeconds());
assertEquals(30, duration.minusSeconds(30).getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.dateapi;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class JavaPeriodTest {
private static final Logger LOG = Logger.getLogger(JavaPeriodTest.class);
@Test
public void whenTestPeriod_thenOk() {
LocalDate startDate = LocalDate.of(2015, 2, 15);
LocalDate endDate = LocalDate.of(2017, 1, 21);
Period period = Period.between(startDate, endDate);
LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays()));
assertFalse(period.isNegative());
assertEquals(56, period.plusDays(50).getDays());
assertEquals(9, period.minusMonths(2).getMonths());
Period fromUnits = Period.of(3, 10, 10);
Period fromDays = Period.ofDays(50);
Period fromMonths = Period.ofMonths(5);
Period fromYears = Period.ofYears(10);
Period fromWeeks = Period.ofWeeks(40);
assertEquals(280, fromWeeks.getDays());
Period fromCharYears = Period.parse("P2Y");
assertEquals(2, fromCharYears.getYears());
Period fromCharUnits = Period.parse("P2Y3M5D");
assertEquals(5, fromCharUnits.getDays());
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.dynamicproxy;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DynamicProxyTest {
@Test
public void givenDynamicProxy_thenPutWorks() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler());
proxyInstance.put("hello", "world");
}
@Test
public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> {
if (method.getName().equals("get")) {
return 42;
} else {
throw new UnsupportedOperationException("Unsupported method: " + method.getName());
}
});
int result = (int) proxyInstance.get("hello");
assertEquals(42, result);
try {
proxyInstance.put("hello", "world");
fail();
} catch(UnsupportedOperationException e) {
// expected
}
}
@Test
public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() {
Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>()));
mapProxyInstance.put("hello", "world");
assertEquals("world", mapProxyInstance.get("hello"));
CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World"));
assertEquals('l', csProxyInstance.charAt(2));
assertEquals(11, csProxyInstance.length());
}
}

View File

@ -1,8 +1,9 @@
package com.baeldung.functionalinterface; package com.baeldung.functionalinterface;
import static org.junit.Assert.assertArrayEquals; import com.google.common.util.concurrent.Uninterruptibles;
import static org.junit.Assert.assertEquals; import org.junit.Test;
import static org.junit.Assert.assertTrue; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -14,12 +15,13 @@ import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Test; import static org.junit.Assert.*;
import com.google.common.util.concurrent.Uninterruptibles;
public class FunctionalInterfaceUnitTest { public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test @Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>(); Map<String, Integer> nameMap = new HashMap<>();
@ -65,7 +67,7 @@ public class FunctionalInterfaceUnitTest {
@Test @Test
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); Thread thread = new Thread(() -> LOG.debug("Hello From Another Thread"));
thread.start(); thread.start();
} }
@ -93,7 +95,7 @@ public class FunctionalInterfaceUnitTest {
@Test @Test
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
List<String> names = Arrays.asList("John", "Freddy", "Samuel"); List<String> names = Arrays.asList("John", "Freddy", "Samuel");
names.forEach(name -> System.out.println("Hello, " + name)); names.forEach(name -> LOG.debug("Hello, " + name));
} }
@Test @Test
@ -103,7 +105,7 @@ public class FunctionalInterfaceUnitTest {
ages.put("Freddy", 24); ages.put("Freddy", 24);
ages.put("Samuel", 30); ages.put("Samuel", 30);
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); ages.forEach((name, age) -> LOG.debug(name + " is " + age + " years old"));
} }
@Test @Test

View File

@ -0,0 +1,126 @@
package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class HttpRequestTest {
@Test
public void whenGetRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
assertTrue("content incorrect", content.toString().contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenGetCookies_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
String cookiesHeader = con.getHeaderField("Set-Cookie");
Optional<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));
usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username"));
}
if (usernameCookie == null) {
cookieManager.getCookieStore().add(null, new HttpCookie("username", "john"));
}
con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));
int status = con.getResponseCode();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenRedirect_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(true);
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
assertEquals("status code incorrect", con.getResponseCode(), 200);
}
}

View File

@ -6,9 +6,10 @@ import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class ConcurrentModificationExceptionTest { public class ConcurrentModificationExceptionTest {
@Test @Test
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception { public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three")); ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));

View File

@ -8,7 +8,9 @@ import java.util.TreeMap;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ConcurrentNavigableMapManualTests { public class ConcurrentNavigableMapManualTests {

View File

@ -0,0 +1,46 @@
package com.baeldung.java.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}

View File

@ -1,24 +1,18 @@
package com.baeldung.java.map; 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; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.Map.Entry;
import static org.junit.Assert.*;
public class MapTest { public class MapTest {
private static final Logger LOG = LoggerFactory.getLogger(MapTest.class);
@Test @Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() { public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
@ -208,22 +202,22 @@ public class MapTest {
MyKey k2 = new MyKey(2, "secondKey"); MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey"); MyKey k3 = new MyKey(2, "thirdKey");
System.out.println("storing value for k1"); LOG.debug("storing value for k1");
map.put(k1, "firstValue"); map.put(k1, "firstValue");
System.out.println("storing value for k2"); LOG.debug("storing value for k2");
map.put(k2, "secondValue"); map.put(k2, "secondValue");
System.out.println("storing value for k3"); LOG.debug("storing value for k3");
map.put(k3, "thirdValue"); map.put(k3, "thirdValue");
System.out.println("retrieving value for k1"); LOG.debug("retrieving value for k1");
String v1 = map.get(k1); String v1 = map.get(k1);
System.out.println("retrieving value for k2"); LOG.debug("retrieving value for k2");
String v2 = map.get(k2); String v2 = map.get(k2);
System.out.println("retrieving value for k3"); LOG.debug("retrieving value for k3");
String v3 = map.get(k3); String v3 = map.get(k3);
assertEquals("firstValue", v1); assertEquals("firstValue", v1);

View File

@ -1,5 +1,8 @@
package com.baeldung.java.nio2.async; package com.baeldung.java.nio2.async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -10,6 +13,8 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
public class AsyncEchoClient { public class AsyncEchoClient {
private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class);
private AsynchronousSocketChannel client; private AsynchronousSocketChannel client;
private Future<Void> future; private Future<Void> future;
private static AsyncEchoClient instance; private static AsyncEchoClient instance;
@ -75,11 +80,11 @@ public class AsyncEchoClient {
client.start(); client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line; String line;
System.out.println("Message to server:"); LOG.debug("Message to server:");
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String response = client.sendMessage(line); String response = client.sendMessage(line);
System.out.println("response from server: " + response); LOG.debug("response from server: " + response);
System.out.println("Message to server:"); LOG.debug("Message to server:");
} }
} }

View File

@ -2,6 +2,8 @@ package com.baeldung.java.nio2.attributes;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -15,6 +17,10 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class BasicAttribsTest { public class BasicAttribsTest {
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsTest.class);
private static final String HOME = System.getProperty("user.home"); private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs; private static BasicFileAttributes basicAttribs;
@ -31,9 +37,9 @@ public class BasicAttribsTest {
FileTime modified = basicAttribs.lastModifiedTime(); FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime(); FileTime accessed = basicAttribs.lastAccessTime();
System.out.println("Created: " + created); LOG.debug("Created: " + created);
System.out.println("Modified: " + modified); LOG.debug("Modified: " + modified);
System.out.println("Accessed: " + accessed); LOG.debug("Accessed: " + accessed);
} }

View File

@ -0,0 +1,57 @@
package com.baeldung.java.reflection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class OperationsUnitTest {
public OperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokePrivateMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method andPrivateMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivateMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception {
Method andPrivatedMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
andPrivatedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivatedMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception {
Method sumInstanceMethod = Operations.class.getMethod("publicSum", int.class, double.class);
Operations operationsInstance = new Operations();
Double result = (Double) sumInstanceMethod.invoke(operationsInstance, 1, 3);
assertThat(result, equalTo(4.0));
}
@Test
public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception {
Method multiplyStaticMethod = Operations.class.getDeclaredMethod("publicStaticMultiply", float.class, long.class);
Double result = (Double) multiplyStaticMethod.invoke(null, 3.5f, 2);
assertThat(result, equalTo(7.0));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.java.reflection.operations;
import com.baeldung.java.reflection.*;
import static org.hamcrest.CoreMatchers.equalTo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
import static org.junit.Assert.assertThat;
public class MoreOperationsUnitTest {
public MoreOperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokeProtectedMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
@Test
public void givenObject_whenInvokeProtectedMethod_thenCorrect() throws Exception {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
maxProtectedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.java.set;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SetTest {
private static final Logger LOG = LoggerFactory.getLogger(SetTest.class);
@Test
public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
assertEquals(3, set.size());
assertTrue(set.iterator()
.next()
.equals("Awesome"));
}
@Test(expected = NullPointerException.class)
public void givenTreeSet_whenAddNullObject_thenNullPointer() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
}
@Test
public void givenHashSet_whenAddNullObject_thenOK() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
assertEquals(3, set.size());
}
@Test
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
long hashSetInsertionTime = measureExecution(() -> {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});
long treeSetInsertionTime = measureExecution(() -> {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});
LOG.debug("HashSet insertion time: {}", hashSetInsertionTime);
LOG.debug("TreeSet insertion time: {}", treeSetInsertionTime);
}
@Test
public void givenHashSetAndTreeSet_whenAddDuplicates_thenOnlyUnique() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("Baeldung");
assertTrue(set.size() == 1);
Set<String> set2 = new TreeSet<>();
set2.add("Baeldung");
set2.add("Baeldung");
assertTrue(set2.size() == 1);
}
@Test(expected = ConcurrentModificationException.class)
public void givenHashSet_whenModifyWhenIterator_thenFailFast() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
set.add("Awesome");
it.next();
}
}
private static long measureExecution(Runnable task) {
long startTime = System.nanoTime();
task.run();
long endTime = System.nanoTime();
long executionTime = endTime - startTime;
LOG.debug(String.valueOf(executionTime));
return executionTime;
}
}

View File

@ -1,13 +1,17 @@
package com.baeldung.java8; package com.baeldung.java8;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.junit.Test;
public class Java8ForEachTest { public class Java8ForEachTest {
private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachTest.class);
@Test @Test
public void compareForEachMethods_thenPrintResults() { public void compareForEachMethods_thenPrintResults() {
@ -19,33 +23,33 @@ public class Java8ForEachTest {
names.add("Ellen"); names.add("Ellen");
// Java 5 - for-loop // Java 5 - for-loop
System.out.println("--- Enhanced for-loop ---"); LOG.debug("--- Enhanced for-loop ---");
for (String name : names) { for (String name : names) {
System.out.println(name); LOG.debug(name);
} }
// Java 8 - forEach // Java 8 - forEach
System.out.println("--- forEach method ---"); LOG.debug("--- forEach method ---");
names.forEach(name -> System.out.println(name)); names.forEach(name -> LOG.debug(name));
// Anonymous inner class that implements Consumer interface // Anonymous inner class that implements Consumer interface
System.out.println("--- Anonymous inner class ---"); LOG.debug("--- Anonymous inner class ---");
names.forEach(new Consumer<String>() { names.forEach(new Consumer<String>() {
public void accept(String name) { public void accept(String name) {
System.out.println(name); LOG.debug(name);
} }
}); });
// Create a Consumer implementation to then use in a forEach method // Create a Consumer implementation to then use in a forEach method
Consumer<String> consumerNames = name -> { Consumer<String> consumerNames = name -> {
System.out.println(name); LOG.debug(name);
}; };
System.out.println("--- Implementation of Consumer interface ---"); LOG.debug("--- Implementation of Consumer interface ---");
names.forEach(consumerNames); names.forEach(consumerNames);
// Print elements using a Method Reference // Print elements using a Method Reference
System.out.println("--- Method Reference ---"); LOG.debug("--- Method Reference ---");
names.forEach(System.out::println); names.forEach(LOG::debug);
} }

Some files were not shown because too many files have changed in this diff Show More