Resolved merge conflicts

This commit is contained in:
iaforek
2017-05-11 11:00:16 +01:00
2492 changed files with 267395 additions and 3729 deletions
+9
View File
@@ -92,3 +92,12 @@
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
+40 -27
View File
@@ -8,6 +8,12 @@
<name>core-java</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- utils -->
@@ -92,17 +98,19 @@
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- test scoped -->
@@ -140,13 +148,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
@@ -170,13 +171,30 @@
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
@@ -190,7 +208,6 @@
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -200,7 +217,6 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@@ -209,11 +225,11 @@
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
@@ -244,7 +260,6 @@
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
@@ -268,7 +283,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
@@ -289,7 +303,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
@@ -306,7 +319,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
@@ -322,7 +334,6 @@
</execution>
</executions>
</plugin>
</plugins>
</build>
@@ -369,6 +380,9 @@
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- mysql -->
<mysql.version>6.0.6</mysql.version>
<!-- util -->
<guava.version>21.0</guava.version>
@@ -387,7 +401,6 @@
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
@@ -0,0 +1,27 @@
package com.baeldung.concurrent.phaser;
import java.util.concurrent.Phaser;
class LongRunningAction implements Runnable {
private String threadName;
private Phaser ph;
LongRunningAction(String threadName, Phaser ph) {
this.threadName = threadName;
this.ph = ph;
ph.register();
}
@Override
public void run() {
System.out.println("This is phase " + ph.getPhase());
System.out.println("Thread " + threadName + " before long running action");
ph.arriveAndAwaitAdvance();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
ph.arriveAndDeregister();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
public class Event {
private final ZonedDateTime eventTime;
private final String content;
public Event(ZonedDateTime eventTime, String content) {
this.eventTime = eventTime;
this.content = content;
}
public ZonedDateTime getEventTime() {
return eventTime;
}
public String getContent() {
return content;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
import java.util.Comparator;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class EventWindowSort {
private final ConcurrentSkipListMap<ZonedDateTime, String> events
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
public void acceptEvent(Event event) {
events.put(event.getEventTime(), event.getContent());
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
return events.tailMap(ZonedDateTime
.now()
.minusMinutes(1));
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
.now()
.minusMinutes(1));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.concurrent.sleepwait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* Example of waking up a waiting thread
*/
public class ThreadA {
private static final Logger LOG = LoggerFactory.getLogger(ThreadA.class);
private static final ThreadB b = new ThreadB();
public static void main(String... args) throws InterruptedException {
b.start();
synchronized (b) {
while (b.sum == 0) {
LOG.debug("Waiting for ThreadB to complete...");
b.wait();
}
LOG.debug("ThreadB has completed. Sum from that thread is: " + b.sum);
}
}
}
@@ -0,0 +1,20 @@
package com.baeldung.concurrent.sleepwait;
/***
* Example of waking up a waiting thread
*/
class ThreadB extends Thread {
int sum;
@Override
public void run() {
synchronized (this) {
int i = 0;
while (i < 100000) {
sum += i;
i++;
}
notify();
}
}
}
@@ -0,0 +1,29 @@
package com.baeldung.concurrent.sleepwait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* Example of wait() and sleep() methods
*/
public class WaitSleepExample {
private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class);
private static final Object LOCK = new Object();
public static void main(String... args) throws InterruptedException {
sleepWaitInSyncronizedBlocks();
}
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
Thread.sleep(1000); // called on the thread
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
synchronized (LOCK) {
LOCK.wait(1000); // called on the object, synchronization required
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
}
}
}
@@ -1,14 +1,19 @@
package com.baeldung.dirmonitoring;
import java.io.File;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
public static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
@@ -17,17 +22,17 @@ public class DirectoryMonitoringExample {
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
System.out.println("File: " + file.getName() + " created");
LOG.debug("File: " + file.getName() + " created");
}
@Override
public void onFileDelete(File file) {
System.out.println("File: " + file.getName() + " deleted");
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
System.out.println("File: " + file.getName() + " changed");
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
@@ -1,9 +1,14 @@
package com.baeldung.doublecolon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Function;
public class MacbookPro extends Computer {
private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class);
public MacbookPro(int age, String color) {
super(age, color);
}
@@ -14,12 +19,12 @@ public class MacbookPro extends Computer {
@Override
public void turnOnPc() {
System.out.println("MacbookPro turned on");
LOG.debug("MacbookPro turned on");
}
@Override
public void turnOffPc() {
System.out.println("MacbookPro turned off");
LOG.debug("MacbookPro turned off");
}
@Override
@@ -27,7 +32,7 @@ public class MacbookPro extends Computer {
Function<Double, Double> function = super::calculateValue;
final Double pcValue = function.apply(initialValue);
System.out.println("First value is:" + pcValue);
LOG.debug("First value is:" + pcValue);
return pcValue + (initialValue / 10);
}
@@ -0,0 +1,19 @@
package com.baeldung.dynamicproxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.info("Invoked method: {}", method.getName());
return 42;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimingDynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
private final Map<String, Method> methods = new HashMap<>();
private Object target;
public TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
this.methods.put(method.getName(), method);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
Object result = methods.get(method.getName()).invoke(target, args);
long elapsed = System.nanoTime() - start;
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
return result;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}
@@ -0,0 +1,21 @@
package com.baeldung.http;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class ParameterStringBuilder {
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
}
@@ -1,6 +1,11 @@
package com.baeldung.java.map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyKey {
private static final Logger LOG = LoggerFactory.getLogger(MyKey.class);
private String name;
private int id;
@@ -27,7 +32,7 @@ public class MyKey {
@Override
public int hashCode() {
System.out.println("Calling hashCode()");
LOG.debug("Calling hashCode()");
return id;
}
@@ -38,7 +43,7 @@ public class MyKey {
@Override
public boolean equals(Object obj) {
System.out.println("Calling equals() for key: " + obj);
LOG.debug("Calling equals() for key: " + obj);
if (this == obj)
return true;
if (obj == null)
@@ -0,0 +1,21 @@
package com.baeldung.java.reflection;
public class Operations {
public double publicSum(int a, double b) {
return a + b;
}
public static double publicStaticMultiply(float a, long b) {
return a * b;
}
private boolean privateAnd(boolean a, boolean b) {
return a && b;
}
protected int protectedMax(int a, int b) {
return a > b ? a : b;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.jdbc;
public class Employee {
private int id;
private String name;
private String position;
private double salary;
public Employee() {
}
public Employee(int id, String name, double salary, String position) {
this.id = id;
this.name = name;
this.salary = salary;
this.position = position;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
@@ -1,23 +1,28 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Game implements GameMBean {
private static final Logger LOG = LoggerFactory.getLogger(Game.class);
private String playerName;
@Override
public void playFootball(String clubName) {
System.out.println(this.playerName + " playing football for " + clubName);
LOG.debug(this.playerName + " playing football for " + clubName);
}
@Override
public String getPlayerName() {
System.out.println("Return playerName " + this.playerName);
LOG.debug("Return playerName " + this.playerName);
return playerName;
}
@Override
public void setPlayerName(String playerName) {
System.out.println("Set playerName to value " + playerName);
LOG.debug("Set playerName to value " + playerName);
this.playerName = playerName;
}
@@ -1,19 +1,20 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
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 {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This is basic JMX tutorial");
LOG.debug("This is basic JMX tutorial");
ObjectName objectName = null;
try {
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
@@ -27,8 +28,8 @@ public class JMXTutorialMainlauncher {
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
e.printStackTrace();
}
System.out.println("Registration for Game mbean with the platform server is successfull");
System.out.println("Please open jconsole to access Game mbean");
LOG.debug("Registration for Game mbean with the platform server is successfull");
LOG.debug("Please open jconsole to access Game mbean");
while (true) {
// to ensure application does not terminate
}
@@ -1,9 +1,16 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.*;
public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
@@ -14,7 +21,7 @@ public class EchoClient {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
System.out.print(e);
LOG.debug("Error when initializing connection", e);
}
}
@@ -34,7 +41,7 @@ public class EchoClient {
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
LOG.debug("error when closing", e);
}
}
@@ -1,9 +1,15 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class EchoMultiServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private ServerSocket serverSocket;
public void start(int port) {
@@ -57,7 +63,7 @@ public class EchoMultiServer {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
}
@@ -1,9 +1,15 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class EchoServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
@@ -24,7 +30,7 @@ public class EchoServer {
out.println(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
@@ -36,7 +42,7 @@ public class EchoServer {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
@@ -1,5 +1,8 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -7,6 +10,9 @@ import java.io.PrintWriter;
import java.net.Socket;
public class GreetClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
@@ -17,7 +23,7 @@ public class GreetClient {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
@@ -37,7 +43,7 @@ public class GreetClient {
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
@@ -1,9 +1,15 @@
package com.baeldung.socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.io.*;
public class GreetServer {
private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class);
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
@@ -21,7 +27,7 @@ public class GreetServer {
else
out.println("unrecognised greeting");
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
@@ -33,7 +39,7 @@ public class GreetServer {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
LOG.debug(e.getMessage());
}
}
@@ -0,0 +1,8 @@
package com.baeldung.stackoverflowerror;
public class AccountHolder {
private String firstName;
private String lastName;
AccountHolder jointAccountHolder = new AccountHolder();
}
@@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassOne {
private int oneValue;
private ClassTwo clsTwoInstance = null;
public ClassOne() {
oneValue = 0;
clsTwoInstance = new ClassTwo();
}
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
this.oneValue = oneValue;
this.clsTwoInstance = clsTwoInstance;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassTwo {
private int twoValue;
private ClassOne clsOneInstance = null;
public ClassTwo() {
twoValue = 10;
clsOneInstance = new ClassOne();
}
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
this.twoValue = twoValue;
this.clsOneInstance = clsOneInstance;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class InfiniteRecursionWithTerminationCondition {
public int calculateFactorial(final int number) {
return number == 1 ? 1 : number * calculateFactorial(number - 1);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class RecursionWithCorrectTerminationCondition {
public static int calculateFactorial(final int number) {
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {
return number * calculateFactorial(number - 1);
}
}
@@ -1,9 +1,15 @@
package com.baeldung.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Stream;
public class InfiniteStreams {
private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class);
public static void main(String[] args) {
doWhileOldWay();
@@ -15,7 +21,7 @@ public class InfiniteStreams {
int i = 0;
while (i < 10) {
System.out.println(i);
LOG.debug("{}", i);
i++;
}
}
@@ -1,7 +1,11 @@
package com.baeldung.threadlocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadLocalWithUserContext implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalWithUserContext.class);
private static final ThreadLocal<Context> userContext = new ThreadLocal<>();
private final Integer userId;
private UserRepository userRepository = new UserRepository();
@@ -15,6 +19,6 @@ public class ThreadLocalWithUserContext implements Runnable {
public void run() {
String userName = userRepository.getUserNameForUserId(userId);
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());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.transferqueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue;
private final String name;
private final int numberOfMessagesToConsume;
public final AtomicInteger numberOfConsumedMessages = new AtomicInteger();
public Consumer(TransferQueue<String> transferQueue, String name, int numberOfMessagesToConsume) {
this.transferQueue = transferQueue;
this.name = name;
this.numberOfMessagesToConsume = numberOfMessagesToConsume;
}
@Override
public void run() {
for (int i = 0; i < numberOfMessagesToConsume; i++) {
try {
LOG.debug("Consumer: " + name + " is waiting to take element...");
String element = transferQueue.take();
longProcessing(element);
LOG.debug("Consumer: " + name + " received element: " + element);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void longProcessing(String element) throws InterruptedException {
numberOfConsumedMessages.incrementAndGet();
Thread.sleep(500);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.transferqueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Producer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Producer.class);
private final TransferQueue<String> transferQueue;
private final String name;
private final Integer numberOfMessagesToProduce;
public final AtomicInteger numberOfProducedMessages = new AtomicInteger();
public Producer(TransferQueue<String> transferQueue, String name, Integer numberOfMessagesToProduce) {
this.transferQueue = transferQueue;
this.name = name;
this.numberOfMessagesToProduce = numberOfMessagesToProduce;
}
@Override
public void run() {
for (int i = 0; i < numberOfMessagesToProduce; i++) {
try {
LOG.debug("Producer: " + name + " is waiting to transfer...");
boolean added = transferQueue.tryTransfer("A" + i, 4000, TimeUnit.MILLISECONDS);
if (added) {
numberOfProducedMessages.incrementAndGet();
LOG.debug("Producer: " + name + " transferred element: A" + i);
} else {
LOG.debug("can not add an element due to the timeout");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<!-- JDO tutorial "unit" -->
<persistence-unit name="Tutorial">
<exclude-unlisted-classes/>
<properties>
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
<property name="javax.jdo.option.ConnectionPassword" value=""/>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
@@ -1,13 +1,14 @@
package com.baeldung;
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 {
private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class);
@Test
public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
@@ -60,36 +61,36 @@ public class PrimitiveConversionsJUnitTest {
@Test
public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
byte myLargeValueByte = (byte) 130; //0b10000010
System.out.println(myLargeValueByte); //0b10000010 -126
LOG.debug("{}", myLargeValueByte); //0b10000010 -126
assertEquals( -126, myLargeValueByte);
int myLargeValueInt = myLargeValueByte;
System.out.println(myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
assertEquals( -126, myLargeValueInt);
char myLargeValueChar = (char) myLargeValueByte;
System.out.println(myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
assertEquals(0xFF82, myLargeValueChar);
myLargeValueInt = myLargeValueChar;
System.out.println(myLargeValueInt); //0b11111111 10000010 65410
LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410
assertEquals(65410, myLargeValueInt);
byte myOtherByte = (byte) myLargeValueInt;
System.out.println(myOtherByte); //0b10000010 -126
LOG.debug("{}", myOtherByte); //0b10000010 -126
assertEquals( -126, myOtherByte);
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);
int myLargeValueInt2 = myLargeValueChar2;
System.out.println(myLargeValueInt2); //0b00000000 10000010 130
LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130
assertEquals(130, myLargeValueInt2);
byte myOtherByte2 = (byte) myLargeValueInt2;
System.out.println(myOtherByte2); //0b10000010 -126
LOG.debug("{}", myOtherByte2); //0b10000010 -126
assertEquals( -126, myOtherByte2);
}
@@ -1,20 +1,21 @@
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.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 {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class);
@Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync();
@@ -72,7 +73,7 @@ public class CompletableFutureUnitTest {
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
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();
}
@@ -81,7 +82,7 @@ public class CompletableFutureUnitTest {
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
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();
}
@@ -111,7 +112,7 @@ public class CompletableFutureUnitTest {
@Test
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
@@ -0,0 +1,42 @@
package com.baeldung.concurrent.accumulator;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;
import static junit.framework.TestCase.assertEquals;
public class LongAccumulatorTest {
@Test
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(accumulator.get(), 20200);
}
}
@@ -0,0 +1,67 @@
package com.baeldung.concurrent.adder;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
import static com.jayway.awaitility.Awaitility.await;
import static junit.framework.TestCase.assertEquals;
public class LongAdderTest {
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThem() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
}
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThemAndResetAdderAfterward() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sumThenReset(), numberOfIncrements * numberOfThreads);
await().until(() -> assertEquals(counter.sum(), 0));
}
}
@@ -0,0 +1,53 @@
package com.baeldung.concurrent.copyonwrite;
import org.junit.Test;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.assertj.core.api.Assertions.assertThat;
public class CopyOnWriteArrayListTest {
@Test
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
numbers.add(10);
//then
List<Integer> result = new LinkedList<>();
iterator.forEachRemaining(result::add);
assertThat(result).containsOnly(1, 3, 5, 8);
//and
Iterator<Integer> iterator2 = numbers.iterator();
List<Integer> result2 = new LinkedList<>();
iterator2.forEachRemaining(result2::add);
//then
assertThat(result2).containsOnly(1, 3, 5, 8, 10);
}
@Test(expected = UnsupportedOperationException.class)
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
iterator.remove();
}
}
}
@@ -1,22 +1,22 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SquareCalculatorIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class);
public class SquareCalculatorUnitTest {
@Rule
public TestName name = new TestName();
@@ -33,7 +33,7 @@ public class SquareCalculatorUnitTest {
Future<Integer> result2 = squareCalculator.calculate(1000);
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);
}
@@ -59,7 +59,7 @@ public class SquareCalculatorUnitTest {
Future<Integer> result2 = squareCalculator.calculate(1000);
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);
}
@@ -89,6 +89,6 @@ public class SquareCalculatorUnitTest {
@After
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));
}
}
@@ -0,0 +1,41 @@
package com.baeldung.concurrent.phaser;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserTest {
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
ExecutorService executorService = Executors.newCachedThreadPool();
Phaser ph = new Phaser(1);
assertEquals(0, ph.getPhase());
//when
executorService.submit(new LongRunningAction("thread-1", ph));
executorService.submit(new LongRunningAction("thread-2", ph));
executorService.submit(new LongRunningAction("thread-3", ph));
//then
ph.arriveAndAwaitAdvance();
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
ph.arriveAndAwaitAdvance();
assertEquals(2, ph.getPhase());
ph.arriveAndDeregister();
}
}
@@ -1,6 +1,8 @@
package com.baeldung.concurrent.priorityblockingqueue;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue;
@@ -9,7 +11,10 @@ import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.newArrayList;
public class PriorityBlockingQueueUnitTest {
public class PriorityBlockingQueueIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(PriorityBlockingQueueIntegrationTest.class);
@Test
public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException {
@@ -32,11 +37,11 @@ public class PriorityBlockingQueueUnitTest {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
final Thread thread = new Thread(() -> {
System.out.println("Polling...");
LOG.debug("Polling...");
while (true) {
try {
Integer poll = queue.take();
System.out.println("Polled: " + poll);
LOG.debug("Polled: " + poll);
} catch (InterruptedException e) {
}
}
@@ -44,7 +49,7 @@ public class PriorityBlockingQueueUnitTest {
thread.start();
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));
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
@@ -0,0 +1,120 @@
package com.baeldung.concurrent.skiplist;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConcurrentSkipListSetIntegrationTest {
@Test
public void givenThreadsProducingEvents_whenGetForEventsFromLastMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(3);
EventWindowSort eventWindowSort = new EventWindowSort();
int numberOfThreads = 2;
//when
Runnable producer = () -> IntStream
.rangeClosed(0, 100)
.forEach(index -> eventWindowSort.acceptEvent(new Event(ZonedDateTime
.now()
.minusSeconds(index), UUID
.randomUUID()
.toString())));
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(producer);
}
Thread.sleep(500);
ConcurrentNavigableMap<ZonedDateTime, String> eventsFromLastMinute = eventWindowSort.getEventsFromLastMinute();
long eventsOlderThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isBefore(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
assertEquals(eventsOlderThanOneMinute, 0);
long eventYoungerThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isAfter(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
//then
assertTrue(eventYoungerThanOneMinute > 0);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenThreadsProducingEvents_whenGetForEventsOlderThanOneMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException {
//given
ExecutorService executorService = Executors.newFixedThreadPool(3);
EventWindowSort eventWindowSort = new EventWindowSort();
int numberOfThreads = 2;
//when
Runnable producer = () -> IntStream
.rangeClosed(0, 100)
.forEach(index -> eventWindowSort.acceptEvent(new Event(ZonedDateTime
.now()
.minusSeconds(index), UUID
.randomUUID()
.toString())));
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(producer);
}
Thread.sleep(500);
ConcurrentNavigableMap<ZonedDateTime, String> eventsFromLastMinute = eventWindowSort.getEventsOlderThatOneMinute();
long eventsOlderThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isBefore(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
assertTrue(eventsOlderThanOneMinute > 0);
long eventYoungerThanOneMinute = eventsFromLastMinute
.entrySet()
.stream()
.filter(e -> e
.getKey()
.isAfter(ZonedDateTime
.now()
.minusMinutes(1)))
.count();
//then
assertEquals(eventYoungerThanOneMinute, 0);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
}
@@ -0,0 +1,42 @@
package com.baeldung.dateapi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
public class JavaDurationTest {
@Test
public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
Duration duration = Duration.between(start, end);
assertFalse(duration.isNegative());
assertEquals(60, duration.getSeconds());
assertEquals(1, duration.toMinutes());
Duration fromDays = Duration.ofDays(1);
assertEquals(86400, fromDays.getSeconds());
Duration fromMinutes = Duration.ofMinutes(60);
assertEquals(1, fromMinutes.toHours());
assertEquals(120, duration.plusSeconds(60).getSeconds());
assertEquals(30, duration.minusSeconds(30).getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.dateapi;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class JavaPeriodTest {
private static final Logger LOG = Logger.getLogger(JavaPeriodTest.class);
@Test
public void whenTestPeriod_thenOk() {
LocalDate startDate = LocalDate.of(2015, 2, 15);
LocalDate endDate = LocalDate.of(2017, 1, 21);
Period period = Period.between(startDate, endDate);
LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays()));
assertFalse(period.isNegative());
assertEquals(56, period.plusDays(50).getDays());
assertEquals(9, period.minusMonths(2).getMonths());
Period fromUnits = Period.of(3, 10, 10);
Period fromDays = Period.ofDays(50);
Period fromMonths = Period.ofMonths(5);
Period fromYears = Period.ofYears(10);
Period fromWeeks = Period.ofWeeks(40);
assertEquals(280, fromWeeks.getDays());
Period fromCharYears = Period.parse("P2Y");
assertEquals(2, fromCharYears.getYears());
Period fromCharUnits = Period.parse("P2Y3M5D");
assertEquals(5, fromCharUnits.getDays());
}
}
@@ -0,0 +1,57 @@
package com.baeldung.dynamicproxy;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DynamicProxyTest {
@Test
public void givenDynamicProxy_thenPutWorks() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler());
proxyInstance.put("hello", "world");
}
@Test
public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> {
if (method.getName().equals("get")) {
return 42;
} else {
throw new UnsupportedOperationException("Unsupported method: " + method.getName());
}
});
int result = (int) proxyInstance.get("hello");
assertEquals(42, result);
try {
proxyInstance.put("hello", "world");
fail();
} catch(UnsupportedOperationException e) {
// expected
}
}
@Test
public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() {
Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>()));
mapProxyInstance.put("hello", "world");
assertEquals("world", mapProxyInstance.get("hello"));
CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World"));
assertEquals('l', csProxyInstance.charAt(2));
assertEquals(11, csProxyInstance.length());
}
}
@@ -1,8 +1,9 @@
package com.baeldung.functionalinterface;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
@@ -14,12 +15,13 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import com.google.common.util.concurrent.Uninterruptibles;
import static org.junit.Assert.*;
public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
@@ -65,7 +67,7 @@ public class FunctionalInterfaceUnitTest {
@Test
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();
}
@@ -93,7 +95,7 @@ public class FunctionalInterfaceUnitTest {
@Test
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
names.forEach(name -> System.out.println("Hello, " + name));
names.forEach(name -> LOG.debug("Hello, " + name));
}
@Test
@@ -103,7 +105,7 @@ public class FunctionalInterfaceUnitTest {
ages.put("Freddy", 24);
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
@@ -0,0 +1,126 @@
package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class HttpRequestTest {
@Test
public void whenGetRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
assertTrue("content incorrect", content.toString().contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenGetCookies_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
String cookiesHeader = con.getHeaderField("Set-Cookie");
Optional<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));
usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username"));
}
if (usernameCookie == null) {
cookieManager.getCookieStore().add(null, new HttpCookie("username", "john"));
}
con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));
int status = con.getResponseCode();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenRedirect_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(true);
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
assertEquals("status code incorrect", con.getResponseCode(), 200);
}
}
@@ -6,9 +6,10 @@ import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals;
import static org.junit.Assert.assertEquals;
public class ConcurrentModificationExceptionTest {
@Test
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));
@@ -8,7 +8,9 @@ import java.util.TreeMap;
import java.util.concurrent.*;
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 {
@@ -0,0 +1,46 @@
package com.baeldung.java.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}
@@ -1,24 +1,18 @@
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.Map.Entry;
import static org.junit.Assert.*;
public class MapTest {
private static final Logger LOG = LoggerFactory.getLogger(MapTest.class);
@Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>();
@@ -208,22 +202,22 @@ public class MapTest {
MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey");
System.out.println("storing value for k1");
LOG.debug("storing value for k1");
map.put(k1, "firstValue");
System.out.println("storing value for k2");
LOG.debug("storing value for k2");
map.put(k2, "secondValue");
System.out.println("storing value for k3");
LOG.debug("storing value for k3");
map.put(k3, "thirdValue");
System.out.println("retrieving value for k1");
LOG.debug("retrieving value for k1");
String v1 = map.get(k1);
System.out.println("retrieving value for k2");
LOG.debug("retrieving value for k2");
String v2 = map.get(k2);
System.out.println("retrieving value for k3");
LOG.debug("retrieving value for k3");
String v3 = map.get(k3);
assertEquals("firstValue", v1);
@@ -1,5 +1,8 @@
package com.baeldung.java.nio2.async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -10,6 +13,8 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoClient {
private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class);
private AsynchronousSocketChannel client;
private Future<Void> future;
private static AsyncEchoClient instance;
@@ -75,11 +80,11 @@ public class AsyncEchoClient {
client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.println("Message to server:");
LOG.debug("Message to server:");
while ((line = br.readLine()) != null) {
String response = client.sendMessage(line);
System.out.println("response from server: " + response);
System.out.println("Message to server:");
LOG.debug("response from server: " + response);
LOG.debug("Message to server:");
}
}
@@ -2,6 +2,8 @@ package com.baeldung.java.nio2.attributes;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
@@ -15,6 +17,10 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BasicAttribsTest {
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsTest.class);
private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs;
@@ -31,9 +37,9 @@ public class BasicAttribsTest {
FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime();
System.out.println("Created: " + created);
System.out.println("Modified: " + modified);
System.out.println("Accessed: " + accessed);
LOG.debug("Created: " + created);
LOG.debug("Modified: " + modified);
LOG.debug("Accessed: " + accessed);
}
@@ -0,0 +1,57 @@
package com.baeldung.java.reflection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class OperationsUnitTest {
public OperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokePrivateMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method andPrivateMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivateMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception {
Method andPrivatedMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
andPrivatedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivatedMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception {
Method sumInstanceMethod = Operations.class.getMethod("publicSum", int.class, double.class);
Operations operationsInstance = new Operations();
Double result = (Double) sumInstanceMethod.invoke(operationsInstance, 1, 3);
assertThat(result, equalTo(4.0));
}
@Test
public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception {
Method multiplyStaticMethod = Operations.class.getDeclaredMethod("publicStaticMultiply", float.class, long.class);
Double result = (Double) multiplyStaticMethod.invoke(null, 3.5f, 2);
assertThat(result, equalTo(7.0));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.java.reflection.operations;
import com.baeldung.java.reflection.*;
import static org.hamcrest.CoreMatchers.equalTo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
import static org.junit.Assert.assertThat;
public class MoreOperationsUnitTest {
public MoreOperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokeProtectedMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
@Test
public void givenObject_whenInvokeProtectedMethod_thenCorrect() throws Exception {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
maxProtectedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
}
@@ -0,0 +1,99 @@
package com.baeldung.java.set;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SetTest {
private static final Logger LOG = LoggerFactory.getLogger(SetTest.class);
@Test
public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
assertEquals(3, set.size());
assertTrue(set.iterator()
.next()
.equals("Awesome"));
}
@Test(expected = NullPointerException.class)
public void givenTreeSet_whenAddNullObject_thenNullPointer() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
}
@Test
public void givenHashSet_whenAddNullObject_thenOK() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
assertEquals(3, set.size());
}
@Test
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
long hashSetInsertionTime = measureExecution(() -> {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});
long treeSetInsertionTime = measureExecution(() -> {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});
LOG.debug("HashSet insertion time: {}", hashSetInsertionTime);
LOG.debug("TreeSet insertion time: {}", treeSetInsertionTime);
}
@Test
public void givenHashSetAndTreeSet_whenAddDuplicates_thenOnlyUnique() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("Baeldung");
assertTrue(set.size() == 1);
Set<String> set2 = new TreeSet<>();
set2.add("Baeldung");
set2.add("Baeldung");
assertTrue(set2.size() == 1);
}
@Test(expected = ConcurrentModificationException.class)
public void givenHashSet_whenModifyWhenIterator_thenFailFast() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
set.add("Awesome");
it.next();
}
}
private static long measureExecution(Runnable task) {
long startTime = System.nanoTime();
task.run();
long endTime = System.nanoTime();
long executionTime = endTime - startTime;
LOG.debug(String.valueOf(executionTime));
return executionTime;
}
}
@@ -1,13 +1,17 @@
package com.baeldung.java8;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.junit.Test;
public class Java8ForEachTest {
private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachTest.class);
@Test
public void compareForEachMethods_thenPrintResults() {
@@ -19,33 +23,33 @@ public class Java8ForEachTest {
names.add("Ellen");
// Java 5 - for-loop
System.out.println("--- Enhanced for-loop ---");
LOG.debug("--- Enhanced for-loop ---");
for (String name : names) {
System.out.println(name);
LOG.debug(name);
}
// Java 8 - forEach
System.out.println("--- forEach method ---");
names.forEach(name -> System.out.println(name));
LOG.debug("--- forEach method ---");
names.forEach(name -> LOG.debug(name));
// Anonymous inner class that implements Consumer interface
System.out.println("--- Anonymous inner class ---");
LOG.debug("--- Anonymous inner class ---");
names.forEach(new Consumer<String>() {
public void accept(String name) {
System.out.println(name);
LOG.debug(name);
}
});
// Create a Consumer implementation to then use in a forEach method
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);
// Print elements using a Method Reference
System.out.println("--- Method Reference ---");
names.forEach(System.out::println);
LOG.debug("--- Method Reference ---");
names.forEach(LOG::debug);
}
@@ -2,6 +2,8 @@ package com.baeldung.java8;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -10,6 +12,9 @@ import java.util.Scanner;
public class JavaTryWithResourcesLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;
@@ -52,32 +57,32 @@ public class JavaTryWithResourcesLongRunningUnitTest {
class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
System.out.println("Constructor -> AutoCloseableResources_First");
LOG.debug("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_First");
LOG.debug("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_First");
LOG.debug("Closed AutoCloseableResources_First");
resource1Date = new Date();
}
}
class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
System.out.println("Constructor -> AutoCloseableResources_Second");
LOG.debug("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_Second");
LOG.debug("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_Second");
LOG.debug("Closed AutoCloseableResources_Second");
resource2Date = new Date();
Thread.sleep(10000);
}
@@ -1,5 +1,4 @@
package com.baeldung.java8.comparator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -15,9 +14,9 @@ public class Employee implements Comparable<Employee>{
double salary;
long mobile;
@Override
public int compareTo(Employee argEmployee) {
return name.compareTo(argEmployee.getName());
}
}
@@ -1,5 +1,4 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
@@ -164,4 +163,3 @@ public class Java8ComparatorTest {
}
@@ -2,6 +2,8 @@ package com.baeldung.java8.lambda.exceptions;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
@@ -11,6 +13,9 @@ import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
public class LambdaExceptionWrappersTest {
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersTest.class);
private List<Integer> integers;
@Before
@@ -20,12 +25,12 @@ public class LambdaExceptionWrappersTest {
@Test
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i)));
}
@Test
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)
@@ -3,6 +3,8 @@ package com.baeldung.java8.optional;
import com.baeldung.optional.Modem;
import com.baeldung.optional.Person;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
@@ -12,6 +14,10 @@ import java.util.Optional;
import static org.junit.Assert.*;
public class OptionalTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalTest.class);
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
@@ -66,7 +72,7 @@ public class OptionalTest {
@Test
public void givenOptional_whenIfPresentWorks_thenCorrect() {
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()
@@ -200,11 +206,11 @@ public class OptionalTest {
@Test
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
System.out.println("Using orElseGet:");
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
System.out.println("Using orElse:");
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@@ -212,11 +218,11 @@ public class OptionalTest {
@Test
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
System.out.println("Using orElseGet:");
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
System.out.println("Using orElse:");
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
@@ -229,7 +235,7 @@ public class OptionalTest {
}
public String getMyDefault() {
System.out.println("Getting default value...");
LOG.debug("Getting default value...");
return "Default Value";
}
}
@@ -0,0 +1,158 @@
package com.baeldung.jdbc;
import static org.junit.Assert.*;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JdbcTest {
private static final Logger LOG = Logger.getLogger(JdbcTest.class);
private Connection con;
@Before
public void setup() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass");
Statement stmt = con.createStatement();
String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)";
stmt.execute(tableSql);
}
@Test
public void whenInsertUpdateRecord_thenCorrect() throws SQLException {
Statement stmt = con.createStatement();
String insertSql = "INSERT INTO employees(name, position, salary) values ('john', 'developer', 2000)";
stmt.executeUpdate(insertSql);
String selectSql = "SELECT * FROM employees";
ResultSet resultSet = stmt.executeQuery(selectSql);
List<Employee> employees = new ArrayList<>();
while (resultSet.next()) {
Employee emp = new Employee();
emp.setId(resultSet.getInt("emp_id"));
emp.setName(resultSet.getString("name"));
emp.setSalary(resultSet.getDouble("salary"));
emp.setPosition(resultSet.getString("position"));
employees.add(emp);
}
assertEquals("employees list size incorrect", 1, employees.size());
assertEquals("name incorrect", "john", employees.iterator().next().getName());
assertEquals("position incorrect", "developer", employees.iterator().next().getPosition());
assertEquals("salary incorrect", 2000, employees.iterator().next().getSalary(), 0.1);
Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet updatableResultSet = updatableStmt.executeQuery(selectSql);
updatableResultSet.moveToInsertRow();
updatableResultSet.updateString("name", "mark");
updatableResultSet.updateString("position", "analyst");
updatableResultSet.updateDouble("salary", 2000);
updatableResultSet.insertRow();
String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?";
PreparedStatement pstmt = con.prepareStatement(updatePositionSql);
pstmt.setString(1, "lead developer");
pstmt.setInt(2, 1);
String updateSalarySql = "UPDATE employees SET salary=? WHERE emp_id=?";
PreparedStatement pstmt2 = con.prepareStatement(updateSalarySql);
pstmt.setDouble(1, 3000);
pstmt.setInt(2, 1);
boolean autoCommit = con.getAutoCommit();
try {
con.setAutoCommit(false);
pstmt.executeUpdate();
pstmt2.executeUpdate();
con.commit();
} catch (SQLException exc) {
con.rollback();
} finally {
con.setAutoCommit(autoCommit);
}
}
@Test
public void whenCallProcedure_thenCorrect() {
try {
String preparedSql = "{call insertEmployee(?,?,?,?)}";
CallableStatement cstmt = con.prepareCall(preparedSql);
cstmt.setString(2, "ana");
cstmt.setString(3, "tester");
cstmt.setDouble(4, 2000);
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.execute();
int new_id = cstmt.getInt(1);
assertTrue(new_id > 0);
} catch (SQLException exc) {
LOG.error("Procedure incorrect or does not exist!");
}
}
@Test
public void whenReadMetadata_thenCorrect() throws SQLException {
DatabaseMetaData dbmd = con.getMetaData();
ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null);
while (tablesResultSet.next()) {
LOG.info(tablesResultSet.getString("TABLE_NAME"));
}
String selectSql = "SELECT * FROM employees";
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery(selectSql);
ResultSetMetaData rsmd = resultSet.getMetaData();
int nrColumns = rsmd.getColumnCount();
assertEquals(nrColumns, 4);
IntStream.range(1, nrColumns).forEach(i -> {
try {
LOG.info(rsmd.getColumnName(i));
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@After
public void closeConnection() throws SQLException {
Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet updatableResultSet = updatableStmt.executeQuery("SELECT * FROM employees");
while (updatableResultSet.next()) {
updatableResultSet.deleteRow();
}
con.close();
}
}
@@ -0,0 +1,68 @@
package com.baeldung.mappedbytebuffer;
import org.junit.Test;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MappedByteBufferTest {
@Test
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
//given
CharBuffer charBuffer = null;
Path pathToRead = getFileURIFromResources("fileToRead.txt");
//when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
if (mappedByteBuffer != null) {
charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer);
}
}
//then
assertNotNull(charBuffer);
assertEquals(charBuffer.toString(), "This is a content of the file");
}
@Test
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
//given
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
//when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer));
}
}
//then
List<String> fileContent = Files.readAllLines(pathToWrite);
assertEquals(fileContent.get(0), "This will be written to the file");
}
public Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).getPath());
}
}
@@ -0,0 +1,10 @@
package com.baeldung.stackoverflowerror;
import org.junit.Test;
public class AccountHolderUnitTest {
@Test(expected = StackOverflowError.class)
public void whenInstanciatingAccountHolder_thenThrowsException() {
AccountHolder holder = new AccountHolder();
}
}
@@ -0,0 +1,17 @@
package com.baeldung.stackoverflowerror;
import static org.junit.Assert.fail;
import org.junit.Test;
public class CyclicDependancyUnitTest {
@Test
public void whenInstanciatingClassOne_thenThrowsException() {
try {
ClassOne obj = new ClassOne();
fail();
} catch (StackOverflowError soe) {
soe.printStackTrace();
}
}
}
@@ -0,0 +1,37 @@
package com.baeldung.stackoverflowerror;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
public class InfiniteRecursionWithTerminationConditionUnitTest {
@Test
public void givenPositiveIntNoOne_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = 1;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
assertEquals(1, irtc.calculateFactorial(numToCalcFactorial));
}
@Test
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = 5;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
assertEquals(120, irtc.calculateFactorial(numToCalcFactorial));
}
@Test
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
try {
int numToCalcFactorial = -1;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
irtc.calculateFactorial(numToCalcFactorial);
fail();
} catch (StackOverflowError soe) {
soe.printStackTrace();
}
}
}
@@ -0,0 +1,29 @@
package com.baeldung.stackoverflowerror;
import org.junit.Test;
public class UnintendedInfiniteRecursionUnitTest {
@Test(expected = StackOverflowError.class)
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
int numToCalcFactorial = 1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
@Test(expected = StackOverflowError.class)
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = 2;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
@Test(expected = StackOverflowError.class)
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = -1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.string;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
public class SplitTest {
@Test
public void givenString_whenSplit_thenRetrunsArray_through_JavaLangString() {
assertArrayEquals("split by comma", Arrays.asList("peter", "james", "thomas").toArray(), "peter,james,thomas".split(","));
assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), "car jeep scooter".split(" "));
assertArrayEquals("split by hyphen", Arrays.asList("1", "120", "232323").toArray(), "1-120-232323".split("-"));
assertArrayEquals("split by dot", Arrays.asList("192", "168", "1", "178").toArray(), "192.168.1.178".split("\\."));
assertArrayEquals("split by a regex", Arrays.asList("b", "a", "e", "l", "d", "u", "n", "g").toArray(),
"b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*"));
}
@Test
public void givenString_whenSplit_thenRetrunsArray_through_StringUtils() {
StringUtils.split("car jeep scooter");
assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car jeep scooter"));
assertArrayEquals("split by space, extra spaces ignored", Arrays.asList("car", "jeep", "scooter").toArray(),
StringUtils.split("car jeep scooter"));
assertArrayEquals("split by colon", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car:jeep:scooter", ":"));
assertArrayEquals("split by dot", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car.jeep.scooter", "."));
}
}
@@ -0,0 +1,88 @@
package com.baeldung.synchronousqueue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SynchronousQueueTest {
private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueTest.class);
@Test
public void givenTwoThreads_whenWantToExchangeUsingLockGuardedVariable_thenItSucceed() throws InterruptedException {
//given
ExecutorService executor = Executors.newFixedThreadPool(2);
AtomicInteger sharedState = new AtomicInteger();
CountDownLatch countDownLatch = new CountDownLatch(1);
Runnable producer = () -> {
Integer producedElement = ThreadLocalRandom.current().nextInt();
LOG.debug("Saving an element: " + producedElement + " to the exchange point");
sharedState.set(producedElement);
countDownLatch.countDown();
};
Runnable consumer = () -> {
try {
countDownLatch.await();
Integer consumedElement = sharedState.get();
LOG.debug("consumed an element: " + consumedElement + " from the exchange point");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
};
//when
executor.execute(producer);
executor.execute(consumer);
//then
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
executor.shutdown();
assertEquals(countDownLatch.getCount(), 0);
}
@Test
public void givenTwoThreads_whenWantToExchangeUsingSynchronousQueue_thenItSucceed() throws InterruptedException {
//given
ExecutorService executor = Executors.newFixedThreadPool(2);
final SynchronousQueue<Integer> queue = new SynchronousQueue<>();
Runnable producer = () -> {
Integer producedElement = ThreadLocalRandom.current().nextInt();
try {
LOG.debug("Saving an element: " + producedElement + " to the exchange point");
queue.put(producedElement);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
};
Runnable consumer = () -> {
try {
Integer consumedElement = queue.take();
LOG.debug("consumed an element: " + consumedElement + " from the exchange point");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
};
//when
executor.execute(producer);
executor.execute(consumer);
//then
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
executor.shutdown();
assertEquals(queue.size(), 0);
}
}
@@ -7,7 +7,7 @@ import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertEquals;
public class ThreadLocalTest {
public class ThreadLocalIntegrationTest {
@Test
public void givenThreadThatStoresContextInAMap_whenStartThread_thenShouldSetContextForBothUsers() throws ExecutionException, InterruptedException {
//when
@@ -1,24 +1,19 @@
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 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 {
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
@Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
@@ -26,7 +21,7 @@ public class CoreThreadPoolIntegrationTest {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
System.out.println("Hello World");
LOG.debug("Hello World");
lock.countDown();
});
@@ -115,7 +110,7 @@ public class CoreThreadPoolIntegrationTest {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(() -> {
System.out.println("Hello World");
LOG.debug("Hello World");
lock.countDown();
}, 500, TimeUnit.MILLISECONDS);
@@ -130,7 +125,7 @@ public class CoreThreadPoolIntegrationTest {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
System.out.println("Hello World");
LOG.debug("Hello World");
lock.countDown();
}, 500, 100, TimeUnit.MILLISECONDS);
@@ -0,0 +1,74 @@
package com.baeldung.transferqueue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.*;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TransferQueueIntegrationTest {
@Test
public void whenMultipleConsumersAndProducers_thenProcessAllMessages() throws InterruptedException {
//given
TransferQueue<String> transferQueue = new LinkedTransferQueue<>();
ExecutorService exService = Executors.newFixedThreadPool(3);
Producer producer1 = new Producer(transferQueue, "1", 3);
Producer producer2 = new Producer(transferQueue, "2", 3);
Consumer consumer1 = new Consumer(transferQueue, "1", 3);
Consumer consumer2 = new Consumer(transferQueue, "2", 3);
//when
exService.execute(producer1);
exService.execute(producer2);
exService.execute(consumer1);
exService.execute(consumer2);
//then
exService.awaitTermination(5000, TimeUnit.MILLISECONDS);
exService.shutdown();
assertEquals(producer1.numberOfProducedMessages.intValue(), 3);
assertEquals(producer2.numberOfProducedMessages.intValue(), 3);
}
@Test
public void whenUseOneConsumerAndOneProducer_thenShouldProcessAllMessages() throws InterruptedException {
//given
TransferQueue<String> transferQueue = new LinkedTransferQueue<>();
ExecutorService exService = Executors.newFixedThreadPool(2);
Producer producer = new Producer(transferQueue, "1", 3);
Consumer consumer = new Consumer(transferQueue, "1", 3);
//when
exService.execute(producer);
exService.execute(consumer);
//then
exService.awaitTermination(5000, TimeUnit.MILLISECONDS);
exService.shutdown();
assertEquals(producer.numberOfProducedMessages.intValue(), 3);
assertEquals(consumer.numberOfConsumedMessages.intValue(), 3);
}
@Test
public void whenUseOneProducerAndNoConsumers_thenShouldFailWithTimeout() throws InterruptedException {
//given
TransferQueue<String> transferQueue = new LinkedTransferQueue<>();
ExecutorService exService = Executors.newFixedThreadPool(2);
Producer producer = new Producer(transferQueue, "1", 3);
//when
exService.execute(producer);
//then
exService.awaitTermination(5000, TimeUnit.MILLISECONDS);
exService.shutdown();
assertEquals(producer.numberOfProducedMessages.intValue(), 0);
}
}
@@ -1,17 +1,14 @@
package org.baeldung.core.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FileNotFoundExceptionUnitTest {
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class);
private static final Logger LOG = LoggerFactory.getLogger(FileNotFoundExceptionUnitTest.class);
private String fileName = Double.toString(Math.random());
@@ -20,7 +17,7 @@ public class FileNotFoundExceptionUnitTest {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
throw new BusinessException("BusinessException: necessary file was not present.", ex);
throw new BusinessException("BusinessException: necessary file was not present.");
}
}
@@ -33,7 +30,7 @@ public class FileNotFoundExceptionUnitTest {
new File(fileName).createNewFile();
readFailingFile();
} catch (IOException ioe) {
throw new RuntimeException("BusinessException: even creation is not possible.", ioe);
throw new RuntimeException("BusinessException: even creation is not possible.");
}
}
}
@@ -43,7 +40,7 @@ public class FileNotFoundExceptionUnitTest {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
LOG.error("Optional file " + fileName + " was not found.", ex);
LOG.error("Optional file " + fileName + " was not found.");
}
}
@@ -54,8 +51,8 @@ public class FileNotFoundExceptionUnitTest {
}
private class BusinessException extends RuntimeException {
BusinessException(String string, FileNotFoundException ex) {
super(string, ex);
BusinessException(String string) {
super(string);
}
}
}
@@ -3,26 +3,31 @@ package org.baeldung.java;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.Random;
public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long
@Test
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new Random().nextLong();
System.out.println(generatedLong);
LOG.debug("{}", generatedLong);
}
@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong();
System.out.println(generatedLong);
LOG.debug("{}", generatedLong);
}
@Test
@@ -31,7 +36,7 @@ public class JavaRandomUnitTest {
final long rightLimit = 10L;
final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
System.out.println(generatedLong);
LOG.debug("{}", generatedLong);
}
@Test
@@ -40,7 +45,7 @@ public class JavaRandomUnitTest {
final long rightLimit = 100L;
final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
System.out.println(generatedLong);
LOG.debug("{}", generatedLong);
}
// tests - random int
@@ -49,7 +54,7 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final int generatedInteger = new Random().nextInt();
System.out.println(generatedInteger);
LOG.debug("{}", generatedInteger);
}
@Test
@@ -58,14 +63,14 @@ public class JavaRandomUnitTest {
final int rightLimit = 10;
final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
System.out.println(generatedInteger);
LOG.debug("{}", generatedInteger);
}
@Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt();
System.out.println(generatedInteger);
LOG.debug("{}", generatedInteger);
}
@Test
@@ -74,7 +79,7 @@ public class JavaRandomUnitTest {
final int rightLimit = 10;
final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
System.out.println(generatedInteger);
LOG.debug("{}", generatedInteger);
}
// tests - random float
@@ -83,14 +88,14 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
final float generatedFloat = new Random().nextFloat();
System.out.println(generatedFloat);
LOG.debug("{}", generatedFloat);
}
@Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
System.out.println(generatedFloat);
LOG.debug("{}", generatedFloat);
}
@Test
@@ -99,7 +104,7 @@ public class JavaRandomUnitTest {
final float rightLimit = 10F;
final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
System.out.println(generatedFloat);
LOG.debug("{}", generatedFloat);
}
@Test
@@ -109,7 +114,7 @@ public class JavaRandomUnitTest {
final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
System.out.println(generatedFloat);
LOG.debug("{}", generatedFloat);
}
// tests - random double
@@ -118,14 +123,14 @@ public class JavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = Math.random();
System.out.println(generatedDouble);
LOG.debug("{}", generatedDouble);
}
@Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
System.out.println(generatedDouble);
LOG.debug("{}", generatedDouble);
}
@Test
@@ -134,7 +139,7 @@ public class JavaRandomUnitTest {
final double rightLimit = 10D;
final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
System.out.println(generatedDouble);
LOG.debug("{}", generatedDouble);
}
@Test
@@ -143,7 +148,7 @@ public class JavaRandomUnitTest {
final double rightLimit = 100D;
final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
System.out.println(generatedDouble);
LOG.debug("{}", generatedDouble);
}
// tests - random String
@@ -154,7 +159,7 @@ public class JavaRandomUnitTest {
new Random().nextBytes(array);
final String generatedString = new String(array, Charset.forName("UTF-8"));
System.out.println(generatedString);
LOG.debug(generatedString);
}
@Test
@@ -169,28 +174,28 @@ public class JavaRandomUnitTest {
}
final String generatedString = buffer.toString();
System.out.println(generatedString);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
final String generatedString = RandomStringUtils.random(10);
System.out.println(generatedString);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphabetic(10);
System.out.println(generatedString);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
System.out.println(generatedString);
LOG.debug(generatedString);
}
@Test
@@ -200,7 +205,7 @@ public class JavaRandomUnitTest {
final boolean useNumbers = false;
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
System.out.println(generatedString);
LOG.debug(generatedString);
}
}
@@ -1,5 +1,9 @@
package org.baeldung.java;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
@@ -7,10 +11,11 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests
@Test
@@ -18,7 +23,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() {
@Override
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");
@@ -35,7 +40,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
}
};
final Timer timer = new Timer("Timer");
@@ -53,7 +58,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
}
};
final Timer timer = new Timer("Timer");
@@ -71,7 +76,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
cancel();
}
};
@@ -89,7 +94,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
}
};
final Timer timer = new Timer("Timer");
@@ -104,7 +109,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
}
};
final Timer timer = new Timer("Timer");
@@ -120,7 +125,7 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask repeatedTask = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
LOG.debug("Task performed on " + new Date());
}
};
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
@@ -1,24 +1,28 @@
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.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class CoreJavaCollectionsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class);
// tests -
@Test
public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> synchronizedList = Collections.synchronizedList(list);
System.out.println("Synchronized List is: " + synchronizedList);
LOG.debug("Synchronized List is: " + synchronizedList);
}
@Test(expected = UnsupportedOperationException.class)
@@ -1,18 +1,10 @@
package org.baeldung.java.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
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.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
@@ -21,10 +13,14 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JavaReadFromFileUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
@Test
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
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 String currentLine = reader.readLine();
reader.close();
System.out.println(currentLine);
LOG.debug(currentLine);
assertEquals(expected_value, currentLine);
}
@@ -1,11 +1,12 @@
package org.baeldung.java.lists;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class ListTestNgUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
@@ -14,8 +15,8 @@ public class ListTestNgUnitTest {
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2);
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
assertEquals(list1, list2);
assertNotSame(list1, list2);
assertNotEquals(list1, list3);
}
}
@@ -1,25 +1,30 @@
package org.baeldung.java.sandbox;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.junit.Test;
public class SandboxJavaManualTest {
private static final Logger LOG = LoggerFactory.getLogger(SandboxJavaManualTest.class);
@Test
public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Time when was task performed" + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Time when was task performed" + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
}
};
final Timer timer = new Timer("Thread's name");
System.out.println("Current time:" + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Current time:" + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
final long delay = 2L * 1000L;
timer.schedule(timerTask, delay);
Thread.sleep(delay);
@@ -33,16 +38,16 @@ public class SandboxJavaManualTest {
@Override
public void run() {
count++;
System.out.println("Time when task was performed: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Time when task was performed: " + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
if (count >= 5) {
cancel();
}
}
};
final Timer timer = new Timer("Timer thread");
System.out.println("Current time: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Current time: " + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
final long delay = 2L * 1000L;
final long period = 1L * 1000L;
timer.scheduleAtFixedRate(repeatedTask, delay, period);
@@ -62,8 +67,8 @@ public class SandboxJavaManualTest {
@Override
public void run() {
timesRunned++;
System.out.println("Task performed on: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Task performed on: " + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
if (timesRunned >= timesToRun) {
cancel();
}
@@ -72,10 +77,10 @@ public class SandboxJavaManualTest {
final MyTask repeatedTask = new MyTask();
repeatedTask.setTimesToRun(5);
final long delay = 2L * 1000L;
final long period = 1L * 1000L;
final long period = 1000L;
final Timer timer = new Timer("Timer");
System.out.println("Current time: " + new Date());
System.out.println("Thread's name: " + Thread.currentThread().getName());
LOG.debug("Current time: " + new Date());
LOG.debug("Thread's name: " + Thread.currentThread().getName());
timer.scheduleAtFixedRate(repeatedTask, delay, period);
Thread.sleep(delay + period * repeatedTask.timesToRun);
}
@@ -25,12 +25,7 @@ public class JavaProcessUnitIntegrationTest {
}
}
private Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
Assert.assertNotNull(s);
}
};
private Consumer<String> consumer = Assert::assertNotNull;
private String homeDirectory = System.getProperty("user.home");
@@ -0,0 +1 @@
This is a content of the file