Optimize build and reduce logging (#1772)

* Reduce logging

* Reduce logging

* Reduce logging

* Reduce logging

* Reduce logging

* Optimize build

* Remove testng from core-java
This commit is contained in:
Grzegorz Piwowarek 2017-05-03 09:29:10 +02:00 committed by GitHub
parent c5ddf680a7
commit 6e86dc27ff
60 changed files with 626 additions and 507 deletions

View File

@ -76,6 +76,17 @@
</instrumentation> </instrumentation>
</configuration> </configuration>
</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>
</reporting> </reporting>
</project> </project>

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

@ -1,76 +1,86 @@
package algorithms; package algorithms;
import org.junit.Test; import org.junit.Test;
import com.baeldung.algorithms.ga.dijkstra.Dijkstra; import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
import com.baeldung.algorithms.ga.dijkstra.Graph; import com.baeldung.algorithms.ga.dijkstra.Graph;
import com.baeldung.algorithms.ga.dijkstra.Node; import com.baeldung.algorithms.ga.dijkstra.Node;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; 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() {
Node nodeA = new Node("A"); Node nodeA = new Node("A");
Node nodeB = new Node("B"); Node nodeB = new Node("B");
Node nodeC = new Node("C"); Node nodeC = new Node("C");
Node nodeD = new Node("D"); Node nodeD = new Node("D");
Node nodeE = new Node("E"); Node nodeE = new Node("E");
Node nodeF = new Node("F"); Node nodeF = new Node("F");
nodeA.addDestination(nodeB, 10); nodeA.addDestination(nodeB, 10);
nodeA.addDestination(nodeC, 15); nodeA.addDestination(nodeC, 15);
nodeB.addDestination(nodeD, 12); nodeB.addDestination(nodeD, 12);
nodeB.addDestination(nodeF, 15); nodeB.addDestination(nodeF, 15);
nodeC.addDestination(nodeE, 10); nodeC.addDestination(nodeE, 10);
nodeD.addDestination(nodeE, 2); nodeD.addDestination(nodeE, 2);
nodeD.addDestination(nodeF, 1); nodeD.addDestination(nodeF, 1);
nodeF.addDestination(nodeE, 5); nodeF.addDestination(nodeE, 5);
Graph graph = new Graph(); Graph graph = new Graph();
graph.addNode(nodeA); graph.addNode(nodeA);
graph.addNode(nodeB); graph.addNode(nodeB);
graph.addNode(nodeC); graph.addNode(nodeC);
graph.addNode(nodeD); graph.addNode(nodeD);
graph.addNode(nodeE); graph.addNode(nodeE);
graph.addNode(nodeF); graph.addNode(nodeF);
graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
List<Node> shortestPathForNodeB = Arrays.asList(nodeA); List<Node> shortestPathForNodeB = Arrays.asList(nodeA);
List<Node> shortestPathForNodeC = Arrays.asList(nodeA); List<Node> shortestPathForNodeC = Arrays.asList(nodeA);
List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB); List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
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
break; .getShortestPath()
case "C": .equals(shortestPathForNodeB));
assertTrue(node.getShortestPath().equals(shortestPathForNodeC)); break;
break; case "C":
case "D": assertTrue(node
assertTrue(node.getShortestPath().equals(shortestPathForNodeD)); .getShortestPath()
break; .equals(shortestPathForNodeC));
case "E": break;
assertTrue(node.getShortestPath().equals(shortestPathForNodeE)); case "D":
break; assertTrue(node
case "F": .getShortestPath()
assertTrue(node.getShortestPath().equals(shortestPathForNodeF)); .equals(shortestPathForNodeD));
break; break;
} case "E":
} assertTrue(node
} .getShortestPath()
} .equals(shortestPathForNodeE));
break;
case "F":
assertTrue(node
.getShortestPath()
.equals(shortestPathForNodeF));
break;
}
}
}
}

View File

@ -1,38 +1,37 @@
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());
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
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

@ -135,13 +135,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>

View File

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

View File

