list = new ArrayList<>();
+
+ public void populateList() {
+ for (int i = 0; i < 10000000; i++) {
+ list.add(Math.random());
+ }
+ System.out.println("Debug Point 2");
+ }
+
+ public static void main(String[] args) {
+ System.out.println("Debug Point 1");
+ new StaticFieldsDemo().populateList();
+ System.out.println("Debug Point 3");
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java
new file mode 100644
index 0000000000..217f1e06de
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java
@@ -0,0 +1,8 @@
+package com.baeldung.nth.root.calculator;
+
+public class NthRootCalculator
+{
+ public Double calculate(Double base, Double n) {
+ return Math.pow(Math.E, Math.log(base)/n);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/nth/root/main/Main.java b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java
new file mode 100644
index 0000000000..3fcd36812f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java
@@ -0,0 +1,13 @@
+package com.baeldung.nth.root.main;
+
+import com.baeldung.nth.root.calculator.NthRootCalculator;
+
+public class Main {
+ public static void main(String[] args) {
+ NthRootCalculator calculator = new NthRootCalculator();
+ Double base = Double.parseDouble(args[0]);
+ Double n = Double.parseDouble(args[1]);
+ Double result = calculator.calculate(base, n);
+ System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java
new file mode 100644
index 0000000000..e2259e4249
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java
@@ -0,0 +1,149 @@
+package com.baeldung.passwordhashing;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.KeySpec;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+
+/**
+ * Hash passwords for storage, and test passwords against password tokens.
+ *
+ * Instances of this class can be used concurrently by multiple threads.
+ *
+ * @author erickson
+ * @see StackOverflow
+ */
+public final class PBKDF2Hasher
+{
+
+ /**
+ * Each token produced by this class uses this identifier as a prefix.
+ */
+ public static final String ID = "$31$";
+
+ /**
+ * The minimum recommended cost, used by default
+ */
+ public static final int DEFAULT_COST = 16;
+
+ private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
+
+ private static final int SIZE = 128;
+
+ private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
+
+ private final SecureRandom random;
+
+ private final int cost;
+
+ public PBKDF2Hasher()
+ {
+ this(DEFAULT_COST);
+ }
+
+ /**
+ * Create a password manager with a specified cost
+ *
+ * @param cost the exponential computational cost of hashing a password, 0 to 30
+ */
+ public PBKDF2Hasher(int cost)
+ {
+ iterations(cost); /* Validate cost */
+ this.cost = cost;
+ this.random = new SecureRandom();
+ }
+
+ private static int iterations(int cost)
+ {
+ if ((cost < 0) || (cost > 30))
+ throw new IllegalArgumentException("cost: " + cost);
+ return 1 << cost;
+ }
+
+ /**
+ * Hash a password for storage.
+ *
+ * @return a secure authentication token to be stored for later authentication
+ */
+ public String hash(char[] password)
+ {
+ byte[] salt = new byte[SIZE / 8];
+ random.nextBytes(salt);
+ byte[] dk = pbkdf2(password, salt, 1 << cost);
+ byte[] hash = new byte[salt.length + dk.length];
+ System.arraycopy(salt, 0, hash, 0, salt.length);
+ System.arraycopy(dk, 0, hash, salt.length, dk.length);
+ Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
+ return ID + cost + '$' + enc.encodeToString(hash);
+ }
+
+ /**
+ * Authenticate with a password and a stored password token.
+ *
+ * @return true if the password and token match
+ */
+ public boolean checkPassword(char[] password, String token)
+ {
+ Matcher m = layout.matcher(token);
+ if (!m.matches())
+ throw new IllegalArgumentException("Invalid token format");
+ int iterations = iterations(Integer.parseInt(m.group(1)));
+ byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
+ byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
+ byte[] check = pbkdf2(password, salt, iterations);
+ int zero = 0;
+ for (int idx = 0; idx < check.length; ++idx)
+ zero |= hash[salt.length + idx] ^ check[idx];
+ return zero == 0;
+ }
+
+ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
+ {
+ KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
+ try {
+ SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
+ return f.generateSecret(spec).getEncoded();
+ }
+ catch (NoSuchAlgorithmException ex) {
+ throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
+ }
+ catch (InvalidKeySpecException ex) {
+ throw new IllegalStateException("Invalid SecretKeyFactory", ex);
+ }
+ }
+
+ /**
+ * Hash a password in an immutable {@code String}.
+ *
+ * Passwords should be stored in a {@code char[]} so that it can be filled
+ * with zeros after use instead of lingering on the heap and elsewhere.
+ *
+ * @deprecated Use {@link #hash(char[])} instead
+ */
+ @Deprecated
+ public String hash(String password)
+ {
+ return hash(password.toCharArray());
+ }
+
+ /**
+ * Authenticate with a password in an immutable {@code String} and a stored
+ * password token.
+ *
+ * @deprecated Use {@link #checkPassword(char[],String)} instead.
+ * @see #hash(String)
+ */
+ @Deprecated
+ public boolean checkPassword(String password, String token)
+ {
+ return checkPassword(password.toCharArray(), token);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java
new file mode 100644
index 0000000000..4f5337f963
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java
@@ -0,0 +1,35 @@
+package com.baeldung.passwordhashing;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+
+/** A really simple SHA_512 Encryption example.
+ *
+ */
+public class SHA512Hasher {
+
+ public String hash(String passwordToHash, byte[] salt){
+ String generatedPassword = null;
+ try {
+ MessageDigest md = MessageDigest.getInstance("SHA-512");
+ md.update(salt);
+ byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
+ StringBuilder sb = new StringBuilder();
+ for(int i=0; i< bytes.length ;i++){
+ sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
+ }
+ generatedPassword = sb.toString();
+ }
+ catch (NoSuchAlgorithmException e){
+ e.printStackTrace();
+ }
+ return generatedPassword;
+ }
+
+ public boolean checkPassword(String hash, String attempt, byte[] salt){
+ String generatedHash = hash(attempt, salt);
+ return hash.equals(generatedHash);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java
new file mode 100644
index 0000000000..36c9b65070
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java
@@ -0,0 +1,18 @@
+package com.baeldung.passwordhashing;
+
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import java.security.spec.KeySpec;
+
+/** A really simple SimplePBKDF2 Encryption example.
+ *
+ */
+public class SimplePBKDF2Hasher {
+
+ public static String hashSimple(String password, byte[] salt) throws Exception{
+ KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
+ SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+ byte[] hash = f.generateSecret(spec).getEncoded();
+ return String.valueOf(hash);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
new file mode 100644
index 0000000000..bebffe52f1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
@@ -0,0 +1,45 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionX {
+
+ public String addCharUsingCharArray(String str, char ch, int position) {
+ validate(str, position);
+ int len = str.length();
+ char[] updatedArr = new char[len + 1];
+ str.getChars(0, position, updatedArr, 0);
+ updatedArr[position] = ch;
+ str.getChars(position, len, updatedArr, position + 1);
+ return new String(updatedArr);
+ }
+
+ public String addCharUsingSubstring(String str, char ch, int position) {
+ validate(str, position);
+ return str.substring(0, position) + ch + str.substring(position);
+ }
+
+ public String addCharUsingStringBuilder(String str, char ch, int position) {
+ validate(str, position);
+ StringBuilder sb = new StringBuilder(str);
+ sb.insert(position, ch);
+ return sb.toString();
+ }
+
+ private void validate(String str, int position) {
+ if (str == null) {
+ throw new IllegalArgumentException("Str should not be null");
+ }
+ int len = str.length();
+ if (position < 0 || position > len) {
+ throw new IllegalArgumentException("position[" + position + "] should be "
+ + "in the range 0.." + len + " for string " + str);
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java
new file mode 100644
index 0000000000..69e151bfcb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java
@@ -0,0 +1,70 @@
+package com.baeldung.switchstatement;
+
+public class SwitchStatement {
+
+ public String exampleOfIF(String animal) {
+
+ String result;
+
+ if (animal.equals("DOG") || animal.equals("CAT")) {
+ result = "domestic animal";
+ } else if (animal.equals("TIGER")) {
+ result = "wild animal";
+ } else {
+ result = "unknown animal";
+ }
+ return result;
+ }
+
+ public String exampleOfSwitch(String animal) {
+
+ String result;
+
+ switch (animal) {
+ case "DOG":
+ case "CAT":
+ result = "domestic animal";
+ break;
+ case "TIGER":
+ result = "wild animal";
+ break;
+ default:
+ result = "unknown animal";
+ break;
+ }
+ return result;
+ }
+
+ public String forgetBreakInSwitch(String animal) {
+
+ String result;
+
+ switch (animal) {
+
+ case "DOG":
+ System.out.println("domestic animal");
+ result = "domestic animal";
+
+ default:
+ System.out.println("unknown animal");
+ result = "unknown animal";
+
+ }
+ return result;
+ }
+
+ public String constantCaseValue(String animal) {
+
+ String result = "";
+
+ final String dog = "DOG";
+
+ switch (animal) {
+
+ case dog:
+ result = "domestic animal";
+ }
+ return result;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java
new file mode 100644
index 0000000000..bdf6684f78
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java
@@ -0,0 +1,23 @@
+package com.baeldung.synthetic;
+
+import java.util.Comparator;
+
+/**
+ * Class which contains a synthetic bridge method.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class BridgeMethodDemo implements Comparator {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public int compare(Integer o1, Integer o2) {
+ return 0;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java
new file mode 100644
index 0000000000..d3d75ac05e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java
@@ -0,0 +1,34 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains a synthetic constructor.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticConstructorDemo {
+
+ /**
+ * We need to instantiate the {@link NestedClass} using a private
+ * constructor from the enclosing instance in order to generate a synthetic
+ * constructor.
+ */
+ private NestedClass nestedClass = new NestedClass();
+
+ /**
+ * Class which contains a synthetic constructor.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ /**
+ * In order to generate a synthetic constructor, this class must have a
+ * private constructor.
+ */
+ private NestedClass() {
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java
new file mode 100644
index 0000000000..1813e03953
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java
@@ -0,0 +1,22 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains a synthetic field reference to the outer
+ * class.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticFieldDemo {
+
+ /**
+ * Class which contains a synthetic field reference to the outer class.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java
new file mode 100644
index 0000000000..59be4e1429
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java
@@ -0,0 +1,48 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains two synthetic methods accessors to a
+ * private field.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticMethodDemo {
+
+ /**
+ * Class which contains two synthetic methods accessors to a private field.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ /**
+ * Field for which will be generated synthetic methods accessors. It's
+ * important that this field is private for this purpose.
+ */
+ private String nestedField;
+ }
+
+ /**
+ * Gets the private nested field. We need to read the nested field in order
+ * to generate the synthetic getter.
+ *
+ * @return the {@link NestedClass#nestedField}
+ */
+ public String getNestedField() {
+ return new NestedClass().nestedField;
+ }
+
+ /**
+ * Sets the private nested field. We need to write the nested field in order
+ * to generate the synthetic setter.
+ *
+ * @param nestedField
+ * the {@link NestedClass#nestedField}
+ */
+ public void setNestedField(String nestedField) {
+ new NestedClass().nestedField = nestedField;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
new file mode 100644
index 0000000000..50dbc9c774
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
@@ -0,0 +1,15 @@
+package com.baeldung.throwsexception;
+
+public class Calculator {
+
+ public double divide(double a, double b) {
+ if (b == 0) {
+ throw new DivideByZeroException("Divider cannot be equal to zero!");
+ }
+ return a/b;
+ }
+
+}
+
+
+
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
new file mode 100644
index 0000000000..0b371dcedb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DataAccessException extends RuntimeException {
+
+ public DataAccessException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
new file mode 100644
index 0000000000..4413374c99
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DivideByZeroException extends RuntimeException {
+
+ public DivideByZeroException(String message) {
+ super(message);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Main.java b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
new file mode 100644
index 0000000000..17fbf5a582
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
@@ -0,0 +1,41 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.net.SocketException;
+
+public class Main {
+
+ public static void main(String[] args) throws FileNotFoundException {
+ TryCatch tryCatch = new TryCatch();
+
+ try {
+ tryCatch.execute();
+ } catch (ConnectionException | SocketException ex) {
+ System.out.println("IOException");
+ } catch (Exception ex) {
+ System.out.println("General exception");
+ }
+
+ checkedException();
+ checkedExceptionWithThrows();
+ }
+
+ private static void checkedExceptionWithThrows() throws FileNotFoundException {
+ File file = new File("not_existing_file.txt");
+ FileInputStream stream = new FileInputStream(file);
+ }
+
+ private static void checkedException() {
+ File file = new File("not_existing_file.txt");
+ try {
+ FileInputStream stream = new FileInputStream(file);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
new file mode 100644
index 0000000000..7d8345c3c1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
@@ -0,0 +1,12 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+import java.util.List;
+
+public class PersonRepository {
+
+ public List findAll() throws SQLException {
+ throw new SQLException();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
new file mode 100644
index 0000000000..6bb8b90bf1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+
+public class SimpleService {
+
+ private PersonRepository personRepository = new PersonRepository();
+
+ public void wrappingException() {
+ try {
+ personRepository.findAll();
+ } catch (SQLException e) {
+ throw new DataAccessException("SQL Exception", e);
+ }
+ }
+
+ public void runtimeNullPointerException() {
+ String a = null;
+ a.length();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
new file mode 100644
index 0000000000..2fd87f124d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
@@ -0,0 +1,13 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.net.SocketException;
+
+public class TryCatch {
+
+ public void execute() throws SocketException, ConnectionException, Exception {
+ //code that would throw any of: SocketException, ConnectionException, Exception
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java
new file mode 100644
index 0000000000..fb92eb8d0d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java
@@ -0,0 +1,13 @@
+package com.baeldung.zoneddatetime;
+
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+
+public class OffsetDateTimeExample {
+
+ public OffsetDateTime getCurrentTimeByZoneOffset(String offset) {
+ ZoneOffset zoneOffSet= ZoneOffset.of(offset);
+ OffsetDateTime date = OffsetDateTime.now(zoneOffSet);
+ return date;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java
new file mode 100644
index 0000000000..58e2d4d5ad
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java
@@ -0,0 +1,13 @@
+package com.baeldung.zoneddatetime;
+
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+
+public class OffsetTimeExample {
+
+ public OffsetTime getCurrentTimeByZoneOffset(String offset) {
+ ZoneOffset zoneOffSet = ZoneOffset.of(offset);
+ OffsetTime time = OffsetTime.now(zoneOffSet);
+ return time;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java
new file mode 100644
index 0000000000..b54b8c5225
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java
@@ -0,0 +1,21 @@
+package com.baeldung.zoneddatetime;
+
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class ZoneDateTimeExample {
+
+ public ZonedDateTime getCurrentTimeByZoneId(String region) {
+ ZoneId zone = ZoneId.of(region);
+ ZonedDateTime date = ZonedDateTime.now(zone);
+ return date;
+ }
+
+ public ZonedDateTime convertZonedDateTime(ZonedDateTime sourceDate, String destZone) {
+
+ ZoneId destZoneId = ZoneId.of(destZone);
+ ZonedDateTime destDate = sourceDate.withZoneSameInstant(destZoneId);
+
+ return destDate;
+ }
+}
diff --git a/core-java/src/main/resources/logback.xml b/core-java/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java/src/main/resources/logback.xml
+++ b/core-java/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java b/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java
deleted file mode 100644
index 7d11016d7f..0000000000
--- a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.array;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class RemoveFirstElementUnitTest {
-
- @Test
- public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
- String[] stringArray = {"foo", "bar", "baz"};
-
- String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
-
- assertThat(modifiedArray.length).isEqualTo(2);
- assertThat(modifiedArray[0]).isEqualTo("bar");
- }
-
- @Test
- public void givenArrayList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
- List stringList = new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
- stringList.remove(0);
-
- assertThat(stringList.size()).isEqualTo(2);
- assertThat(stringList.get(0)).isEqualTo("bar");
- }
-
- @Test
- public void givenLinkedList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
- List stringList = new LinkedList<>(Arrays.asList("foo", "bar", "baz"));
- stringList.remove(0);
-
- assertThat(stringList.size()).isEqualTo(2);
- assertThat(stringList.get(0)).isEqualTo("bar");
- }
-
-}
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
new file mode 100644
index 0000000000..41c67ff389
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040
+ */
+@RunWith(MockitoJUnitRunner.class)
+
+public class AnimalActivityUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal animal = new Animal();
+
+ AnimalActivity.sleep(animal);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+
+ @Test
+ public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() {
+
+ Cat cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Cat is sleeping"));
+ }
+
+ @Test
+ public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
new file mode 100644
index 0000000000..a34640b58a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.util.List;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+
+@RunWith(MockitoJUnitRunner.class)
+public class AnimalUnitTest {
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() {
+
+ Animal animal = new Animal();
+
+ animal.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise"));
+ }
+
+ @Test
+ public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() {
+
+ Animal animal = new Animal();
+
+ int testValue = 3;
+ animal.makeNoise(testValue);
+
+ verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
+
+ final List loggingEvents = captorLoggingEvent.getAllValues();
+
+ for(LoggingEvent loggingEvent : loggingEvents)
+ {
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise countdown "+testValue));
+
+ testValue--;
+ }
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
new file mode 100644
index 0000000000..76ccfb7719
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class CatUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void makeNoiseTest() {
+
+ Cat cat = new Cat();
+
+ cat.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("meow"));
+
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
index ec35885b84..cabf9f7bdb 100644
--- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
@@ -11,7 +11,7 @@ public class CustomClassLoaderUnitTest {
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
CustomClassLoader customClassLoader = new CustomClassLoader();
- Class> c = customClassLoader.getClass(PrintClassLoader.class.getName());
+ Class> c = customClassLoader.findClass(PrintClassLoader.class.getName());
Object ob = c.newInstance();
diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
new file mode 100644
index 0000000000..0c0266a111
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.constructorsstaticfactorymethods;
+
+import com.baeldung.constructorsstaticfactorymethods.entities.User;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class UserUnitTest {
+
+ @Test
+ public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() {
+ assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getName()).isEqualTo("John");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getEmail()).isEqualTo("john@domain.com");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getCountry()).isEqualTo("Argentina");
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() {
+ assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() {
+ User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ assertThat(user1).isEqualTo(user2);
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
index 35aa07821c..70bfe168dd 100644
--- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
@@ -75,26 +75,5 @@ public class PizzaUnitTest {
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
- @Test
- public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
- String pizzaEnumValue = "READY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "rEAdY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "invalid";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
-
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
index 1e86132116..b3f585cfe4 100644
--- a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
@@ -21,7 +21,7 @@ public class ExceptionsUnitTest {
@Test
public void loadAllPlayers() {
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
- .isInstanceOf(IOException.class);
+ .isInstanceOf(IllegalStateException.class);
}
@Test
@@ -72,12 +72,6 @@ public class ExceptionsUnitTest {
.isInstanceOf(NullPointerException.class);
}
- @Test
- public void throwAsGotoAntiPattern() {
- assertThatThrownBy(() -> exceptions.throwAsGotoAntiPattern())
- .isInstanceOf(MyException.class);
- }
-
@Test
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
index bc012dae6b..b484eecef7 100644
--- a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
@@ -9,28 +9,15 @@ import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
@Log
public class ListInitializationUnitTest {
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List cities = new ArrayList() {
- // Inside declaration of the subclass
-
- // You can have multiple initializer block
{
- log.info("Inside the first initializer block.");
- }
-
- {
- log.info("Inside the second initializer block.");
add("New York");
add("Rio");
add("Tokyo");
@@ -47,11 +34,10 @@ public class ListInitializationUnitTest {
Assert.assertTrue(list.contains("foo"));
}
- @Test
+ @Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List list = Arrays.asList("foo", "bar");
- exception.expect(UnsupportedOperationException.class);
list.add("baz");
}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..3fa1db18d2
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.memoryleaks.equalshashcode;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class PersonMemoryLeakUnitTest {
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
+ Map map = new HashMap();
+ for(int i=0; i<10000000; i++) {
+ map.put(new Person("jon"), 1);
+ }
+ assertTrue(map.size() > 1);
+ System.out.print("Debug Point - VisuaLVM");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
+ Map map = new HashMap();
+ for(int i=0; i<10000; i++) {
+ map.put(new PersonOptimized("jon"), 1);
+ }
+ assertTrue(map.size() == 1);
+ System.out.print("Debug Point - VisuaLVM");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..b6d81a8968
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.memoryleaks.finalize;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class FinalizeMemoryLeakUnitTest {
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
+ BulkyObject[] stock = new BulkyObject[100000];
+
+ for(int i=0; i<100000; i++) {
+ stock[i] = new BulkyObject();
+ }
+ System.out.print("Debug Point - VisuaLVM");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
+ BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
+
+ for(int i=0; i<100000; i++) {
+ stock[i] = new BulkyObjectOptimized();
+ }
+ System.out.print("Debug Point - VisuaLVM");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..0854e4a38a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.memoryleaks.innerclass;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class StaticInnerClassMemoryLeakUnitTest {
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
+ InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
+ System.out.print("Debug Point - VisuaLVM");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
+ StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
+ System.out.print("Debug Point - VisuaLVM");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..6d363e0bdc
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.memoryleaks.internedstrings;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class StringInternMemoryLeakUnitTest {
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
+ new InternedString().readString();
+ System.out.print("Debug Point - VisuaLVM");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
+ new StringObject().readString();
+ System.out.print("Debug Point - VisuaLVM");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..e64fdb73e0
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.memoryleaks.staticfields;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class NonStaticFieldsMemoryLeakUnitTest {
+ public List list = new ArrayList<>();
+
+ public void populateList() {
+ for (int i = 0; i < 10000000; i++) {
+ list.add(Math.random());
+ }
+ System.out.println("Debug Point 2");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
+ System.out.println("Debug Point 1");
+ new NonStaticFieldsMemoryLeakUnitTest().populateList();
+ System.out.println("Debug Point 3");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java
new file mode 100644
index 0000000000..1765f0cf0d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.memoryleaks.staticfields;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class StaticFieldsMemoryLeakUnitTest {
+ public static List list = new ArrayList<>();
+
+ public void populateList() {
+ for (int i = 0; i < 10000000; i++) {
+ list.add(Math.random());
+ }
+ System.out.println("Debug Point 2");
+ }
+
+ @Test
+ @Ignore // Test deliberately ignored as memory leak tests consume lots of resources
+ public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
+ System.out.println("Debug Point 1");
+ new StaticFieldsDemo().populateList();
+ System.out.println("Debug Point 3");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java
new file mode 100644
index 0000000000..286dffb56a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.nth.root.calculator;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class NthRootCalculatorUnitTest {
+
+ @InjectMocks
+ private NthRootCalculator nthRootCalculator;
+
+ @Test
+ public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() {
+ Double result = nthRootCalculator.calculate(125.0, 3.0);
+ assertEquals(result, (Double) 5.0d);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java
new file mode 100644
index 0000000000..a2fd839ba4
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.nth.root.main;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import static org.junit.Assert.assertEquals;
+
+public class MainUnitTest {
+ @InjectMocks
+ private Main main;
+
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+
+ @Before
+ public void setUpStreams() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @After
+ public void restoreStreams() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
+ main.main(new String[]{"125.0", "3.0"});
+ assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java
new file mode 100644
index 0000000000..8e90725c77
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.passwordhashing;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+
+public class PBKDF2HasherUnitTest {
+
+ private PBKDF2Hasher mPBKDF2Hasher;
+
+ @Before
+ public void setUp() throws Exception {
+ mPBKDF2Hasher = new PBKDF2Hasher();
+ }
+
+ @Test
+ public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
+ String message1 = "password123";
+
+ String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
+
+ assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
+
+ }
+
+ @Test
+ public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
+ String message1 = "password123";
+
+ String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
+
+ String wrongPasswordAttempt = "IamWrong";
+
+ assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java
new file mode 100644
index 0000000000..3acfb0ba9d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.passwordhashing;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.security.SecureRandom;
+
+import static org.junit.Assert.*;
+
+/**
+ * Created by PhysicsSam on 06-Sep-18.
+ */
+public class SHA512HasherUnitTest {
+
+ private SHA512Hasher hasher;
+ private SecureRandom secureRandom;
+
+ @Before
+ public void setUp() throws Exception {
+ hasher = new SHA512Hasher();
+ secureRandom = new SecureRandom();
+ }
+
+ @Test
+ public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception {
+
+ byte[] salt = new byte[16];
+ secureRandom.nextBytes(salt);
+
+ String hash1 = hasher.hash("password", salt);
+ String hash2 = hasher.hash("password", salt);
+
+ assertEquals(hash1, hash2);
+
+ }
+
+ @Test
+ public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception {
+
+ byte[] salt = new byte[16];
+ secureRandom.nextBytes(salt);
+ String hash1 = hasher.hash("password", salt);
+ //generate a second salt
+ byte[] secondSalt = new byte[16];
+ String hash2 = hasher.hash("password", secondSalt);
+
+ assertNotEquals(hash1, hash2);
+
+ }
+
+ @Test
+ public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception {
+ byte[] salt = new byte[16];
+ secureRandom.nextBytes(salt);
+
+ String originalHash = hasher.hash("password123", salt);
+
+ assertTrue(hasher.checkPassword(originalHash, "password123", salt));
+ }
+
+ @Test
+ public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception {
+ byte[] salt = new byte[16];
+ secureRandom.nextBytes(salt);
+
+ String originalHash = hasher.hash("password123", salt);
+
+ assertFalse(hasher.checkPassword(originalHash, "password124", salt));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
new file mode 100644
index 0000000000..f21a755b01
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
@@ -0,0 +1,109 @@
+package com.baeldung.regexp.optmization;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertTrue;
+
+public class OptimizedMatcherUnitTest {
+
+ private long time;
+ private long mstimePreCompiled;
+ private long mstimeNotPreCompiled;
+
+ private String action;
+
+ private List items;
+
+ @Before
+ public void setup() {
+ Random random = new Random();
+ items = new ArrayList();
+ long average = 0;
+
+ for (int i = 0; i < 100000; ++i) {
+ StringBuilder s = new StringBuilder();
+ int characters = random.nextInt(7) + 1;
+ for (int k = 0; k < characters; ++ k) {
+ char c = (char)(random.nextInt('Z' - 'A') + 'A');
+ int rep = random.nextInt(95) + 5;
+ for (int j = 0; j < rep; ++ j)
+ s.append(c);
+ average += rep;
+ }
+ items.add(s.toString());
+ }
+
+ average /= 100000;
+ System.out.println("generated data, average length: " + average);
+ }
+
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*B*C*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("E*C*W*F*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ private void testPatterns(String regex) {
+ time = System.nanoTime();
+ int matched = 0;
+ int unmatched = 0;
+
+ for (String item : this.items) {
+ if (item.matches(regex)) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms");
+
+ time = System.nanoTime();
+
+ Matcher matcher = Pattern.compile(regex).matcher("");
+ matched = 0;
+ unmatched = 0;
+
+ for (String item : this.items) {
+ if (matcher.reset(item).matches()) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimePreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimePreCompiled + "ms");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java
new file mode 100644
index 0000000000..8dbfcaf5e7
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java
@@ -0,0 +1,100 @@
+package com.baeldung.removingdecimals;
+
+import org.junit.Test;
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * This benchmark compares some of the approaches to formatting a floating-point
+ * value into a {@link String} while removing the decimal part.
+ *
+ * To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test
+ * at the end of this class.
+ *
+ * The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput},
+ * higher numbers mean better performance.
+ */
+@BenchmarkMode(Mode.Throughput)
+@Warmup(iterations = 5)
+@Measurement(iterations = 20)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+@State(Scope.Benchmark)
+public class RemovingDecimalsManualTest {
+ @Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue;
+
+ NumberFormat nf;
+ DecimalFormat df;
+
+ @Setup
+ public void readyFormatters() {
+ nf = NumberFormat.getInstance();
+ nf.setMaximumFractionDigits(0);
+ df = new DecimalFormat("#,###");
+ }
+
+ @Benchmark
+ public String whenCastToInt_thenValueIsTruncated() {
+ return String.valueOf((int) doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingStringFormat_thenValueIsRounded() {
+ return String.format("%.0f", doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingNumberFormat_thenValueIsRounded() {
+ nf.setRoundingMode(RoundingMode.HALF_UP);
+ return nf.format(doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
+ nf.setRoundingMode(RoundingMode.FLOOR);
+ return nf.format(doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingDecimalFormat_thenValueIsRounded() {
+ df.setRoundingMode(RoundingMode.HALF_UP);
+ return df.format(doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
+ df.setRoundingMode(RoundingMode.FLOOR);
+ return df.format(doubleValue);
+ }
+
+ @Benchmark
+ public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
+ BigDecimal big = new BigDecimal(doubleValue);
+ big = big.setScale(0, RoundingMode.FLOOR);
+ return big.toString();
+ }
+
+ @Benchmark
+ public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
+ BigDecimal big = new BigDecimal(doubleValue);
+ big = big.setScale(0, RoundingMode.HALF_UP);
+ return big.toString();
+ }
+
+ @Test
+ public void runBenchmarks() throws Exception {
+ Options options = new OptionsBuilder()
+ .include(this.getClass().getSimpleName()).threads(1)
+ .forks(1).shouldFailOnError(true).shouldDoGC(true)
+ .jvmArgs("-server").build();
+
+ new Runner(options).run();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java
new file mode 100644
index 0000000000..2f634b553b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.removingdecimals;
+
+import org.junit.Test;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+/**
+ * Tests that demonstrate some different approaches for formatting a
+ * floating-point value into a {@link String} while removing the decimal part.
+ */
+public class RemovingDecimalsUnitTest {
+ private final double doubleValue = 345.56;
+
+ @Test
+ public void whenCastToInt_thenValueIsTruncated() {
+ String truncated = String.valueOf((int) doubleValue);
+ assertEquals("345", truncated);
+ }
+
+ @Test
+ public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() {
+ double outOfIntRange = 6_000_000_000.56;
+ String truncationAttempt = String.valueOf((int) outOfIntRange);
+ assertNotEquals("6000000000", truncationAttempt);
+ }
+
+ @Test
+ public void whenUsingStringFormat_thenValueIsRounded() {
+ String rounded = String.format("%.0f", doubleValue);
+ assertEquals("346", rounded);
+ }
+
+ @Test
+ public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() {
+ double outOfIntRange = 6_000_000_000.56;
+ String rounded = String.format("%.0f", outOfIntRange);
+ assertEquals("6000000001", rounded);
+ }
+
+ @Test
+ public void whenUsingNumberFormat_thenValueIsRounded() {
+ NumberFormat nf = NumberFormat.getInstance();
+ nf.setMaximumFractionDigits(0);
+ nf.setRoundingMode(RoundingMode.HALF_UP);
+ String rounded = nf.format(doubleValue);
+ assertEquals("346", rounded);
+ }
+
+ @Test
+ public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
+ NumberFormat nf = NumberFormat.getInstance();
+ nf.setMaximumFractionDigits(0);
+ nf.setRoundingMode(RoundingMode.FLOOR);
+ String truncated = nf.format(doubleValue);
+ assertEquals("345", truncated);
+ }
+
+ @Test
+ public void whenUsingDecimalFormat_thenValueIsRounded() {
+ DecimalFormat df = new DecimalFormat("#,###");
+ df.setRoundingMode(RoundingMode.HALF_UP);
+ String rounded = df.format(doubleValue);
+ assertEquals("346", rounded);
+ }
+
+ @Test
+ public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
+ DecimalFormat df = new DecimalFormat("#,###");
+ df.setRoundingMode(RoundingMode.FLOOR);
+ String truncated = df.format(doubleValue);
+ assertEquals("345", truncated);
+ }
+
+ @Test
+ public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
+ BigDecimal big = new BigDecimal(doubleValue);
+ big = big.setScale(0, RoundingMode.FLOOR);
+ String truncated = big.toString();
+ assertEquals("345", truncated);
+ }
+
+ @Test
+ public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
+ BigDecimal big = new BigDecimal(doubleValue);
+ big = big.setScale(0, RoundingMode.HALF_UP);
+ String truncated = big.toString();
+ assertEquals("346", truncated);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
new file mode 100644
index 0000000000..2cdf6145d3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
@@ -0,0 +1,110 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionXUnitTest {
+
+ private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
+ private String word = "Titanc";
+ private char letter = 'i';
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java
new file mode 100644
index 0000000000..e8ac645531
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.switchstatement;
+
+import org.junit.Test;
+
+import org.junit.Assert;
+
+public class SwitchStatementUnitTest {
+ private SwitchStatement s = new SwitchStatement();
+
+
+ @Test
+ public void whenDog_thenDomesticAnimal() {
+
+ String animal = "DOG";
+ Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
+ }
+
+ @Test
+ public void whenNoBreaks_thenGoThroughBlocks() {
+ String animal = "DOG";
+ Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void whenSwitchAgumentIsNull_thenNullPointerException() {
+ String animal = null;
+ Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
+ }
+
+
+ @Test
+ public void whenCompareStrings_thenByEqual() {
+ String animal = new String("DOG");
+ Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
+ }
+
+
+}
diff --git a/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java
new file mode 100644
index 0000000000..20f7647f48
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java
@@ -0,0 +1,99 @@
+package com.baeldung.synthetic;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
+ * {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticUnitTest {
+
+ /**
+ * Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
+ * methods.
+ */
+ @Test
+ public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
+ // Checks that the nested class contains exactly two synthetic methods.
+ Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
+ Assert.assertEquals("This class should contain only two methods", 2, methods.length);
+
+ for (Method m : methods) {
+ System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
+ Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
+ }
+ }
+
+ /**
+ * Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
+ * constructor.
+ */
+ @Test
+ public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
+ // Checks that the nested class contains exactly a synthetic
+ // constructor.
+ int syntheticConstructors = 0;
+ Constructor>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
+ Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
+
+ for (Constructor> c : constructors) {
+ System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
+
+ // Counts the synthetic constructors.
+ if (c.isSynthetic()) {
+ syntheticConstructors++;
+ }
+ }
+
+ // Checks that there's exactly one synthetic constructor.
+ Assert.assertEquals(1, syntheticConstructors);
+ }
+
+ /**
+ * Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
+ */
+ @Test
+ public void givenSyntheticField_whenIsSinthetic_thenTrue() {
+ // This class should contain exactly one synthetic field.
+ Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
+ Assert.assertEquals("This class should contain only one field", 1, fields.length);
+
+ for (Field f : fields) {
+ System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
+ Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
+ }
+ }
+
+ /**
+ * Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
+ */
+ @Test
+ public void givenBridgeMethod_whenIsBridge_thenTrue() {
+ // This class should contain exactly one synthetic bridge method.
+ int syntheticMethods = 0;
+ Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
+ for (Method m : methods) {
+ System.out.println(
+ "Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
+
+ // Counts the synthetic methods and checks that they are also bridge
+ // methods.
+ if (m.isSynthetic()) {
+ syntheticMethods++;
+ Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
+ }
+ }
+
+ // Checks that there's exactly one synthetic bridge method.
+ Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java
new file mode 100644
index 0000000000..6b292ad8ab
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.ternaryoperator;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class TernaryOperatorUnitTest {
+
+ @Test
+ public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
+ int number = 10;
+ String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
+
+ assertThat(msg).isEqualTo("Number is less than or equal to 10");
+ }
+
+ @Test
+ public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
+ int exp1 = 0, exp2 = 0;
+ int result = 12 > 10 ? ++exp1 : ++exp2;
+
+ assertThat(exp1).isEqualTo(1);
+ assertThat(exp2).isEqualTo(0);
+ assertThat(result).isEqualTo(1);
+ }
+
+ @Test
+ public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
+ int exp1 = 0, exp2 = 0;
+ int result = 8 > 10 ? ++exp1 : ++exp2;
+
+ assertThat(exp1).isEqualTo(0);
+ assertThat(exp2).isEqualTo(1);
+ assertThat(result).isEqualTo(1);
+ }
+
+ @Test
+ public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
+ int number = 6;
+ String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
+
+ assertThat(msg).isEqualTo("Number is greater than 5");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
new file mode 100644
index 0000000000..ef838ed304
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.throwsexception;
+
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class CalculatorUnitTest {
+
+ @Test
+ public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() {
+ Calculator calculator = new Calculator();
+
+ assertThrows(DivideByZeroException.class,
+ () -> calculator.divide(10, 0));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
new file mode 100644
index 0000000000..b9a658a960
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class SimpleServiceUnitTest {
+
+ SimpleService simpleService = new SimpleService();
+
+ @Test
+ void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
+ assertThrows(DataAccessException.class,
+ () -> simpleService.wrappingException());
+ }
+
+ @Test
+ void whenCalled_thenNullPointerExceptionIsThrown() {
+ assertThrows(NullPointerException.class,
+ () -> simpleService.runtimeNullPointerException());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
index 6aa59e68d0..22fe0f5e57 100644
--- a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
@@ -1,6 +1,7 @@
package com.baeldung.unsafe;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import sun.misc.Unsafe;
@@ -56,6 +57,7 @@ public class UnsafeUnitTest {
}
@Test
+ @Ignore // Uncomment for local
public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException {
//given
long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java
new file mode 100644
index 0000000000..a08d3737cd
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.zoneddatetime;
+
+import static org.junit.Assert.assertTrue;
+
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+
+import org.junit.Test;
+
+public class OffsetDateTimeExampleUnitTest {
+
+ OffsetDateTimeExample offsetDateTimeExample = new OffsetDateTimeExample();
+
+ @Test
+ public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
+ String offset = "+02:00";
+ OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset);
+
+ assertTrue(time.getOffset()
+ .equals(ZoneOffset.of(offset)));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java
new file mode 100644
index 0000000000..488f934179
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.zoneddatetime;
+
+import static org.junit.Assert.assertTrue;
+
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+
+import org.junit.Test;
+
+public class OffsetTimeExampleUnitTest {
+
+ OffsetTimeExample offsetTimeExample = new OffsetTimeExample();
+
+ @Test
+ public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() {
+ String offset = "+02:00";
+ OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset);
+
+ assertTrue(time.getOffset()
+ .equals(ZoneOffset.of(offset)));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java
new file mode 100644
index 0000000000..e78ff3e3fd
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.zoneddatetime;
+
+import static org.junit.Assert.assertTrue;
+
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Test;
+
+public class ZoneDateTimeExampleUnitTest {
+
+ ZoneDateTimeExample zoneDateTimeExample = new ZoneDateTimeExample();
+
+ @Test
+ public void givenZone_whenGetCurrentTime_thenResultHasZone() {
+ String zone = "Europe/Berlin";
+ ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone);
+
+ assertTrue(time.getZone()
+ .equals(ZoneId.of(zone)));
+ }
+
+ @Test
+ public void givenZones_whenConvertDateByZone_thenGetConstantDiff() {
+ String sourceZone = "Europe/Berlin";
+ String destZone = "Asia/Tokyo";
+ ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone);
+ ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone);
+
+ assertTrue(sourceDate.toInstant()
+ .compareTo(destDate.toInstant()) == 0);
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
deleted file mode 100644
index bb3abff28d..0000000000
--- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.baeldung.java.enums;
-
-import static junit.framework.TestCase.assertTrue;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-
-import org.junit.Test;
-
-import com.baeldung.enums.Pizza;
-
-public class PizzaUnitTest {
-
- @Test
- public void givenPizaOrder_whenReady_thenDeliverable() {
- Pizza testPz = new Pizza();
- testPz.setStatus(Pizza.PizzaStatusEnum.READY);
- assertTrue(testPz.isDeliverable());
- }
-
- @Test
- public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
- assertTrue(undeliveredPzs.size() == 3);
- }
-
- @Test
- public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
-
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- EnumMap> map = Pizza.groupPizzaByStatus(pzList);
- assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
- assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
- assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
- }
-
- @Test
- public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
- Pizza pz = new Pizza();
- pz.setStatus(Pizza.PizzaStatusEnum.READY);
- pz.deliver();
- assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
-}
diff --git a/core-kotlin/README.md b/core-kotlin/README.md
index 734b2c08b3..523f5b6e78 100644
--- a/core-kotlin/README.md
+++ b/core-kotlin/README.md
@@ -8,7 +8,6 @@
- [Generics in Kotlin](http://www.baeldung.com/kotlin-generics)
- [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines)
- [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations)
-- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito)
- [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization)
- [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api)
- [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map)
@@ -19,8 +18,6 @@
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions)
- [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources)
-- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp)
-- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection)
- [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions)
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)
- [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file)
@@ -28,13 +25,17 @@
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
- [Writing to a File in Kotlin](http://www.baeldung.com/kotlin-write-file)
- [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions)
-- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek)
-- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson)
- [Kotlin String Templates](http://www.baeldung.com/kotlin-string-template)
-- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
-- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum)
- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project)
- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection)
- [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number)
- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
+- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
+- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
+- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
+- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
+- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
+- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
+- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
+- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
diff --git a/core-kotlin/build.gradle b/core-kotlin/build.gradle
index 6c1e06aa25..2b6527fca7 100755
--- a/core-kotlin/build.gradle
+++ b/core-kotlin/build.gradle
@@ -6,7 +6,6 @@ version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.41'
- ext.ktor_version = '0.9.2'
repositories {
mavenCentral()
@@ -44,14 +43,6 @@ sourceSets {
}
dependencies {
- compile "io.ktor:ktor-server-netty:$ktor_version"
compile "ch.qos.logback:logback-classic:1.2.1"
- compile "io.ktor:ktor-gson:$ktor_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
- implementation 'com.beust:klaxon:3.0.1'
-
-}
-task runServer(type: JavaExec) {
- main = 'APIServer'
- classpath = sourceSets.main.runtimeClasspath
}
\ No newline at end of file
diff --git a/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml b/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml
deleted file mode 100755
index 513a80cb27..0000000000
--- a/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
- io.ktor.ktor.config
- application.conf
-
-
-
- KtorServlet
- KtorServlet
- io.ktor.server.servlet.ServletApplicationEngine
-
-
- true
-
-
-
- 304857600
- 304857600
- 0
-
-
-
-
- KtorServlet
- /
-
-
-
\ No newline at end of file
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index afa7d8a963..0894a57320 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -3,26 +3,15 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-kotlin
- 1.0-SNAPSHOT
jar
com.baeldung
- parent-modules
+ parent-kotlin
1.0.0-SNAPSHOT
+ ../parent-kotlin
-
-
- jcenter
- http://jcenter.bintray.com
-
-
- kotlin-ktor
- https://dl.bintray.com/kotlin/ktor/
-
-
-
org.apache.commons
@@ -35,66 +24,6 @@
${junit.platform.version}
test
-
- org.jetbrains.kotlin
- kotlin-stdlib
- ${kotlin-stdlib.version}
-
-
- org.jetbrains.kotlin
- kotlin-stdlib-jdk8
- ${kotlin-stdlib.version}
-
-
- khttp
- khttp
- ${khttp.version}
-
-
- org.jetbrains.kotlin
- kotlin-test-junit
- ${kotlin-test-junit.version}
- test
-
-
- org.jetbrains.kotlin
- kotlin-reflect
- ${kotlin-reflect.version}
-
-
- org.jetbrains.kotlinx
- kotlinx-coroutines-core
- ${kotlinx.version}
-
-
- org.jetbrains.spek
- spek-api
- 1.1.5
- test
-
-
- org.jetbrains.spek
- spek-subject-extension
- 1.1.5
- test
-
-
- org.jetbrains.spek
- spek-junit-platform-engine
- 1.1.5
- test
-
-
- com.nhaarman
- mockito-kotlin
- ${mockito-kotlin.version}
- test
-
-
- com.github.salomonbrys.kodein
- kodein
- ${kodein.version}
-
org.assertj
assertj-core
@@ -102,142 +31,45 @@
test
- com.beust
- klaxon
- ${klaxon.version}
+ com.h2database
+ h2
+ ${h2database.version}
+
+
+ com.github.kittinunf.fuel
+ fuel
+ ${fuel.version}
+
+
+ com.github.kittinunf.fuel
+ fuel-gson
+ ${fuel.version}
+
+
+ com.github.kittinunf.fuel
+ fuel-rxjava
+ ${fuel.version}
+
+
+ com.github.kittinunf.fuel
+ fuel-coroutines
+ ${fuel.version}
+
+
+ nl.komponents.kovenant
+ kovenant
+ 3.3.0
+ pom
-
- io.ktor
- ktor-server-netty
- ${ktor.io.version}
-
-
- io.ktor
- ktor-gson
- ${ktor.io.version}
-
-
- ch.qos.logback
- logback-classic
- 1.2.1
- test
-
-
-
-
- org.jetbrains.kotlin
- kotlin-maven-plugin
- ${kotlin-maven-plugin.version}
-
-
- compile
-
- compile
-
-
-
- ${project.basedir}/src/main/kotlin
- ${project.basedir}/src/main/java
-
-
-
-
- test-compile
-
- test-compile
-
-
-
- ${project.basedir}/src/test/kotlin
- ${project.basedir}/src/test/java
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- ${java.version}
-
-
-
-
- default-compile
- none
-
-
-
- default-testCompile
- none
-
-
- java-compile
- compile
-
- compile
-
-
-
- java-test-compile
- test-compile
-
- testCompile
-
-
-
-
-
- maven-failsafe-plugin
- ${maven-failsafe-plugin.version}
-
-
- org.junit.platform
- junit-platform-surefire-provider
- ${junit.platform.version}
-
-
-
-
- junit5
-
- integration-test
- verify
-
-
-
- **/*Test5.java
-
-
-
-
-
-
-
-
- UTF-8
- 1.2.51
- 1.2.51
- 1.2.51
- 1.2.51
- 0.22.5
- 0.9.2
- 1.5.0
- 4.1.0
- 3.0.4
- 0.1.0
3.6.1
- 1.0.0
+ 1.1.1
5.2.0
3.10.0
+ 1.4.197
+ 1.15.0
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
new file mode 100644
index 0000000000..72b8d330e8
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
@@ -0,0 +1,17 @@
+package com.baeldung.constructor
+
+class Car {
+ val id: String
+ val type: String
+
+ constructor(id: String, type: String) {
+ this.id = id
+ this.type = type
+ }
+
+}
+
+fun main(args: Array) {
+ val car = Car("1", "sport")
+ val s= Car("2", "suv")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
new file mode 100644
index 0000000000..4483bfcf08
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
@@ -0,0 +1,3 @@
+package com.baeldung.constructor
+
+class Employee(name: String, val salary: Int): Person(name)
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
new file mode 100644
index 0000000000..57911b24ee
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.constructor;
+
+class PersonJava {
+ final String name;
+ final String surname;
+ final Integer age;
+
+ public PersonJava(String name, String surname) {
+ this.name = name;
+ this.surname = surname;
+ this.age = null;
+ }
+
+ public PersonJava(String name, String surname, Integer age) {
+ this.name = name;
+ this.surname = surname;
+ this.age = age;
+ }
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
index 7d10d849b9..1384cd9937 100644
--- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
@@ -1,39 +1,22 @@
package com.baeldung.builder
-class FoodOrder private constructor(builder: FoodOrder.Builder) {
-
- val bread: String?
- val condiments: String?
- val meat: String?
- val fish: String?
-
- init {
- this.bread = builder.bread
- this.condiments = builder.condiments
- this.meat = builder.meat
- this.fish = builder.fish
- }
-
- class Builder {
-
- var bread: String? = null
- private set
- var condiments: String? = null
- private set
- var meat: String? = null
- private set
- var fish: String? = null
- private set
+class FoodOrder(
+ val bread: String?,
+ val condiments: String?,
+ val meat: String?,
+ val fish: String?
+) {
+ data class Builder(
+ var bread: String? = null,
+ var condiments: String? = null,
+ var meat: String? = null,
+ var fish: String? = null) {
fun bread(bread: String) = apply { this.bread = bread }
-
fun condiments(condiments: String) = apply { this.condiments = condiments }
-
fun meat(meat: String) = apply { this.meat = meat }
-
fun fish(fish: String) = apply { this.fish = fish }
-
- fun build() = FoodOrder(this)
-
+ fun build() = FoodOrder(bread, condiments, meat, fish)
}
}
+
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
index 6e20cf51b9..0e4219b40e 100644
--- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
@@ -1,7 +1,7 @@
package com.baeldung.builder
data class FoodOrderNamed(
- val bread: String? = null,
- val condiments: String? = null,
- val meat: String? = null,
- val fish: String? = null)
+ val bread: String? = null,
+ val condiments: String? = null,
+ val meat: String? = null,
+ val fish: String? = null)
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
new file mode 100644
index 0000000000..cc348e3fbf
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
@@ -0,0 +1,9 @@
+package com.baeldung.builder
+
+fun main(args: Array) {
+ FoodOrder.Builder()
+ .bread("bread")
+ .condiments("condiments")
+ .meat("meat")
+ .fish("bread").let { println(it) }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
new file mode 100644
index 0000000000..3779d74541
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
@@ -0,0 +1,26 @@
+package com.baeldung.constructor
+
+open class Person(
+ val name: String,
+ val age: Int? = null
+) {
+ val upperCaseName: String = name.toUpperCase()
+
+ init {
+ println("Hello, I'm $name")
+
+ if (age != null && age < 0) {
+ throw IllegalArgumentException("Age cannot be less than zero!")
+ }
+ }
+
+ init {
+ println("upperCaseName is $upperCaseName")
+ }
+
+}
+
+fun main(args: Array) {
+ val person = Person("John")
+ val personWithAge = Person("John", 22)
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt
new file mode 100644
index 0000000000..4fd8aa27c7
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt
@@ -0,0 +1,19 @@
+package com.baeldung.datastructures
+
+/**
+ * Example of how to use the {@link Node} class.
+ *
+ */
+fun main(args: Array) {
+ val tree = Node(4)
+ val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
+ for (key in keys) {
+ tree.insert(key)
+ }
+ val node = tree.find(4)!!
+ println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
+ println("Delete node with key = 3")
+ node.delete(3)
+ print("Tree content after the node elimination: ")
+ println(tree.visit().joinToString { it.toString() })
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt
new file mode 100644
index 0000000000..b81afe1e4c
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt
@@ -0,0 +1,167 @@
+package com.baeldung.datastructures
+
+/**
+ * An ADT for a binary search tree.
+ * Note that this data type is neither immutable nor thread safe.
+ */
+class Node(
+ var key: Int,
+ var left: Node? = null,
+ var right: Node? = null) {
+
+ /**
+ * Return a node with given value. If no such node exists, return null.
+ * @param value
+ */
+ fun find(value: Int): Node? = when {
+ this.key > value -> left?.find(value)
+ this.key < value -> right?.find(value)
+ else -> this
+
+ }
+
+ /**
+ * Insert a given value into the tree.
+ * After insertion, the tree should contain a node with the given value.
+ * If the tree already contains the given value, nothing is performed.
+ * @param value
+ */
+ fun insert(value: Int) {
+ if (value > this.key) {
+ if (this.right == null) {
+ this.right = Node(value)
+ } else {
+ this.right?.insert(value)
+ }
+ } else if (value < this.key) {
+ if (this.left == null) {
+ this.left = Node(value)
+ } else {
+ this.left?.insert(value)
+ }
+ }
+ }
+
+ /**
+ * Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
+ * @param value
+ */
+ fun delete(value: Int) {
+ when {
+ value > key -> scan(value, this.right, this)
+ value < key -> scan(value, this.left, this)
+ else -> removeNode(this, null)
+ }
+ }
+
+ /**
+ * Scan the tree in the search of the given value.
+ * @param value
+ * @param node sub-tree that potentially might contain the sought value
+ * @param parent node's parent
+ */
+ private fun scan(value: Int, node: Node?, parent: Node?) {
+ if (node == null) {
+ System.out.println("value " + value
+ + " seems not present in the tree.")
+ return
+ }
+ when {
+ value > node.key -> scan(value, node.right, node)
+ value < node.key -> scan(value, node.left, node)
+ value == node.key -> removeNode(node, parent)
+ }
+
+ }
+
+ /**
+ * Remove the node.
+ *
+ * Removal process depends on how many children the node has.
+ *
+ * @param node node that is to be removed
+ * @param parent parent of the node to be removed
+ */
+ private fun removeNode(node: Node, parent: Node?) {
+ node.left?.let { leftChild ->
+ run {
+ node.right?.let {
+ removeTwoChildNode(node)
+ } ?: removeSingleChildNode(node, leftChild)
+ }
+ } ?: run {
+ node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
+ }
+
+
+ }
+
+ /**
+ * Remove the node without children.
+ * @param node
+ * @param parent
+ */
+ private fun removeNoChildNode(node: Node, parent: Node?) {
+ parent?.let { p ->
+ if (node == p.left) {
+ p.left = null
+ } else if (node == p.right) {
+ p.right = null
+ }
+ } ?: throw IllegalStateException(
+ "Can not remove the root node without child nodes")
+
+ }
+
+ /**
+ * Remove a node that has two children.
+ *
+ * The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
+ * node that is to be deleted with that key.
+ */
+ private fun removeTwoChildNode(node: Node) {
+ val leftChild = node.left!!
+ leftChild.right?.let {
+ val maxParent = findParentOfMaxChild(leftChild)
+ maxParent.right?.let {
+ node.key = it.key
+ maxParent.right = null
+ } ?: throw IllegalStateException("Node with max child must have the right child!")
+
+ } ?: run {
+ node.key = leftChild.key
+ node.left = leftChild.left
+ }
+
+ }
+
+ /**
+ * Return a node whose right child contains the biggest value in the given sub-tree.
+ * Assume that the node n has a non-null right child.
+ *
+ * @param n
+ */
+ private fun findParentOfMaxChild(n: Node): Node {
+ return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
+ ?: throw IllegalArgumentException("Right child must be non-null")
+
+ }
+
+ /**
+ * Remove a parent that has only one child.
+ * Removal is effectively is just coping the data from the child parent to the parent parent.
+ * @param parent Node to be deleted. Assume that it has just one child
+ * @param child Assume it is a child of the parent
+ */
+ private fun removeSingleChildNode(parent: Node, child: Node) {
+ parent.key = child.key
+ parent.left = child.left
+ parent.right = child.right
+ }
+
+ fun visit(): Array {
+ val a = left?.visit() ?: emptyArray()
+ val b = right?.visit() ?: emptyArray()
+ return a + arrayOf(key) + b
+ }
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt
new file mode 100644
index 0000000000..377ef979dc
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt
@@ -0,0 +1,11 @@
+package com.baeldung.fuel
+
+import com.github.kittinunf.fuel.core.Request
+
+fun tokenInterceptor() = {
+ next: (Request) -> Request ->
+ { req: Request ->
+ req.header(mapOf("Authorization" to "Bearer AbCdEf123456"))
+ next(req)
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt
new file mode 100644
index 0000000000..035dfe7aa0
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt
@@ -0,0 +1,15 @@
+package com.baeldung.fuel
+
+import com.github.kittinunf.fuel.core.ResponseDeserializable
+import com.google.gson.Gson
+
+data class Post(var userId:Int,
+ var id:Int,
+ var title:String,
+ var body:String){
+
+
+ class Deserializer : ResponseDeserializable> {
+ override fun deserialize(content: String): Array = Gson().fromJson(content, Array::class.java)
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt
new file mode 100644
index 0000000000..8238c41e56
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt
@@ -0,0 +1,42 @@
+package com.baeldung.fuel
+
+import com.github.kittinunf.fuel.core.Method
+import com.github.kittinunf.fuel.util.FuelRouting
+
+sealed class PostRoutingAPI : FuelRouting {
+
+ override val basePath = "https://jsonplaceholder.typicode.com"
+
+ class posts(val id: String, override val body: String?): PostRoutingAPI()
+
+ class comments(val postId: String, override val body: String?): PostRoutingAPI()
+
+ override val method: Method
+ get() {
+ return when(this) {
+ is PostRoutingAPI.posts -> Method.GET
+ is PostRoutingAPI.comments -> Method.GET
+ }
+ }
+
+ override val path: String
+ get() {
+ return when(this) {
+ is PostRoutingAPI.posts -> "/posts"
+ is PostRoutingAPI.comments -> "/comments"
+ }
+ }
+
+ override val params: List>?
+ get() {
+ return when(this) {
+ is PostRoutingAPI.posts -> listOf("id" to this.id)
+ is PostRoutingAPI.comments -> listOf("postId" to this.postId)
+ }
+ }
+
+ override val headers: Map?
+ get() {
+ return null
+ }
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt
deleted file mode 100755
index a12182ccc8..0000000000
--- a/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt
+++ /dev/null
@@ -1,73 +0,0 @@
-@file:JvmName("APIServer")
-
-
-import io.ktor.application.call
-import io.ktor.application.install
-import io.ktor.features.CallLogging
-import io.ktor.features.ContentNegotiation
-import io.ktor.features.DefaultHeaders
-import io.ktor.gson.gson
-import io.ktor.request.path
-import io.ktor.request.receive
-import io.ktor.response.respond
-import io.ktor.routing.*
-import io.ktor.server.engine.embeddedServer
-import io.ktor.server.netty.Netty
-import org.slf4j.event.Level
-
-data class Author(val name: String, val website: String)
-data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean)
-
-fun main(args: Array) {
-
- val toDoList = ArrayList();
- val jsonResponse = """{
- "id": 1,
- "task": "Pay waterbill",
- "description": "Pay water bill today",
- }"""
-
-
- embeddedServer(Netty, 8080) {
- install(DefaultHeaders) {
- header("X-Developer", "Baeldung")
- }
- install(CallLogging) {
- level = Level.DEBUG
- filter { call -> call.request.path().startsWith("/todo") }
- filter { call -> call.request.path().startsWith("/author") }
- }
- install(ContentNegotiation) {
- gson {
- setPrettyPrinting()
- }
- }
- routing() {
- route("/todo") {
- post {
- var toDo = call.receive();
- toDo.id = toDoList.size;
- toDoList.add(toDo);
- call.respond("Added")
-
- }
- delete("/{id}") {
- call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt()));
- }
- get("/{id}") {
-
- call.respond(toDoList[call.parameters["id"]!!.toInt()]);
- }
- get {
- call.respond(toDoList);
- }
- }
- get("/author"){
- call.respond(Author("Baeldung","baeldung.com"));
-
- }
-
-
- }
- }.start(wait = true)
-}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
new file mode 100644
index 0000000000..ee01c06646
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
@@ -0,0 +1,75 @@
+package com.baeldung.nested
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class Computer(val model: String) {
+
+ companion object {
+ const val originCountry = "China"
+ fun getBuiltDate(): String {
+ return "2018-05-23"
+ }
+
+ val log: Logger = LoggerFactory.getLogger(Computer::class.java)
+ }
+
+ //Nested class
+ class MotherBoard(val manufacturer: String) {
+ fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}"
+ }
+
+ //Inner class
+ inner class HardDisk(val sizeInGb: Int) {
+ fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB"
+ }
+
+ interface Switcher {
+ fun on(): String
+ }
+
+ interface Protector {
+ fun smart()
+ }
+
+ fun powerOn(): String {
+ //Local class
+ var defaultColor = "Blue"
+
+ class Led(val color: String) {
+ fun blink(): String {
+ return "blinking $color"
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Violet"
+ }
+ }
+
+ val powerLed = Led("Green")
+ log.debug("defaultColor is $defaultColor")
+ powerLed.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside Led class to $defaultColor")
+ //Anonymous object
+ val powerSwitch = object : Switcher, Protector {
+ override fun on(): String {
+ return powerLed.blink()
+ }
+
+ override fun smart() {
+ log.debug("Smart protection is implemented")
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Yellow"
+ }
+ }
+ powerSwitch.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor")
+ return powerSwitch.on()
+ }
+
+ override fun toString(): String {
+ return "Computer(model=$model)"
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt
index 17f5a43479..a6687b6e0a 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt
+++ b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt
@@ -93,6 +93,7 @@ internal class BuilderPatternUnitTest {
Assertions.assertNull(foodOrder.fish)
}
+
@Test
fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt
new file mode 100644
index 0000000000..8a46c5f6ec
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt
@@ -0,0 +1,319 @@
+package com.baeldung.datastructures
+
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+class NodeTest {
+
+ @Before
+ fun setUp() {
+ }
+
+ @After
+ fun tearDown() {
+ }
+
+ /**
+ * Test suit for finding the node by value
+ * Partition the tests as follows:
+ * 1. tree depth: 0, 1, > 1
+ * 2. pivot depth location: not present, 0, 1, 2, > 2
+ */
+
+ /**
+ * Find the node by value
+ * 1. tree depth: 0
+ * 2. pivot depth location: not present
+ */
+ @Test
+ fun givenDepthZero_whenPivotNotPresent_thenNull() {
+ val n = Node(1)
+ assertNull(n.find(2))
+ }
+
+ /**
+ * Find the node by value
+ * 1. tree depth: 0
+ * 2. pivot depth location: 0
+ */
+ @Test
+ fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() {
+ val n = Node(1)
+ assertEquals(n, n.find(1))
+ }
+
+ /**
+ * Find the node by value
+ * 1. tree depth: 1
+ * 2. pivot depth location: not present
+ */
+ @Test
+ fun givenDepthOne_whenPivotNotPresent_thenNull() {
+ val n = Node(1, Node(0))
+ assertNull(n.find(2))
+ }
+
+ /**
+ * Find the node by value
+ * 1. tree depth: 1
+ * 2. pivot depth location: not present
+ */
+ @Test
+ fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() {
+ val n = Node(1, Node(0))
+ assertEquals(n.left, n.find(0)
+ )
+ }
+
+ @Test
+ fun givenDepthTwo_whenPivotAtDepth2_then_Success() {
+ val left = Node(1, Node(0), Node(2))
+ val right = Node(5, Node(4), Node(6))
+ val n = Node(3, left, right)
+ assertEquals(left.left, n.find(0))
+ }
+
+
+ /**
+ * Test suit for inserting a value
+ * Partition the test as follows:
+ * 1. tree depth: 0, 1, 2, > 2
+ * 2. depth to insert: 0, 1, > 1
+ * 3. is duplicate: no, yes
+ * 4. sub-tree: left, right
+ */
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 0
+ * 2. depth to insert: 1
+ * 3. is duplicate: no
+ * 4. sub-tree: right
+ */
+ @Test
+ fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() {
+ val n = Node(1)
+ n.insert(2)
+ assertEquals(1, n.key)
+ with(n.right!!) {
+ assertEquals(2, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ assertNull(n.left)
+ }
+
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 0
+ * 2. depth to insert: 1
+ * 3. is duplicate: no
+ * 4. sub-tree: right
+ */
+ @Test
+ fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() {
+ val n = Node(1)
+ n.insert(0)
+ assertEquals(1, n.key)
+ with(n.left!!) {
+ assertEquals(0, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ assertNull(n.right)
+ }
+
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 0
+ * 2. depth to insert: 1
+ * 3. is duplicate: yes
+ */
+ @Test
+ fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() {
+ val n = Node(1)
+ n.insert(1)
+ assertEquals(1, n.key)
+ assertNull(n.right)
+ assertNull(n.left)
+ }
+
+
+ /**
+ * Test suit for inserting a value
+ * Partition the test as follows:
+ * 1. tree depth: 0, 1, 2, > 2
+ * 2. depth to insert: 0, 1, > 1
+ * 3. is duplicate: no, yes
+ * 4. sub-tree: left, right
+ */
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 1
+ * 2. depth to insert: 1
+ * 3. is duplicate: no
+ * 4. sub-tree: right
+ */
+ @Test
+ fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() {
+ val n = Node(10, Node(3))
+ n.insert(15)
+ assertEquals(10, n.key)
+ with(n.right!!) {
+ assertEquals(15, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ with(n.left!!) {
+ assertEquals(3, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ }
+
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 1
+ * 2. depth to insert: 1
+ * 3. is duplicate: no
+ * 4. sub-tree: left
+ */
+ @Test
+ fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() {
+ val n = Node(10, null, Node(15))
+ n.insert(3)
+ assertEquals(10, n.key)
+ with(n.right!!) {
+ assertEquals(15, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ with(n.left!!) {
+ assertEquals(3, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ }
+
+ /**
+ * Test for inserting a value
+ * 1. tree depth: 1
+ * 2. depth to insert: 1
+ * 3. is duplicate: yes
+ */
+ @Test
+ fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() {
+ val n = Node(10, null, Node(15))
+ n.insert(15)
+ assertEquals(10, n.key)
+ with(n.right!!) {
+ assertEquals(15, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ assertNull(n.left)
+ }
+
+ /**
+ * Test suit for removal
+ * Partition the input as follows:
+ * 1. tree depth: 0, 1, 2, > 2
+ * 2. value to delete: absent, present
+ * 3. # child nodes: 0, 1, 2
+ */
+ /**
+ * Test for removal value
+ * 1. tree depth: 0
+ * 2. value to delete: absent
+ */
+ @Test
+ fun givenTreeDepthZero_whenValueAbsent_thenNoChange() {
+ val n = Node(1)
+ n.delete(0)
+ assertEquals(1, n.key)
+ assertNull(n.left)
+ assertNull(n.right)
+ }
+
+ /**
+ * Test for removal
+ * 1. tree depth: 1
+ * 2. value to delete: absent
+ */
+ @Test
+ fun givenTreeDepthOne_whenValueAbsent_thenNoChange() {
+ val n = Node(1, Node(0), Node(2))
+ n.delete(3)
+ assertEquals(1, n.key)
+ assertEquals(2, n.right!!.key)
+ with(n.left!!) {
+ assertEquals(0, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ with(n.right!!) {
+ assertNull(left)
+ assertNull(right)
+ }
+ }
+
+ /**
+ * Test suit for removal
+ * 1. tree depth: 1
+ * 2. value to delete: present
+ * 3. # child nodes: 0
+ */
+ @Test
+ fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() {
+ val n = Node(1, Node(0))
+ n.delete(0)
+ assertEquals(1, n.key)
+ assertNull(n.left)
+ assertNull(n.right)
+ }
+
+ /**
+ * Test suit for removal
+ * 1. tree depth: 2
+ * 2. value to delete: present
+ * 3. # child nodes: 1
+ */
+ @Test
+ fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() {
+ val n = Node(2, Node(0, null, Node(1)), Node(3))
+ n.delete(0)
+ assertEquals(2, n.key)
+ with(n.right!!) {
+ assertEquals(3, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ with(n.left!!) {
+ assertEquals(1, key)
+ assertNull(left)
+ assertNull(right)
+ }
+ }
+
+ @Test
+ fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() {
+ val l = Node(2, Node(1), Node(5, Node(4), Node(6)))
+ val r = Node(10, Node(9), Node(11))
+ val n = Node(8, l, r)
+ n.delete(8)
+ assertEquals(6, n.key)
+ with(n.left!!) {
+ assertEquals(2, key)
+ assertEquals(1, left!!.key)
+ assertEquals(5, right!!.key)
+ assertEquals(4, right!!.left!!.key)
+ }
+ with(n.right!!) {
+ assertEquals(10, key)
+ assertEquals(9, left!!.key)
+ assertEquals(11, right!!.key)
+ }
+ }
+
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt
new file mode 100644
index 0000000000..f0f9267618
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt
@@ -0,0 +1,286 @@
+package com.baeldung.fuel
+
+import awaitObjectResult
+import awaitStringResponse
+import com.github.kittinunf.fuel.Fuel
+import com.github.kittinunf.fuel.core.FuelManager
+import com.github.kittinunf.fuel.core.Request
+import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor
+import com.github.kittinunf.fuel.gson.responseObject
+import com.github.kittinunf.fuel.httpGet
+import com.github.kittinunf.fuel.rx.rx_object
+import com.google.gson.Gson
+import kotlinx.coroutines.experimental.runBlocking
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Test
+import java.io.File
+import java.util.concurrent.CountDownLatch
+
+internal class FuelHttpUnitTest {
+
+ @Test
+ fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val latch = CountDownLatch(1)
+
+ "http://httpbin.org/get".httpGet().response{
+ request, response, result ->
+
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+
+ latch.countDown()
+ }
+
+ latch.await()
+
+ }
+
+ @Test
+ fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val (request, response, result) = "http://httpbin.org/get".httpGet().response()
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+
+ }
+
+ @Test
+ fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val (request, response, result) =
+ "https://jsonplaceholder.typicode.com/posts"
+ .httpGet(listOf("id" to "1")).response()
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+
+ }
+
+ @Test
+ fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val latch = CountDownLatch(1)
+
+ Fuel.post("http://httpbin.org/post").response{
+ request, response, result ->
+
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+
+ latch.countDown()
+ }
+
+ latch.await()
+
+ }
+
+ @Test
+ fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val (request, response, result) = Fuel.post("http://httpbin.org/post").response()
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+ }
+
+ @Test
+ fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
+ .body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}")
+ .response()
+
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(201,response.statusCode)
+ }
+
+ @Test
+ fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ FuelManager.instance.basePath = "http://httpbin.org"
+ FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra")
+
+ FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
+ FuelManager.instance.addRequestInterceptor(tokenInterceptor())
+
+
+ val (request, response, result) = "/get"
+ .httpGet().response()
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+ }
+
+ @Test
+ fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
+
+ FuelManager.instance.basePath = "http://httpbin.org"
+ FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
+ FuelManager.instance.addRequestInterceptor(tokenInterceptor())
+
+ val (request, response, result) = "/get"
+ .httpGet().response()
+ val (data, error) = result
+
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+ }
+
+ @Test
+ fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
+
+ Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
+ File.createTempFile("temp", ".tmp")
+ }.response{
+ request, response, result ->
+
+ val (data, error) = result
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+ }
+ }
+
+ @Test
+ fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
+
+ val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680")
+ .destination { response, url -> File.createTempFile("temp", ".tmp")
+ }.progress { readBytes, totalBytes ->
+ val progress = readBytes.toFloat() / totalBytes.toFloat()
+ }.response ()
+
+ val (data, error) = result
+ Assertions.assertNull(error)
+ Assertions.assertNotNull(data)
+ Assertions.assertEquals(200,response.statusCode)
+
+
+ }
+
+ @Test
+ fun whenMakeGetRequest_thenDeserializePostwithGson() {
+
+ val latch = CountDownLatch(1)
+
+ "https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject { _,_, result ->
+ val post = result.component1()
+ Assertions.assertEquals(1, post?.userId)
+ latch.countDown()
+ }
+
+ latch.await()
+
+ }
+
+ @Test
+ fun whenMakePOSTRequest_thenSerializePostwithGson() {
+
+ val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet")
+
+ val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
+ .header("Content-Type" to "application/json")
+ .body(Gson().toJson(post).toString())
+ .response()
+
+ Assertions.assertEquals(201,response.statusCode)
+
+ }
+
+ @Test
+ fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() {
+
+ val latch = CountDownLatch(1)
+
+
+ "https://jsonplaceholder.typicode.com/posts?id=1"
+ .httpGet().rx_object(Post.Deserializer()).subscribe{
+ res, throwable ->
+
+ val post = res.component1()
+ Assertions.assertEquals(1, post?.get(0)?.userId)
+ latch.countDown()
+ }
+
+ latch.await()
+
+ }
+
+ @Test
+ fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() {
+
+ runBlocking {
+ val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()
+
+ result.fold({ data ->
+ Assertions.assertEquals(200, response.statusCode)
+
+ }, { error -> })
+ }
+
+ }
+
+ @Test
+ fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() {
+
+
+ runBlocking {
+ Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())
+ .fold({ data ->
+ Assertions.assertEquals(1, data.get(0).userId)
+ }, { error -> })
+ }
+
+ }
+
+ @Test
+ fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() {
+
+ val latch = CountDownLatch(1)
+
+ Fuel.request(PostRoutingAPI.posts("1",null))
+ .responseObject(Post.Deserializer()) {
+ request, response, result ->
+ Assertions.assertEquals(1, result.component1()?.get(0)?.userId)
+ latch.countDown()
+ }
+
+ latch.await()
+ }
+
+ @Test
+ fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() {
+
+ val latch = CountDownLatch(1)
+
+ Fuel.request(PostRoutingAPI.comments("1",null))
+ .responseString { request, response, result ->
+ Assertions.assertEquals(200, response.statusCode)
+ latch.countDown()
+ }
+
+ latch.await()
+ }
+
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt
similarity index 99%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
rename to core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt
index 54fafdb3e1..d724933654 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt
@@ -103,7 +103,7 @@ class CoroutinesTest {
//given
val job = launch(CommonPool) {
while (isActive) {
- println("is working")
+ //println("is working")
}
}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt
new file mode 100644
index 0000000000..469118f0f6
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt
@@ -0,0 +1,191 @@
+package com.baeldung.kotlin
+
+import nl.komponents.kovenant.*
+import nl.komponents.kovenant.Kovenant.deferred
+import nl.komponents.kovenant.combine.and
+import nl.komponents.kovenant.combine.combine
+import org.junit.Assert
+import org.junit.Before
+import org.junit.Test
+import java.io.IOException
+import java.util.*
+import java.util.concurrent.TimeUnit
+
+class KovenantTest {
+ @Before
+ fun setupTestMode() {
+ Kovenant.testMode { error ->
+ println("An unexpected error occurred")
+ Assert.fail(error.message)
+ }
+ }
+
+ @Test
+ fun testSuccessfulDeferred() {
+ val def = deferred()
+ Assert.assertFalse(def.promise.isDone())
+
+ def.resolve(1L)
+ Assert.assertTrue(def.promise.isDone())
+ Assert.assertTrue(def.promise.isSuccess())
+ Assert.assertFalse(def.promise.isFailure())
+ }
+
+ @Test
+ fun testFailedDeferred() {
+ val def = deferred()
+ Assert.assertFalse(def.promise.isDone())
+
+ def.reject(RuntimeException())
+ Assert.assertTrue(def.promise.isDone())
+ Assert.assertFalse(def.promise.isSuccess())
+ Assert.assertTrue(def.promise.isFailure())
+ }
+
+ @Test
+ fun testResolveDeferredTwice() {
+ val def = deferred()
+ def.resolve(1L)
+ try {
+ def.resolve(1L)
+ } catch (e: AssertionError) {
+ // Expected.
+ // This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode()
+ }
+ }
+
+ @Test
+ fun testSuccessfulTask() {
+ val promise = task { 1L }
+ Assert.assertTrue(promise.isDone())
+ Assert.assertTrue(promise.isSuccess())
+ Assert.assertFalse(promise.isFailure())
+ }
+
+ @Test
+ fun testFailedTask() {
+ val promise = task { throw RuntimeException() }
+ Assert.assertTrue(promise.isDone())
+ Assert.assertFalse(promise.isSuccess())
+ Assert.assertTrue(promise.isFailure())
+ }
+
+ @Test
+ fun testCallbacks() {
+ val promise = task { 1L }
+
+ promise.success {
+ println("This was a success")
+ Assert.assertEquals(1L, it)
+ }
+
+ promise.fail {
+ println(it)
+ Assert.fail("This shouldn't happen")
+ }
+
+ promise.always {
+ println("This always happens")
+ }
+ }
+
+ @Test
+ fun testGetValues() {
+ val promise = task { 1L }
+ Assert.assertEquals(1L, promise.get())
+ }
+
+ @Test
+ fun testAllSucceed() {
+ val numbers = all(
+ task { 1L },
+ task { 2L },
+ task { 3L }
+ )
+
+ Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get())
+ }
+
+ @Test
+ fun testOneFails() {
+ val runtimeException = RuntimeException()
+
+ val numbers = all(
+ task { 1L },
+ task { 2L },
+ task { throw runtimeException }
+ )
+
+ Assert.assertEquals(runtimeException, numbers.getError())
+ }
+
+ @Test
+ fun testAnySucceeds() {
+ val promise = any(
+ task {
+ TimeUnit.SECONDS.sleep(3)
+ 1L
+ },
+ task {
+ TimeUnit.SECONDS.sleep(2)
+ 2L
+ },
+ task {
+ TimeUnit.SECONDS.sleep(1)
+ 3L
+ }
+ )
+
+ Assert.assertTrue(promise.isDone())
+ Assert.assertTrue(promise.isSuccess())
+ Assert.assertFalse(promise.isFailure())
+ }
+
+ @Test
+ fun testAllFails() {
+ val runtimeException = RuntimeException()
+ val ioException = IOException()
+ val illegalStateException = IllegalStateException()
+ val promise = any(
+ task {
+ TimeUnit.SECONDS.sleep(3)
+ throw runtimeException
+ },
+ task {
+ TimeUnit.SECONDS.sleep(2)
+ throw ioException
+ },
+ task {
+ TimeUnit.SECONDS.sleep(1)
+ throw illegalStateException
+ }
+ )
+
+ Assert.assertTrue(promise.isDone())
+ Assert.assertFalse(promise.isSuccess())
+ Assert.assertTrue(promise.isFailure())
+ }
+
+ @Test
+ fun testSimpleCombine() {
+ val promise = task { 1L } and task { "Hello" }
+ val result = promise.get()
+
+ Assert.assertEquals(1L, result.first)
+ Assert.assertEquals("Hello", result.second)
+ }
+
+ @Test
+ fun testLongerCombine() {
+ val promise = combine(
+ task { 1L },
+ task { "Hello" },
+ task { Currency.getInstance("USD") }
+ )
+ val result = promise.get()
+
+ Assert.assertEquals(1L, result.first)
+ Assert.assertEquals("Hello", result.second)
+ Assert.assertEquals(Currency.getInstance("USD"), result.third)
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt
new file mode 100644
index 0000000000..e37d2cc2fa
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt
@@ -0,0 +1,38 @@
+package com.baeldung.kotlin
+
+import nl.komponents.kovenant.Promise
+import nl.komponents.kovenant.any
+import nl.komponents.kovenant.task
+import org.junit.Assert
+import org.junit.Ignore
+import org.junit.Test
+
+@Ignore
+// Note that this can not run in the same test run if KovenantTest has already been executed
+class KovenantTimeoutTest {
+ @Test
+ fun testTimeout() {
+ val promise = timedTask(1000) { "Hello" }
+ val result = promise.get()
+ Assert.assertEquals("Hello", result)
+ }
+
+ @Test
+ fun testTimeoutExpired() {
+ val promise = timedTask(1000) {
+ Thread.sleep(3000)
+ "Hello"
+ }
+ val result = promise.get()
+ Assert.assertNull(result)
+ }
+
+ fun timedTask(millis: Long, body: () -> T) : Promise> {
+ val timeoutTask = task {
+ Thread.sleep(millis)
+ null
+ }
+ val activeTask = task(body = body)
+ return any(activeTask, timeoutTask)
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt
new file mode 100644
index 0000000000..9c371614a4
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt
@@ -0,0 +1,48 @@
+package com.baeldung.kotlin
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class StringConcatenationTest {
+
+ @Test
+ fun givenTwoStrings_concatenateWithTemplates_thenEquals() {
+ val a = "Hello"
+ val b = "Baeldung"
+ val c = "$a $b"
+
+ assertEquals("Hello Baeldung", c)
+ }
+
+ @Test
+ fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() {
+ val a = "Hello"
+ val b = "Baeldung"
+ val c = a + " " + b
+
+ assertEquals("Hello Baeldung", c)
+ }
+
+ @Test
+ fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() {
+ val a = "Hello"
+ val b = "Baeldung"
+
+ val builder = StringBuilder()
+ builder.append(a).append(" ").append(b)
+
+ val c = builder.toString()
+
+ assertEquals("Hello Baeldung", c)
+ }
+
+ @Test
+ fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() {
+ val a = "Hello"
+ val b = "Baeldung"
+ val c = a.plus(" ").plus(b)
+
+ assertEquals("Hello Baeldung", c)
+ }
+
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt
new file mode 100644
index 0000000000..436dc9e2ba
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt
@@ -0,0 +1,121 @@
+package com.baeldung.kotlin
+
+import org.junit.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+
+class StructuralJumpUnitTest {
+
+ @Test
+ fun givenLoop_whenBreak_thenComplete() {
+ var value = ""
+ for (i in "hello_world") {
+ if (i == '_')
+ break
+ value += i.toString()
+ }
+ assertEquals("hello", value)
+ }
+ @Test
+ fun givenLoop_whenBreakWithLabel_thenComplete() {
+ var value = ""
+ outer_loop@ for (i in 'a'..'d') {
+ for (j in 1..3) {
+ value += "" + i + j
+ if (i == 'b' && j == 1)
+ break@outer_loop
+ }
+ }
+ assertEquals("a1a2a3b1", value)
+ }
+
+ @Test
+ fun givenLoop_whenContinue_thenComplete() {
+ var result = ""
+ for (i in "hello_world") {
+ if (i == '_')
+ continue
+ result += i
+ }
+ assertEquals("helloworld", result)
+ }
+ @Test
+ fun givenLoop_whenContinueWithLabel_thenComplete() {
+ var result = ""
+ outer_loop@ for (i in 'a'..'c') {
+ for (j in 1..3) {
+ if (i == 'b')
+ continue@outer_loop
+ result += "" + i + j
+ }
+ }
+ assertEquals("a1a2a3c1c2c3", result)
+ }
+
+ @Test
+ fun givenLambda_whenReturn_thenComplete() {
+ var result = returnInLambda();
+ assertEquals("hello", result)
+ }
+
+ private fun returnInLambda(): String {
+ var result = ""
+ "hello_world".forEach {
+ // non-local return directly to the caller
+ if (it == '_') return result
+ result += it.toString()
+ }
+ //this line won't be reached
+ return result;
+ }
+
+ @Test
+ fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
+ var result = ""
+ "hello_world".forEach lit@{
+ if (it == '_') {
+ // local return to the caller of the lambda, i.e. the forEach loop
+ return@lit
+ }
+ result += it.toString()
+ }
+ assertEquals("helloworld", result)
+ }
+
+ @Test
+ fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
+ var result = ""
+ "hello_world".forEach {
+ if (it == '_') {
+ // local return to the caller of the lambda, i.e. the forEach loop
+ return@forEach
+ }
+ result += it.toString()
+ }
+ assertEquals("helloworld", result)
+ }
+
+ @Test
+ fun givenAnonymousFunction_return_thenComplete() {
+ var result = ""
+ "hello_world".forEach(fun(element) {
+ // local return to the caller of the anonymous fun, i.e. the forEach loop
+ if (element == '_') return
+ result += element.toString()
+ })
+ assertEquals("helloworld", result)
+ }
+
+ @Test
+ fun givenAnonymousFunction_returnToLabel_thenComplete() {
+ var result = ""
+ run loop@{
+ "hello_world".forEach {
+ // non-local return from the lambda passed to run
+ if (it == '_') return@loop
+ result += it.toString()
+ }
+ }
+ assertEquals("hello", result)
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt
new file mode 100644
index 0000000000..bdf44d3b49
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt
@@ -0,0 +1,30 @@
+package com.baeldung.kotlin.gson
+
+import com.google.gson.Gson
+
+import org.junit.Assert
+import org.junit.Test
+
+class GsonUnitTest {
+
+ var gson = Gson()
+
+ @Test
+ fun givenObject_thenGetJSONString() {
+ var jsonString = gson.toJson(TestModel(1,"Test"))
+ Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}")
+ }
+
+ @Test
+ fun givenJSONString_thenGetObject() {
+ var jsonString = "{\"id\":1,\"description\":\"Test\"}";
+ var testModel = gson.fromJson(jsonString, TestModel::class.java)
+ Assert.assertEquals(testModel.id, 1)
+ Assert.assertEquals(testModel.description, "Test")
+ }
+
+ data class TestModel(
+ val id: Int,
+ val description: String
+ )
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
new file mode 100644
index 0000000000..7882d85b3c
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
@@ -0,0 +1,28 @@
+package com.baeldung.nested
+
+import org.assertj.core.api.Assertions.assertThat
+import org.junit.jupiter.api.Test
+
+class ComputerUnitTest {
+
+ @Test
+ fun givenComputer_whenPowerOn_thenBlink() {
+ val computer = Computer("Desktop")
+
+ assertThat(computer.powerOn()).isEqualTo("blinking Green")
+ }
+
+ @Test
+ fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() {
+ val motherBoard = Computer.MotherBoard("MotherBoard Inc.")
+
+ assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23")
+ }
+
+ @Test
+ fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() {
+ val hardDisk = Computer("Desktop").HardDisk(1000)
+
+ assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB")
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
new file mode 100644
index 0000000000..2956a35f8a
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
@@ -0,0 +1,55 @@
+
+import org.junit.jupiter.api.Test
+import java.util.concurrent.ThreadLocalRandom
+import kotlin.test.assertTrue
+
+class RandomNumberTest {
+
+ @Test
+ fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
+ val randomNumber = Math.random()
+ assertTrue { randomNumber >=0 }
+ assertTrue { randomNumber <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble()
+ val randomInteger = ThreadLocalRandom.current().nextInt()
+ val randomLong = ThreadLocalRandom.current().nextLong()
+ assertTrue { randomDouble >= 0 }
+ assertTrue { randomDouble <= 1 }
+ assertTrue { randomInteger >= Integer.MIN_VALUE }
+ assertTrue { randomInteger <= Integer.MAX_VALUE }
+ assertTrue { randomLong >= Long.MIN_VALUE }
+ assertTrue { randomLong <= Long.MAX_VALUE }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
+ val randomDouble = Math.random()
+ assertTrue { randomDouble >=0 }
+ assertTrue { randomDouble <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
+ val randomInteger = (1..12).shuffled().first()
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 12 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
+ val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
+ val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
+ assertTrue { randomDouble >= 1 }
+ assertTrue { randomDouble <= 10 }
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 10 }
+ assertTrue { randomLong >= 1 }
+ assertTrue { randomLong <= 10 }
+ }
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out
new file mode 100644
index 0000000000..63d15d2528
--- /dev/null
+++ b/core-kotlin/src/test/resources/Kotlin.out
@@ -0,0 +1,2 @@
+Kotlin
+Concise, Safe, Interoperable, Tool-friendly
\ No newline at end of file
diff --git a/couchbase/pom.xml b/couchbase/pom.xml
index f6397fe309..4f0f8787ca 100644
--- a/couchbase/pom.xml
+++ b/couchbase/pom.xml
@@ -3,11 +3,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- couchbase-sdk
+ couchbase
0.1-SNAPSHOT
jar
couchbase
- Couchbase SDK Tutorials
+ Couchbase Tutorials
com.baeldung
diff --git a/couchbase/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/main/resources/logback.xml
+++ b/couchbase/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/couchbase/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/test/resources/logback.xml
+++ b/couchbase/src/test/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
index e3179dca32..f435e41afa 100644
--- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
+++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
@@ -57,7 +57,7 @@ public class BinaryTree {
}
public void delete(int value) {
- deleteRecursive(root, value);
+ root = deleteRecursive(root, value);
}
private Node deleteRecursive(Node current, int value) {
diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
similarity index 90%
rename from data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
rename to data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
index 99e656fe28..f81247b74d 100644
--- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
+++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
@@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class BinaryTreeTest {
+public class BinaryTreeUnitTest {
@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
@@ -70,6 +70,17 @@ public class BinaryTreeTest {
assertEquals(initialSize, bt.getSize());
}
+ @Test
+ public void it_deletes_the_root() {
+ int value = 12;
+ BinaryTree bt = new BinaryTree();
+ bt.add(value);
+
+ assertTrue(bt.containsNode(value));
+ bt.delete(value);
+ assertFalse(bt.containsNode(value));
+ }
+
@Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
similarity index 98%
rename from data-structures/src/test/java/com/baeldung/trie/TrieTest.java
rename to data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
index 6f7073651e..bf9555315c 100644
--- a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java
+++ b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Assertions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-public class TrieTest {
+public class TrieUnitTest {
@Test
public void whenEmptyTrie_thenNoElements() {
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 6f3a8d9bfd..c26dcc0cd4 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -36,22 +36,6 @@
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
org.apache.maven.plugins
maven-jar-plugin
@@ -112,6 +96,7 @@
com.jolira
onejar-maven-plugin
+ ${onejar-maven-plugin.version}
@@ -138,6 +123,7 @@
2.4.3
3.0.2
+ 1.4.4
\ No newline at end of file
diff --git a/drools/pom.xml b/drools/pom.xml
index 631bc8c792..009ac8acec 100644
--- a/drools/pom.xml
+++ b/drools/pom.xml
@@ -48,12 +48,18 @@
poi-ooxml
${apache-poi-version}