@ -1,9 +1,15 @@
package com.baeldung.concurrent.sleepwait; package com.baeldung.concurrent.sleepwait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*** /***
* Example of wait() and sleep() methods * Example of wait() and sleep() methods
*/ */
public class WaitSleepExample { public class WaitSleepExample {
private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class);
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
public static void main(String... args) throws InterruptedException { public static void main(String... args) throws InterruptedException {
@ -12,11 +18,11 @@ public class WaitSleepExample {
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
Thread.sleep(1000); // called on the thread Thread.sleep(1000); // called on the thread
System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
synchronized (LOCK) { synchronized (LOCK) {
LOCK.wait(1000); // called on the object, synchronization required LOCK.wait(1000); // called on the object, synchronization required
System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second"); 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

@ -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

@ -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

@ -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

@ -1,9 +1,15 @@
package com.baeldung.transferqueue; package com.baeldung.transferqueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TransferQueue; import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable { public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue; private final TransferQueue<String> transferQueue;
private final String name; private final String name;
private final int numberOfMessagesToConsume; private final int numberOfMessagesToConsume;
@ -19,10 +25,10 @@ public class Consumer implements Runnable {
public void run() { public void run() {
for (int i = 0; i < numberOfMessagesToConsume; i++) { for (int i = 0; i < numberOfMessagesToConsume; i++) {
try { try {
System.out.println("Consumer: " + name + " is waiting to take element..."); LOG.debug("Consumer: " + name + " is waiting to take element...");
String element = transferQueue.take(); String element = transferQueue.take();
longProcessing(element); longProcessing(element);
System.out.println("Consumer: " + name + " received element: " + element); LOG.debug("Consumer: " + name + " received element: " + element);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

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

View File

@ -1,13 +1,14 @@
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() {
@ -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

@ -5,6 +5,8 @@ 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 java.util.concurrent.*;
@ -13,6 +15,9 @@ import static org.junit.Assert.assertTrue;
public class SquareCalculatorIntegrationTest { public class SquareCalculatorIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class);
@Rule @Rule
public TestName name = new TestName(); public TestName name = new TestName();
@ -28,7 +33,7 @@ public class SquareCalculatorIntegrationTest {
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);
} }
@ -54,7 +59,7 @@ public class SquareCalculatorIntegrationTest {
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);
} }
@ -84,6 +89,6 @@ public class SquareCalculatorIntegrationTest {
@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

@ -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;
@ -11,6 +13,9 @@ import static org.assertj.core.util.Lists.newArrayList;
public class PriorityBlockingQueueIntegrationTest { 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 {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
@ -32,11 +37,11 @@ public class PriorityBlockingQueueIntegrationTest {
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 PriorityBlockingQueueIntegrationTest {
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

@ -7,7 +7,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.testng.Assert.fail; import static org.junit.Assert.fail;
public class DynamicProxyTest { public class DynamicProxyTest {

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

@ -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

@ -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

@ -1,6 +1,8 @@
package com.baeldung.java.set; package com.baeldung.java.set;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
@ -9,6 +11,8 @@ import static org.junit.Assert.assertTrue;
public class SetTest { public class SetTest {
private static final Logger LOG = LoggerFactory.getLogger(SetTest.class);
@Test @Test
public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() { public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() {
Set<String> set = new TreeSet<>(); Set<String> set = new TreeSet<>();
@ -88,7 +92,7 @@ public class SetTest {
task.run(); task.run();
long endTime = System.nanoTime(); long endTime = System.nanoTime();
long executionTime = endTime - startTime; long executionTime = endTime - startTime;
System.out.println(executionTime); LOG.debug(String.valueOf(executionTime));
return 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);
} }

View File

@ -2,6 +2,8 @@ package com.baeldung.java8;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
@ -10,6 +12,9 @@ import java.util.Scanner;
public class JavaTryWithResourcesLongRunningUnitTest { public class JavaTryWithResourcesLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date; private Date resource1Date, resource2Date;
@ -52,32 +57,32 @@ public class JavaTryWithResourcesLongRunningUnitTest {
class AutoCloseableResourcesFirst implements AutoCloseable { class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() { public AutoCloseableResourcesFirst() {
System.out.println("Constructor -> AutoCloseableResources_First"); LOG.debug("Constructor -> AutoCloseableResources_First");
} }
public void doSomething() { public void doSomething() {
System.out.println("Something -> AutoCloseableResources_First"); LOG.debug("Something -> AutoCloseableResources_First");
} }
@Override @Override
public void close() throws Exception { public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_First"); LOG.debug("Closed AutoCloseableResources_First");
resource1Date = new Date(); resource1Date = new Date();
} }
} }
class AutoCloseableResourcesSecond implements AutoCloseable { class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() { public AutoCloseableResourcesSecond() {
System.out.println("Constructor -> AutoCloseableResources_Second"); LOG.debug("Constructor -> AutoCloseableResources_Second");
} }
public void doSomething() { public void doSomething() {
System.out.println("Something -> AutoCloseableResources_Second"); LOG.debug("Something -> AutoCloseableResources_Second");
} }
@Override @Override
public void close() throws Exception { public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_Second"); LOG.debug("Closed AutoCloseableResources_Second");
resource2Date = new Date(); resource2Date = new Date();
Thread.sleep(10000); Thread.sleep(10000);
} }

View File

@ -2,6 +2,8 @@ package com.baeldung.java8.lambda.exceptions;
import org.junit.Before; import org.junit.Before;
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.util.Arrays; import java.util.Arrays;
@ -11,6 +13,9 @@ import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
public class LambdaExceptionWrappersTest { public class LambdaExceptionWrappersTest {
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersTest.class);
private List<Integer> integers; private List<Integer> integers;
@Before @Before
@ -20,12 +25,12 @@ public class LambdaExceptionWrappersTest {
@Test @Test
public void whenNoExceptionFromLambdaWrapper_thenSuccess() { public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i))); integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i)));
} }
@Test @Test
public void whenNoExceptionFromConsumerWrapper_thenSuccess() { public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class)); integers.forEach(consumerWrapper(i -> LOG.debug("{}", 50 / i), ArithmeticException.class));
} }
@Test(expected = RuntimeException.class) @Test(expected = RuntimeException.class)

View File

@ -3,6 +3,8 @@ package com.baeldung.java8.optional;
import com.baeldung.optional.Modem; import com.baeldung.optional.Modem;
import com.baeldung.optional.Person; import com.baeldung.optional.Person;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -12,6 +14,10 @@ import java.util.Optional;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class OptionalTest { public class OptionalTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalTest.class);
// creating Optional // creating Optional
@Test @Test
public void whenCreatesEmptyOptional_thenCorrect() { public void whenCreatesEmptyOptional_thenCorrect() {
@ -66,7 +72,7 @@ public class OptionalTest {
@Test @Test
public void givenOptional_whenIfPresentWorks_thenCorrect() { public void givenOptional_whenIfPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("baeldung"); Optional<String> opt = Optional.of("baeldung");
opt.ifPresent(name -> System.out.println(name.length())); opt.ifPresent(name -> LOG.debug("{}", name.length()));
} }
// returning Value With get() // returning Value With get()
@ -200,11 +206,11 @@ public class OptionalTest {
@Test @Test
public void whenOrElseGetAndOrElseOverlap_thenCorrect() { public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null; String text = null;
System.out.println("Using orElseGet:"); LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText); assertEquals("Default Value", defaultText);
System.out.println("Using orElse:"); LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault()); defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Default Value", defaultText); assertEquals("Default Value", defaultText);
} }
@ -212,11 +218,11 @@ public class OptionalTest {
@Test @Test
public void whenOrElseGetAndOrElseDiffer_thenCorrect() { public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present"; String text = "Text present";
System.out.println("Using orElseGet:"); LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText); assertEquals("Text present", defaultText);
System.out.println("Using orElse:"); LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault()); defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Text present", defaultText); assertEquals("Text present", defaultText);
} }
@ -229,7 +235,7 @@ public class OptionalTest {
} }
public String getMyDefault() { public String getMyDefault() {
System.out.println("Getting default value..."); LOG.debug("Getting default value...");
return "Default Value"; return "Default Value";
} }
} }

View File

@ -3,6 +3,8 @@ package com.baeldung.synchronousqueue;
import org.junit.FixMethodOrder; import org.junit.FixMethodOrder;
import org.junit.Test; import org.junit.Test;
import org.junit.runners.MethodSorters; import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -12,6 +14,9 @@ import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SynchronousQueueTest { public class SynchronousQueueTest {
private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueTest.class);
@Test @Test
public void givenTwoThreads_whenWantToExchangeUsingLockGuardedVariable_thenItSucceed() throws InterruptedException { public void givenTwoThreads_whenWantToExchangeUsingLockGuardedVariable_thenItSucceed() throws InterruptedException {
//given //given
@ -21,7 +26,7 @@ public class SynchronousQueueTest {
Runnable producer = () -> { Runnable producer = () -> {
Integer producedElement = ThreadLocalRandom.current().nextInt(); Integer producedElement = ThreadLocalRandom.current().nextInt();
System.out.println("Saving an element: " + producedElement + " to the exchange point"); LOG.debug("Saving an element: " + producedElement + " to the exchange point");
sharedState.set(producedElement); sharedState.set(producedElement);
countDownLatch.countDown(); countDownLatch.countDown();
}; };
@ -30,7 +35,7 @@ public class SynchronousQueueTest {
try { try {
countDownLatch.await(); countDownLatch.await();
Integer consumedElement = sharedState.get(); Integer consumedElement = sharedState.get();
System.out.println("consumed an element: " + consumedElement + " from the exchange point"); LOG.debug("consumed an element: " + consumedElement + " from the exchange point");
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
@ -55,7 +60,7 @@ public class SynchronousQueueTest {
Runnable producer = () -> { Runnable producer = () -> {
Integer producedElement = ThreadLocalRandom.current().nextInt(); Integer producedElement = ThreadLocalRandom.current().nextInt();
try { try {
System.out.println("Saving an element: " + producedElement + " to the exchange point"); LOG.debug("Saving an element: " + producedElement + " to the exchange point");
queue.put(producedElement); queue.put(producedElement);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
ex.printStackTrace(); ex.printStackTrace();
@ -65,7 +70,7 @@ public class SynchronousQueueTest {
Runnable consumer = () -> { Runnable consumer = () -> {
try { try {
Integer consumedElement = queue.take(); Integer consumedElement = queue.take();
System.out.println("consumed an element: " + consumedElement + " from the exchange point"); LOG.debug("consumed an element: " + consumedElement + " from the exchange point");
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@ -1,24 +1,19 @@
package com.baeldung.threadpool; package com.baeldung.threadpool;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
public class CoreThreadPoolIntegrationTest { public class CoreThreadPoolIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
@Test(timeout = 1000) @Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
@ -26,7 +21,7 @@ public class CoreThreadPoolIntegrationTest {
Executor executor = Executors.newSingleThreadExecutor(); Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> { executor.execute(() -> {
System.out.println("Hello World"); LOG.debug("Hello World");
lock.countDown(); lock.countDown();
}); });
@ -115,7 +110,7 @@ public class CoreThreadPoolIntegrationTest {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(() -> { executor.schedule(() -> {
System.out.println("Hello World"); LOG.debug("Hello World");
lock.countDown(); lock.countDown();
}, 500, TimeUnit.MILLISECONDS); }, 500, TimeUnit.MILLISECONDS);
@ -130,7 +125,7 @@ public class CoreThreadPoolIntegrationTest {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> { ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
System.out.println("Hello World"); LOG.debug("Hello World");
lock.countDown(); lock.countDown();
}, 500, 100, TimeUnit.MILLISECONDS); }, 500, 100, TimeUnit.MILLISECONDS);

View File

@ -1,15 +1,10 @@
package org.baeldung.core.exceptions; package org.baeldung.core.exceptions;
import java.io.BufferedReader; import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.junit.Test; import java.io.*;
public class FileNotFoundExceptionUnitTest { public class FileNotFoundExceptionUnitTest {
@ -22,7 +17,7 @@ public class FileNotFoundExceptionUnitTest {
try { try {
readFailingFile(); readFailingFile();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
throw new BusinessException("BusinessException: necessary file was not present.", ex); throw new BusinessException("BusinessException: necessary file was not present.");
} }
} }
@ -35,7 +30,7 @@ public class FileNotFoundExceptionUnitTest {
new File(fileName).createNewFile(); new File(fileName).createNewFile();
readFailingFile(); readFailingFile();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new RuntimeException("BusinessException: even creation is not possible.", ioe); throw new RuntimeException("BusinessException: even creation is not possible.");
} }
} }
} }
@ -45,7 +40,7 @@ public class FileNotFoundExceptionUnitTest {
try { try {
readFailingFile(); readFailingFile();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOG.error("Optional file " + fileName + " was not found.", ex); LOG.error("Optional file " + fileName + " was not found.");
} }
} }
@ -56,8 +51,8 @@ public class FileNotFoundExceptionUnitTest {
} }
private class BusinessException extends RuntimeException { private class BusinessException extends RuntimeException {
BusinessException(String string, FileNotFoundException ex) { BusinessException(String string) {
super(string, ex); super(string);
} }
} }
} }

View File

@ -3,26 +3,31 @@ package org.baeldung.java;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.commons.math3.random.RandomDataGenerator;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Random; import java.util.Random;
public class JavaRandomUnitTest { public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long // tests - random long
@Test @Test
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() { public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new Random().nextLong(); final long generatedLong = new Random().nextLong();
System.out.println(generatedLong); LOG.debug("{}", generatedLong);
} }
@Test @Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong();
System.out.println(generatedLong); LOG.debug("{}", generatedLong);
} }
@Test @Test
@ -31,7 +36,7 @@ public class JavaRandomUnitTest {
final long rightLimit = 10L; final long rightLimit = 10L;
final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit)); final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
System.out.println(generatedLong); LOG.debug("{}", generatedLong);
} }
@Test @Test
@ -40,7 +45,7 @@ public class JavaRandomUnitTest {
final long rightLimit = 100L; final long rightLimit = 100L;
final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit); final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
System.out.println(generatedLong); LOG.debug("{}", generatedLong);
} }
// tests - random int // tests - random int
@ -49,7 +54,7 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() { public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final int generatedInteger = new Random().nextInt(); final int generatedInteger = new Random().nextInt();
System.out.println(generatedInteger); LOG.debug("{}", generatedInteger);
} }
@Test @Test
@ -58,14 +63,14 @@ public class JavaRandomUnitTest {
final int rightLimit = 10; final int rightLimit = 10;
final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
System.out.println(generatedInteger); LOG.debug("{}", generatedInteger);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt();
System.out.println(generatedInteger); LOG.debug("{}", generatedInteger);
} }
@Test @Test
@ -74,7 +79,7 @@ public class JavaRandomUnitTest {
final int rightLimit = 10; final int rightLimit = 10;
final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit); final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
System.out.println(generatedInteger); LOG.debug("{}", generatedInteger);
} }
// tests - random float // tests - random float
@ -83,14 +88,14 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() { public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
final float generatedFloat = new Random().nextFloat(); final float generatedFloat = new Random().nextFloat();
System.out.println(generatedFloat); LOG.debug("{}", generatedFloat);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
System.out.println(generatedFloat); LOG.debug("{}", generatedFloat);
} }
@Test @Test
@ -99,7 +104,7 @@ public class JavaRandomUnitTest {
final float rightLimit = 10F; final float rightLimit = 10F;
final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit); final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
System.out.println(generatedFloat); LOG.debug("{}", generatedFloat);
} }
@Test @Test
@ -109,7 +114,7 @@ public class JavaRandomUnitTest {
final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
System.out.println(generatedFloat); LOG.debug("{}", generatedFloat);
} }
// tests - random double // tests - random double
@ -118,14 +123,14 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() { public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = Math.random(); final double generatedDouble = Math.random();
System.out.println(generatedDouble); LOG.debug("{}", generatedDouble);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
System.out.println(generatedDouble); LOG.debug("{}", generatedDouble);
} }
@Test @Test
@ -134,7 +139,7 @@ public class JavaRandomUnitTest {
final double rightLimit = 10D; final double rightLimit = 10D;
final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
System.out.println(generatedDouble); LOG.debug("{}", generatedDouble);
} }
@Test @Test
@ -143,7 +148,7 @@ public class JavaRandomUnitTest {
final double rightLimit = 100D; final double rightLimit = 100D;
final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit); final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
System.out.println(generatedDouble); LOG.debug("{}", generatedDouble);
} }
// tests - random String // tests - random String
@ -154,7 +159,7 @@ public class JavaRandomUnitTest {
new Random().nextBytes(array); new Random().nextBytes(array);
final String generatedString = new String(array, Charset.forName("UTF-8")); final String generatedString = new String(array, Charset.forName("UTF-8"));
System.out.println(generatedString); LOG.debug(generatedString);
} }
@Test @Test
@ -169,28 +174,28 @@ public class JavaRandomUnitTest {
} }
final String generatedString = buffer.toString(); final String generatedString = buffer.toString();
System.out.println(generatedString); LOG.debug(generatedString);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
final String generatedString = RandomStringUtils.random(10); final String generatedString = RandomStringUtils.random(10);
System.out.println(generatedString); LOG.debug(generatedString);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphabetic(10); final String generatedString = RandomStringUtils.randomAlphabetic(10);
System.out.println(generatedString); LOG.debug(generatedString);
} }
@Test @Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphanumeric(10); final String generatedString = RandomStringUtils.randomAlphanumeric(10);
System.out.println(generatedString); LOG.debug(generatedString);
} }
@Test @Test
@ -200,7 +205,7 @@ public class JavaRandomUnitTest {
final boolean useNumbers = false; final boolean useNumbers = false;
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
System.out.println(generatedString); LOG.debug(generatedString);
} }
} }

View File

@ -1,5 +1,9 @@
package org.baeldung.java; package org.baeldung.java;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -7,10 +11,11 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class JavaTimerLongRunningUnitTest { public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests // tests
@Test @Test
@ -18,7 +23,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() { final TimerTask timerTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName());
} }
}; };
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
@ -35,7 +40,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() { final TimerTask repeatedTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
} }
}; };
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
@ -53,7 +58,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() { final TimerTask repeatedTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
} }
}; };
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
@ -71,7 +76,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() { final TimerTask task = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
cancel(); cancel();
} }
}; };
@ -89,7 +94,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() { final TimerTask task = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
} }
}; };
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
@ -104,7 +109,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() { final TimerTask task = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
} }
}; };
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
@ -120,7 +125,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() { final TimerTask repeatedTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Task performed on " + new Date()); LOG.debug("Task performed on " + new Date());
} }
}; };
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

View File

@ -1,24 +1,28 @@
package org.baeldung.java.collections; package org.baeldung.java.collections;
import com.google.common.collect.ImmutableList;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class CoreJavaCollectionsUnitTest { public class CoreJavaCollectionsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class);
// tests - // tests -
@Test @Test
public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() { public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three")); final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> synchronizedList = Collections.synchronizedList(list); final List<String> synchronizedList = Collections.synchronizedList(list);
System.out.println("Synchronized List is: " + synchronizedList); LOG.debug("Synchronized List is: " + synchronizedList);
} }
@Test(expected = UnsupportedOperationException.class) @Test(expected = UnsupportedOperationException.class)

View File

@ -1,18 +1,10 @@
package org.baeldung.java.io; package org.baeldung.java.io;
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.io.BufferedReader; import java.io.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.io.StreamTokenizer;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -21,10 +13,14 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Scanner; import java.util.Scanner;
import org.junit.Test; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JavaReadFromFileUnitTest { public class JavaReadFromFileUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
@Test @Test
public void whenReadWithBufferedReader_thenCorrect() throws IOException { public void whenReadWithBufferedReader_thenCorrect() throws IOException {
final String expected_value = "Hello world"; final String expected_value = "Hello world";
@ -115,7 +111,7 @@ public class JavaReadFromFileUnitTest {
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine(); final String currentLine = reader.readLine();
reader.close(); reader.close();
System.out.println(currentLine); LOG.debug(currentLine);
assertEquals(expected_value, currentLine); assertEquals(expected_value, currentLine);
} }

View File

@ -1,11 +1,12 @@
package org.baeldung.java.lists; package org.baeldung.java.lists;
import org.testng.Assert; import org.junit.Test;
import org.testng.annotations.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.junit.Assert.*;
public class ListTestNgUnitTest { public class ListTestNgUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4"); private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
@ -14,8 +15,8 @@ public class ListTestNgUnitTest {
@Test @Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception { public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2); assertEquals(list1, list2);
Assert.assertNotSame(list1, list2); assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3); assertNotEquals(list1, list3);
} }
} }

View File

@ -1,25 +1,30 @@
package org.baeldung.java.sandbox; package org.baeldung.java.sandbox;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import org.junit.Test;
public class SandboxJavaManualTest { public class SandboxJavaManualTest {
private static final Logger LOG = LoggerFactory.getLogger(SandboxJavaManualTest.class);
@Test @Test
public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException {
final TimerTask timerTask = new TimerTask() { final TimerTask timerTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
System.out.println("Time when was task performed" + new Date()); LOG.debug("Time when was task performed" + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
} }
}; };
final Timer timer = new Timer("Thread's name"); final Timer timer = new Timer("Thread's name");
System.out.println("Current time:" + new Date()); LOG.debug("Current time:" + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
final long delay = 2L * 1000L; final long delay = 2L * 1000L;
timer.schedule(timerTask, delay); timer.schedule(timerTask, delay);
Thread.sleep(delay); Thread.sleep(delay);
@ -33,16 +38,16 @@ public class SandboxJavaManualTest {
@Override @Override
public void run() { public void run() {
count++; count++;
System.out.println("Time when task was performed: " + new Date()); LOG.debug("Time when task was performed: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
if (count >= 5) { if (count >= 5) {
cancel(); cancel();
} }
} }
}; };
final Timer timer = new Timer("Timer thread"); final Timer timer = new Timer("Timer thread");
System.out.println("Current time: " + new Date()); LOG.debug("Current time: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
final long delay = 2L * 1000L; final long delay = 2L * 1000L;
final long period = 1L * 1000L; final long period = 1L * 1000L;
timer.scheduleAtFixedRate(repeatedTask, delay, period); timer.scheduleAtFixedRate(repeatedTask, delay, period);
@ -62,8 +67,8 @@ public class SandboxJavaManualTest {
@Override @Override
public void run() { public void run() {
timesRunned++; timesRunned++;
System.out.println("Task performed on: " + new Date()); LOG.debug("Task performed on: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
if (timesRunned >= timesToRun) { if (timesRunned >= timesToRun) {
cancel(); cancel();
} }
@ -72,10 +77,10 @@ public class SandboxJavaManualTest {
final MyTask repeatedTask = new MyTask(); final MyTask repeatedTask = new MyTask();
repeatedTask.setTimesToRun(5); repeatedTask.setTimesToRun(5);
final long delay = 2L * 1000L; final long delay = 2L * 1000L;
final long period = 1L * 1000L; final long period = 1000L;
final Timer timer = new Timer("Timer"); final Timer timer = new Timer("Timer");
System.out.println("Current time: " + new Date()); LOG.debug("Current time: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName()); LOG.debug("Thread's name: " + Thread.currentThread().getName());
timer.scheduleAtFixedRate(repeatedTask, delay, period); timer.scheduleAtFixedRate(repeatedTask, delay, period);
Thread.sleep(delay + period * repeatedTask.timesToRun); Thread.sleep(delay + period * repeatedTask.timesToRun);
} }

View File

@ -77,14 +77,14 @@
<target>${java.target.version}</target> <target>${java.target.version}</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>
<version>${surefire.plugin.version}</version>
<configuration> <configuration>
<includes> <excludes>
<include>**/CalculatorTest.java</include> <exclude>**/*IntegrationTest.java</exclude>
</includes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -11,5 +11,5 @@ import cucumber.api.junit.Cucumber;
, plugin = { "pretty", "json:target/reports/json/calculator.json" } , plugin = { "pretty", "json:target/reports/json/calculator.json" }
, glue = {"com.baeldung.cucumber.calculator"} , glue = {"com.baeldung.cucumber.calculator"}
) )
public class CalculatorTest { public class CalculatorIntegrationTest {
} }

View File

@ -52,6 +52,7 @@
<module>handling-spring-static-resources</module> <module>handling-spring-static-resources</module>
<module>hazelcast</module> <module>hazelcast</module>
<module>hbase</module> <module>hbase</module>
<module>hibernate5</module>
<module>httpclient</module> <module>httpclient</module>
<module>hystrix</module> <module>hystrix</module>
@ -200,7 +201,7 @@
<module>video-tutorials</module> <module>video-tutorials</module>
<module>wicket</module> <!--<module>wicket</module>-->
<module>xml</module> <module>xml</module>
<module>xmlunit2</module> <module>xmlunit2</module>
@ -225,8 +226,6 @@
<version>1.6.0</version> <version>1.6.0</version>
<configuration> <configuration>
<executable>maven</executable> <executable>maven</executable>
<module>hibernate5</module>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>

View File

@ -4,10 +4,10 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.wicket.examples</groupId> <groupId>com.baeldung.wicket.examples</groupId>
<artifactId>wicket-intro</artifactId> <artifactId>wicket</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>WicketIntro</name> <name>Wicket</name>
<properties> <properties>
<wicket.version>7.5.0</wicket.version> <wicket.version>7.5.0</wicket.version>
<jetty9.version>9.2.13.v20150730</jetty9.version> <jetty9.version>9.2.13.v20150730</jetty9.version>
@ -100,6 +100,16 @@
<artifactId>jetty-maven-plugin</artifactId> <artifactId>jetty-maven-plugin</artifactId>
<version>${jetty9.version}</version> <version>${jetty9.version}</version>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>