diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java new file mode 100644 index 0000000000..c3bcd048a4 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java @@ -0,0 +1,24 @@ +package com.baeldung.files; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; + +public class Main { + + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + + public static void main(String... args) throws Exception { + System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME)); + } +} diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java new file mode 100644 index 0000000000..076825d76c --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java @@ -0,0 +1,112 @@ +package com.baeldung.files; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileChannel.MapMode; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Stream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; + +public class NumberOfLineFinder { + + public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) { + int lines = 0; + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + while (reader.readLine() != null) { + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) { + int lines = 0; + try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) { + reader.skip(Integer.MAX_VALUE); + lines = reader.getLineNumber() + 1; + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingScanner(String fileName) { + int lines = 0; + try (Scanner scanner = new Scanner(new FileReader(fileName))) { + while (scanner.hasNextLine()) { + scanner.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) { + int lines = 0; + try (Stream fileStream = Files.lines(Paths.get(fileName))) { + lines = (int) fileStream.count(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) { + int lines = 1; + try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) { + ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size()); + while (byteBuffer.hasRemaining()) { + byte currentChar = byteBuffer.get(); + if (currentChar == '\n') { + lines++; + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) { + int lines = 0; + try { + LineIterator lineIterator = FileUtils.lineIterator(new File(fileName)); + while (lineIterator.hasNext()) { + lineIterator.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) { + int lines = 0; + try { + List lineItems = com.google.common.io.Files.readLines(Paths.get(fileName) + .toFile(), Charset.defaultCharset()); + lines = lineItems.size(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java new file mode 100644 index 0000000000..6f0427ebd2 --- /dev/null +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.file; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NumberOfLineFinderUnitTest { + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + private static final int ACTUAL_LINE_COUNT = 45; + + @Test + public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingScanner_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java new file mode 100644 index 0000000000..6be9a18781 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class Car { + + private List wheels; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java new file mode 100644 index 0000000000..96c07f13a4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java @@ -0,0 +1,13 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class CarWithStaticInnerWheel { + + private List wheels; + + public static class Wheel { + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java new file mode 100644 index 0000000000..1f38ea85ad --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.aggregation; + +public class Wheel { + + private Car car; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java new file mode 100644 index 0000000000..4c748e8084 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.association; + +public class Child { + + private Mother mother; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java new file mode 100644 index 0000000000..0e8edef125 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.association; + +import java.util.List; + +public class Mother { + + private List children; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java new file mode 100644 index 0000000000..1ab44f73fa --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java @@ -0,0 +1,18 @@ +package com.baeldung.relationships.composition; + +import java.util.List; + +public class Building { + + private String address; + private List rooms; + + public class Room { + + public String getBuildingAddress() { + return Building.this.address; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java new file mode 100644 index 0000000000..4e3411cf30 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java @@ -0,0 +1,28 @@ +package com.baeldung.relationships.composition; + +public class BuildingWithDefinitionRoomInMethod { + + public Room createAnonymousRoom() { + return new Room() { + @Override + public void doInRoom() {} + }; + } + + public Room createInlineRoom() { + class InlineRoom implements Room { + @Override + public void doInRoom() {} + } + return new InlineRoom(); + } + + public Room createLambdaRoom() { + return () -> {}; + } + + public interface Room { + void doInRoom(); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java new file mode 100644 index 0000000000..63cfd1b89e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Department { + + private List professors; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java new file mode 100644 index 0000000000..8e1258c3e6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java @@ -0,0 +1,10 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Professor { + + private List department; + private List friends; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java new file mode 100644 index 0000000000..e5e518e0f1 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class University { + + private List department; + +} diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java new file mode 100644 index 0000000000..ee17c1e8ea --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.incrementdecrementunaryoperator; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class IncrementDecrementUnaryOperatorUnitTest { + + @Test + public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + ++operand; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() { + int operand = 1; + int number = ++operand; + assertThat(number).isEqualTo(2); + } + + @Test + public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + --operand; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() { + int operand = 1; + int number = --operand; + assertThat(number).isEqualTo(0); + } + + @Test + public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + operand++; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand++; + assertThat(number).isEqualTo(1); + } + + @Test + public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + operand--; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand--; + assertThat(number).isEqualTo(1); + } +} diff --git a/core-java-modules/core-java-networking-2/.gitignore b/core-java-modules/core-java-networking-2/.gitignore deleted file mode 100644 index 374c8bf907..0000000000 --- a/core-java-modules/core-java-networking-2/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java new file mode 100644 index 0000000000..d73f2a2708 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java @@ -0,0 +1,29 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.RealmCallback; + +public class ClientCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java new file mode 100644 index 0000000000..3e071d68cc --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.AuthorizeCallback; +import javax.security.sasl.RealmCallback; + +public class ServerCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof AuthorizeCallback) { + AuthorizeCallback ac = (AuthorizeCallback) cb; + ac.setAuthorized(true); + } else if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java new file mode 100644 index 0000000000..6601654781 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.sasl; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SaslUnitTest { + + private static final String MECHANISM = "DIGEST-MD5"; + private static final String SERVER_NAME = "myServer"; + private static final String PROTOCOL = "myProtocol"; + private static final String AUTHORIZATION_ID = null; + private static final String QOP_LEVEL = "auth-conf"; + + private SaslServer saslServer; + private SaslClient saslClient; + + @Before + public void setUp() throws SaslException { + + ServerCallbackHandler serverHandler = new ServerCallbackHandler(); + ClientCallbackHandler clientHandler = new ClientCallbackHandler(); + + Map props = new HashMap<>(); + props.put(Sasl.QOP, QOP_LEVEL); + + saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler); + saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler); + + } + + @Test + public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException { + + byte[] challenge; + byte[] response; + + challenge = saslServer.evaluateResponse(new byte[0]); + response = saslClient.evaluateChallenge(challenge); + + challenge = saslServer.evaluateResponse(response); + response = saslClient.evaluateChallenge(challenge); + + assertTrue(saslServer.isComplete()); + assertTrue(saslClient.isComplete()); + + String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP); + assertEquals("auth-conf", qop); + + byte[] outgoing = "Baeldung".getBytes(); + byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length); + + byte[] secureIncoming = secureOutgoing; + byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length); + assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8)); + } + + @After + public void tearDown() throws SaslException { + saslClient.dispose(); + saslServer.dispose(); + } + +} diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java index 16b7e04297..40df2c713a 100644 --- a/data-structures/src/main/java/com/baeldung/graph/Graph.java +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -2,6 +2,7 @@ package com.baeldung.graph; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; @@ -29,7 +30,7 @@ public class Graph { while (!stack.isEmpty()) { int current = stack.pop(); isVisited[current] = true; - System.out.print(" " + current); + visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) stack.push(dest); @@ -44,29 +45,30 @@ public class Graph { private void dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; - System.out.print(" " + current); + visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } } - public void topologicalSort(int start) { - Stack result = new Stack(); + public List topologicalSort(int start) { + LinkedList result = new LinkedList(); boolean[] isVisited = new boolean[adjVertices.size()]; topologicalSortRecursive(start, isVisited, result); - while (!result.isEmpty()) { - System.out.print(" " + result.pop()); - } + return result; } - private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { + private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList result) { isVisited[current] = true; for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) topologicalSortRecursive(dest, isVisited, result); } - result.push(current); + result.addFirst(current); } + private void visit(int value) { + System.out.print(" " + value); + } } 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 ff73ee8e54..bb62714006 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -103,14 +103,14 @@ public class BinaryTree { public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); - System.out.print(" " + node.value); + visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { - System.out.print(" " + node.value); + visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } @@ -120,7 +120,7 @@ public class BinaryTree { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); - System.out.print(" " + node.value); + visit(node.value); } } @@ -159,7 +159,7 @@ public class BinaryTree { stack.push(current); } current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); if(current.right != null) { current = current.right; stack.push(current); @@ -173,7 +173,7 @@ public class BinaryTree { stack.push(root); while(! stack.isEmpty()) { current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); if(current.right != null) stack.push(current.right); @@ -196,7 +196,7 @@ public class BinaryTree { if (!hasChild || isPrevLastChild) { current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); prev = current; } else { if (current.right != null) { @@ -209,6 +209,9 @@ public class BinaryTree { } } + private void visit(int value) { + System.out.print(" " + value); + } class Node { int value; diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java index 249cb6e093..09b92115d2 100644 --- a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.graph; +import java.util.List; + import org.junit.Test; public class GraphUnitTest { @@ -15,7 +17,8 @@ public class GraphUnitTest { @Test public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { Graph graph = createDirectedGraph(); - graph.topologicalSort(0); + List list = graph.topologicalSort(0); + System.out.println(list); } private Graph createDirectedGraph() { diff --git a/java-numbers-2/.gitignore b/java-numbers-2/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/java-numbers-2/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java new file mode 100644 index 0000000000..effdee07ad --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java @@ -0,0 +1,148 @@ +package com.baeldung.binarynumbers; + +public class BinaryNumbers { + + /** + * This method takes a decimal number and convert it into a binary number. + * example:- input:10, output:1010 + * + * @param decimalNumber + * @return binary number + */ + public Integer convertDecimalToBinary(Integer decimalNumber) { + + if (decimalNumber == 0) { + return decimalNumber; + } + + StringBuilder binaryNumber = new StringBuilder(); + + while (decimalNumber > 0) { + + int remainder = decimalNumber % 2; + int result = decimalNumber / 2; + + binaryNumber.append(remainder); + decimalNumber = result; + } + + binaryNumber = binaryNumber.reverse(); + + return Integer.valueOf(binaryNumber.toString()); + } + + /** + * This method takes a binary number and convert it into a decimal number. + * example:- input:101, output:5 + * + * @param binary number + * @return decimal Number + */ + public Integer convertBinaryToDecimal(Integer binaryNumber) { + + Integer result = 0; + Integer base = 1; + + while (binaryNumber > 0) { + + int lastDigit = binaryNumber % 10; + binaryNumber = binaryNumber / 10; + + result += lastDigit * base; + + base = base * 2; + } + return result; + } + + /** + * This method accepts two binary numbers and returns sum of input numbers. + * Example:- firstNum: 101, secondNum: 100, output: 1001 + * + * @param firstNum + * @param secondNum + * @return addition of input numbers + */ + public Integer addBinaryNumber(Integer firstNum, Integer secondNum) { + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || secondNum != 0) { + + temp = (firstNum % 10 + secondNum % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + secondNum % 10 + carry) / 2; + + firstNum = firstNum / 10; + secondNum = secondNum / 10; + } + + if (carry != 0) { + output.append(carry); + } + + return Integer.valueOf(output.reverse() + .toString()); + } + + /** + * This method takes two binary number as input and subtract second number from the first number. + * example:- firstNum: 1000, secondNum: 11, output: 101 + * @param firstNum + * @param secondNum + * @return Result of subtraction of secondNum from first + */ + public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) { + + int onesComplement = Integer.valueOf(getOnesComplement(secondNum)); + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || onesComplement != 0) { + + temp = (firstNum % 10 + onesComplement % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + onesComplement % 10 + carry) / 2; + + firstNum = firstNum / 10; + onesComplement = onesComplement / 10; + } + + String additionOfFirstNumAndOnesComplement = output.reverse() + .toString(); + + if (carry == 1) { + return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry); + } else { + return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement)); + } + + } + + public Integer getOnesComplement(Integer num) { + + StringBuilder onesComplement = new StringBuilder(); + + while (num > 0) { + int lastDigit = num % 10; + if (lastDigit == 0) { + onesComplement.append(1); + } else { + onesComplement.append(0); + } + num = num / 10; + } + + return Integer.valueOf(onesComplement.reverse() + .toString()); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java new file mode 100644 index 0000000000..ca6022261d --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.binarynumbers; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BinaryNumbersUnitTest { + + private BinaryNumbers binaryNumbers = new BinaryNumbers(); + + @Test + public void given_decimalNumber_then_returnBinaryNumber() { + assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8)); + assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20)); + } + + @Test + public void given_decimalNumber_then_convertToBinaryNumber() { + assertEquals("1000", Integer.toBinaryString(8)); + assertEquals("10100", Integer.toBinaryString(20)); + } + + @Test + public void given_binaryNumber_then_ConvertToDecimalNumber() { + assertEquals(8, Integer.parseInt("1000", 2)); + assertEquals(20, Integer.parseInt("10100", 2)); + } + + @Test + public void given_binaryNumber_then_returnDecimalNumber() { + assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000)); + assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100)); + } + + @Test + public void given_twoBinaryNumber_then_returnAddition() { + // adding 4 and 10 + assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010)); + + // adding 26 and 14 + assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110)); + } + + @Test + public void given_twoBinaryNumber_then_returnSubtraction() { + // subtracting 16 from 25 + assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000)); + + // subtracting 29 from 16, the output here is negative + assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101)); + } + + @Test + public void given_binaryLiteral_thenReturnDecimalValue() { + + byte five = 0b101; + assertEquals((byte) 5, five); + + short three = 0b11; + assertEquals((short) 3, three); + + int nine = 0B1001; + assertEquals(9, nine); + + long twentyNine = 0B11101; + assertEquals(29, twentyNine); + + int minusThirtySeven = -0B100101; + assertEquals(-37, minusThirtySeven); + + } + +} diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index c6d4f0222a..b4b16fbaef 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -3,5 +3,20 @@ - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Java – Generate Random String](http://www.baeldung.com/java-random-string) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) +- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) +- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) +- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) +- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) +- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) - [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) - [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml index 7342953d15..be47b1ec89 100755 --- a/java-strings-2/pom.xml +++ b/java-strings-2/pom.xml @@ -40,6 +40,16 @@ commons-lang3 ${commons-lang3.version} + + commons-io + commons-io + ${commons-io.version} + + + commons-codec + commons-codec + ${commons-codec.version} + junit junit @@ -52,32 +62,54 @@ ${org.hamcrest.version} test + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.passay + passay + ${passay.version} + org.apache.commons commons-text ${commons-text.version} + + com.vdurmont + emoji-java + ${emoji-java.version} + + + org.ahocorasick + ahocorasick + ${ahocorasick.version} + javax.validation validation-api - 2.0.0.Final + ${validation-api.version} org.hibernate.validator hibernate-validator - 6.0.2.Final + ${hibernate-validator.version} javax.el javax.el-api - 3.0.0 + ${javax.el-api.version} org.glassfish.web javax.el - 2.2.6 + ${javax.el.version} - @@ -105,9 +137,19 @@ 3.8.1 + 1.10 + 1.3.1 + + 3.6.1 + 4.0.0 + 0.4.0 61.1 28.0-jre 1.4 + 2.0.0.Final + 6.0.2.Final + 3.0.0 + 2.2.6 \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/MatchWords.java rename to java-strings-2/src/main/java/com/baeldung/string/MatchWords.java diff --git a/java-strings/src/main/java/com/baeldung/string/Pangram.java b/java-strings-2/src/main/java/com/baeldung/string/Pangram.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Pangram.java rename to java-strings-2/src/main/java/com/baeldung/string/Pangram.java diff --git a/java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java b/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java rename to java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java rename to java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java rename to java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java rename to java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java new file mode 100644 index 0000000000..9abb7ac453 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.string.todouble; + +import static org.junit.Assert.assertEquals; + +import java.text.DecimalFormat; +import java.text.ParseException; + +import org.junit.Test; + +public class StringToDoubleConversionUnitTest { + + @Test + public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.parseDouble("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() { + Double.parseDouble(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() { + Double.parseDouble("&"); + } + + @Test + public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.valueOf("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() { + Double.valueOf(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() { + Double.valueOf("&"); + } + + @Test + public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException { + assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse(null); + } + + @Test(expected = ParseException.class) + public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse("&"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java diff --git a/java-strings/src/test/resources/test_image.jpg b/java-strings-2/src/test/resources/test_image.jpg similarity index 100% rename from java-strings/src/test/resources/test_image.jpg rename to java-strings-2/src/test/resources/test_image.jpg diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md new file mode 100644 index 0000000000..d909f171a7 --- /dev/null +++ b/java-strings-ops/README.md @@ -0,0 +1,22 @@ +========= + +## Java Strings Cookbooks and Examples + +### Relevant Articles: +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Java String Conversions](https://www.baeldung.com/java-string-conversions) +- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) +- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Split a String in Java](http://www.baeldung.com/java-split-string) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) +- [Java toString() Method](https://www.baeldung.com/java-tostring) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) \ No newline at end of file diff --git a/java-strings-ops/pom.xml b/java-strings-ops/pom.xml new file mode 100644 index 0000000000..b6a7ea2728 --- /dev/null +++ b/java-strings-ops/pom.xml @@ -0,0 +1,99 @@ + + 4.0.0 + com.baeldung + java-strings-ops + 0.1.0-SNAPSHOT + jar + java-strings-ops + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + com.google.guava + guava + ${guava.version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + java-strings-ops + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + -parameters + + + + + + + + 3.8.1 + + 3.6.1 + 27.0.1-jre + 5.3.1 + + + diff --git a/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java rename to java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java diff --git a/java-strings/src/main/java/com/baeldung/string/Palindrome.java b/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Palindrome.java rename to java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringHelper.java b/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringHelper.java rename to java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Customer.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Order.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java diff --git a/spring-security-mvc-boot/src/main/resources/logback.xml b/java-strings-ops/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/logback.xml rename to java-strings-ops/src/main/resources/logback.xml diff --git a/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/README.md b/java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/README.md rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/spring-boot-properties/.gitignore b/java-strings-ops/src/test/resources/.gitignore similarity index 82% rename from spring-boot-properties/.gitignore rename to java-strings-ops/src/test/resources/.gitignore index 0532ef1888..83c05e60c8 100644 --- a/spring-boot-properties/.gitignore +++ b/java-strings-ops/src/test/resources/.gitignore @@ -10,8 +10,4 @@ # Packaged files # *.jar *.war -*.ear - -*.ipr -*.iml -*.iws +*.ear \ No newline at end of file diff --git a/java-strings/README.md b/java-strings/README.md index b342f53918..ef536b4099 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -6,51 +6,18 @@ - [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) - [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) -- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) -- [Java – Generate Random String](http://www.baeldung.com/java-random-string) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) -- [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) -- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) -- [Split a String in Java](http://www.baeldung.com/java-split-string) -- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) -- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) -- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) -- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) -- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) -- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) - [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) - [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) -- [Get Substring from String in Java](https://www.baeldung.com/java-substring) - [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) -- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) -- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) -- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) -- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) -- [Java toString() Method](https://www.baeldung.com/java-tostring) -- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) -- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) -- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) \ No newline at end of file diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 7f66b95355..42a57bfb42 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -62,12 +62,6 @@ guava ${guava.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - org.junit.jupiter @@ -83,24 +77,6 @@ test - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - @@ -134,11 +110,8 @@ 3.6.1 61.1 27.0.1-jre - 4.0.0 5.3.1 - 1.3.1 1.4 - 0.4.0 diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java new file mode 100644 index 0000000000..b4d80db0ab --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java @@ -0,0 +1,57 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping") +public class MyHttpServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter writer = response.getWriter(); + writer.println(request.getParameter("function")); + if ("getContextPath".equals(request.getParameter("function"))) { + writer.println(request.getContextPath()); + } else if ("getLocalAddr".equals(request.getParameter("function"))) { + writer.println(request.getLocalAddr()); + } else if ("getLocalName".equals(request.getParameter("function"))) { + writer.println(request.getLocalName()); + } else if ("getLocalAPort".equals(request.getParameter("function"))) { + writer.println(request.getLocalPort()); + } else if ("getMethod".equals(request.getParameter("function"))) { + writer.println(request.getMethod()); + } else if ("getParameterNames".equals(request.getParameter("function"))) { + writer.println(request.getParameterNames()); + } else if ("getPathInfo".equals(request.getParameter("function"))) { + writer.println(request.getPathInfo()); + } else if ("getProtocol".equals(request.getParameter("function"))) { + writer.println(request.getProtocol()); + } else if ("getQueryString".equals(request.getParameter("function"))) { + writer.println(request.getQueryString()); + } else if ("getRequestedSessionId".equals(request.getParameter("function"))) { + writer.println(request.getRequestedSessionId()); + } else if ("getRequestURI".equals(request.getParameter("function"))) { + writer.println(request.getRequestURI()); + } else if ("getRequestURL".equals(request.getParameter("function"))) { + writer.println(request.getRequestURL()); + } else if ("getScheme".equals(request.getParameter("function"))) { + writer.println(request.getScheme()); + } else if ("getServerName".equals(request.getParameter("function"))) { + writer.println(request.getServerName()); + } else if ("getServerPort".equals(request.getParameter("function"))) { + writer.println(request.getServerPort()); + } else if ("getServletPath".equals(request.getParameter("function"))) { + writer.println(request.getServletPath()); + } else { + writer.println("INVALID FUNCTION"); + } + writer.flush(); + } + +} + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java deleted file mode 100644 index 84b9a89c54..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java +++ /dev/null @@ -1,209 +0,0 @@ -//package com.baeldung.security.oauth2.server.web; -// -//import AuthorizationCode; -//import Client; -//import User; -//import com.baeldung.security.oauth2.server.service.AuthCodeService; -// -//import javax.ejb.EJB; -//import javax.enterprise.context.RequestScoped; -//import javax.inject.Inject; -//import javax.persistence.EntityManager; -//import javax.persistence.PersistenceContext; -//import javax.security.enterprise.SecurityContext; -//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; -//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; -//import javax.servlet.ServletException; -//import javax.servlet.annotation.HttpConstraint; -//import javax.servlet.annotation.ServletSecurity; -//import javax.servlet.annotation.WebServlet; -//import javax.servlet.http.HttpServlet; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -//import java.io.IOException; -//import java.security.Principal; -//import java.util.*; -// -///** -// * 1. GET http://localhost:8080/app/ (302) -// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) -// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input -// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302) -// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200) -// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) -// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200) -// */ -///* -// -//Query Params: -// client_id: app -// redirect_uri: http://localhost:8080/app/ -// response_type: code -// state: A123 -// -// ==> GET user login WITH client request as hidden input: -// -// -// ==> After user login ==> Initial client request -// ==> gen code -// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123 -//*/ -// -////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 -////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123 -// -////@RequestScoped -//@FormAuthenticationMechanismDefinition( -// loginToContinue = @LoginToContinue( -// loginPage = "/login-servlet", -// errorPage = "/login-error-servlet" -// ) -//) -//@WebServlet({"/authorize"}) -//@ServletSecurity(@HttpConstraint(rolesAllowed = "user")) -////@Stateless -//@RequestScoped -//public class AuthorizationEndpoint extends HttpServlet { -// -// private static final List authorizedResponseTypes = Arrays.asList("code", "token"); -// -// @Inject -// private SecurityContext securityContext; -// -// @PersistenceContext(name = "jpa-oauth2-pu") -// private EntityManager entityManager; -// -// @EJB -// private AuthCodeService authCodeService; -// -// //HTTP GET IS A MUST, POST IS OPTIONAL -// @Override -// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// -// String error = ""; -// -// //1. User Authentication -// Principal principal = securityContext.getCallerPrincipal(); -// -// //2. Check for a valid client_id -// String clientId = request.getParameter("client_id"); -// if (clientId == null) { -// request.setAttribute("error", "The client " + clientId + " doesn't exist."); -// } -// request.setAttribute("clientId", clientId); -// Client client = entityManager.find(Client.class, clientId); -// if (client == null) { -// request.setAttribute("error", "The client " + clientId + " doesn't exist."); -// } -// -// //3. check for a valid response_type -// String responseType = request.getParameter("response_type"); -// if (!authorizedResponseTypes.contains(responseType)) { -// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; -// request.setAttribute("error", error); -// request.getRequestDispatcher("/error.jsp") -// .forward(request, response); -// } -// -// //4. Optional redirect_uri, if provided should match -// String redirectUri = request.getParameter("redirect_uri"); -// checkRedirectUri(client, redirectUri); -// -// //save params -// String currentUri = request.getRequestURI(); -// request.setAttribute("post_redirect_uri", currentUri); -// -// String state = request.getParameter("state"); -// Map requestMap = new HashMap<>(); -// requestMap.put("response_type", responseType); -// requestMap.put("client_id", clientId); -// requestMap.put("redirect_uri", redirectUri); -// requestMap.put("state", state); -// request.setAttribute("requestMap", requestMap); -// -// //5.scope: Optional -// String requestedScope = request.getParameter("scope"); -// if (requestedScope.isEmpty()) { -// requestedScope = client.getScope(); -// } -// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes) -// //checkRequestedScope(requestedScope, client.getScope()); -// -// //sub set of user scope -// //allowed scope by the user -// -// User user = entityManager.find(User.class, principal.getName()); -// request.setAttribute("scopes", requestedScope); -// -// -// forward("/authorize.jsp", request, response); -// } -// -// @Override -// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// String clientId = request.getParameter("client_id"); -// -// String responseType = request.getParameter("response_type"); -// if (!authorizedResponseTypes.contains(responseType)) { -// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; -// request.setAttribute("error", error); -// forward("/error.jsp", request, response); -// } -// -// Client client = entityManager.find(Client.class, clientId); -// Objects.requireNonNull(client); -// -// String userId = securityContext.getCallerPrincipal().getName(); -// AuthorizationCode authorizationCode = new AuthorizationCode(); -// authorizationCode.setClientId(clientId); -// authorizationCode.setUserId(userId); -// String redirectUri = request.getParameter("redirect_uri"); -// authorizationCode.setRedirectUri(redirectUri); -// -// redirectUri = checkRedirectUri(client, redirectUri); -// -// String[] scope = request.getParameterValues("scope"); -// if (scope == null) { -// request.setAttribute("error", "User doesn't approved any scope"); -// forward("/error.jsp", request, response); -// } -// -// String approvedScopes = String.join(" ", scope); -// authorizationCode.setApprovedScopes(approvedScopes); -// -// //entityManager.persist(authorizationCode); -// authCodeService.save(authorizationCode); -// String code = authorizationCode.getCode(); -// -// StringBuilder sb = new StringBuilder(redirectUri); -// sb.append("?code=").append(code); -// -// //If the client send a state, Send it back -// String state = request.getParameter("state"); -// if (state != null) { -// sb.append("&state=").append(state); -// } -// response.sendRedirect(sb.toString()); -// } -// -// private String checkRedirectUri(Client client, String redirectUri) { -// //redirect uri -// if (redirectUri == null) { -// //erreur: param redirect_uri && client redirect_uri don't match. -// redirectUri = client.getRedirectUri(); -// if (redirectUri == null) { -// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri."); -// } -// } else if (!redirectUri.equals(client.getRedirectUri())) { -// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match."); -// } -// return redirectUri; -// } -// -// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// request.getRequestDispatcher(path) -// .forward(request, response); -// } -//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java deleted file mode 100644 index 73085a68d1..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java +++ /dev/null @@ -1,70 +0,0 @@ -//package com.baeldung.security.oauth2.server.web; -// -//import AuthorizationGrantTypeHandler; -//import TokenResponse; -//import com.baeldung.security.oauth2.server.security.Authenticated; -//import com.nimbusds.jose.JOSEException; -// -//import javax.enterprise.inject.Instance; -//import javax.enterprise.inject.literal.NamedLiteral; -//import javax.inject.Inject; -//import javax.security.enterprise.SecurityContext; -//import javax.ws.rs.Consumes; -//import javax.ws.rs.POST; -//import javax.ws.rs.Path; -//import javax.ws.rs.Produces; -//import javax.ws.rs.core.MediaType; -//import javax.ws.rs.core.MultivaluedMap; -//import javax.ws.rs.core.Response; -//import java.security.Principal; -//import java.util.Arrays; -//import java.util.List; -//import java.util.Objects; -// -///** -// * { -// * "access_token" : "acb6803a48114d9fb4761e403c17f812", -// * "token_type" : "bearer", -// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ", -// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r", -// * "expires_in" : 43199, -// * "scope" : "openid oauth.approvals", -// * "jti" : "acb6803a48114d9fb4761e403c17f812" -// * } -// */ -//@Path("token") -//public class TokenEndpoint { -// -// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials"); -// -// @Inject -// private SecurityContext securityContext; -// -// @Inject -// Instance authorizationGrantTypeHandlers; -// -// @POST -// @Produces(MediaType.APPLICATION_JSON) -// @Consumes(MediaType.APPLICATION_FORM_URLENCODED) -// @Authenticated -// public Response token(MultivaluedMap params) throws JOSEException { -// //Authenticate client with [basic] http authentication mechanism -// Principal principal = securityContext.getCallerPrincipal(); -// Objects.requireNonNull(principal, "Client not authenticated!"); -// -// //Check grant_type params -// String grantType = params.getFirst("grant_type"); -// Objects.requireNonNull(grantType, "grant_type params is required"); -// //authorization_code, password, refresh, client_credentials -// if (!supportedGrantTypes.contains(grantType)) { -// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes); -// } -// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); -// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params); -// Response response = Response.ok(tokenResponse) -// .header("Cache-Control", "no-store") -// .header("Pragma", "no-cache") -// .build(); -// return response; -// } -//} diff --git a/patterns/backoff-jitter/README.md b/patterns/backoff-jitter/README.md new file mode 100644 index 0000000000..6459e4c8e0 --- /dev/null +++ b/patterns/backoff-jitter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Better Retries with Exponential Backoff and Jitter](https://baeldung.com/retries-with-exponential-backoff-and-jitter) diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml new file mode 100644 index 0000000000..6b0d016609 --- /dev/null +++ b/patterns/backoff-jitter/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.baeldung + backoff-jitter + 1.0.0-SNAPSHOT + pom + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + test + + + org.slf4j + slf4j-simple + ${slf4j.version} + test + + + + + UTF-8 + 1.8 + 1.8 + 4.12 + 2.27.0 + 1.7.26 + 0.16.0 + + + \ No newline at end of file diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java new file mode 100644 index 0000000000..f6b3ebbe45 --- /dev/null +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -0,0 +1,103 @@ +package com.baeldung.backoff.jitter; + +import io.github.resilience4j.retry.IntervalFunction; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; + +import static com.baeldung.backoff.jitter.BackoffWithJitterTest.RetryProperties.*; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialBackoff; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialRandomBackoff; +import static java.util.Collections.nCopies; +import static java.util.concurrent.Executors.newFixedThreadPool; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +public class BackoffWithJitterTest { + + static Logger log = LoggerFactory.getLogger(BackoffWithJitterTest.class); + + interface PingPongService { + + String call(String ping) throws PingPongServiceException; + } + + class PingPongServiceException extends RuntimeException { + + public PingPongServiceException(String reason) { + super(reason); + } + } + + private PingPongService service; + private static final int NUM_CONCURRENT_CLIENTS = 8; + + @Before + public void setUp() { + service = mock(PingPongService.class); + } + + @Test + public void whenRetryExponentialBackoff_thenRetriedConfiguredNoOfTimes() { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + Function pingPongFn = getRetryablePingPongFn(intervalFn); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + try { + pingPongFn.apply("Hello"); + } catch (PingPongServiceException e) { + verify(service, times(MAX_RETRIES)).call(anyString()); + } + } + + @Test + public void whenRetryExponentialBackoffWithoutJitter_thenThunderingHerdProblemOccurs() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + test(intervalFn); + } + + @Test + public void whenRetryExponentialBackoffWithJitter_thenRetriesAreSpread() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialRandomBackoff(INITIAL_INTERVAL, MULTIPLIER, RANDOMIZATION_FACTOR); + test(intervalFn); + } + + private void test(IntervalFunction intervalFn) throws InterruptedException { + Function pingPongFn = getRetryablePingPongFn(intervalFn); + ExecutorService executors = newFixedThreadPool(NUM_CONCURRENT_CLIENTS); + List> tasks = nCopies(NUM_CONCURRENT_CLIENTS, () -> pingPongFn.apply("Hello")); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + + executors.invokeAll(tasks); + } + + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { + RetryConfig retryConfig = RetryConfig.custom() + .maxAttempts(MAX_RETRIES) + .intervalFunction(intervalFn) + .retryExceptions(PingPongServiceException.class) + .build(); + Retry retry = Retry.of("pingpong", retryConfig); + return Retry.decorateFunction(retry, ping -> { + log.info("Invoked at {}", LocalDateTime.now()); + return service.call(ping); + }); + } + + static class RetryProperties { + static final Long INITIAL_INTERVAL = 1000L; + static final Double MULTIPLIER = 2.0D; + static final Double RANDOMIZATION_FACTOR = 0.6D; + static final Integer MAX_RETRIES = 4; + } +} diff --git a/patterns/pom.xml b/patterns/pom.xml index 2be9d2519e..7f7368ca07 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -19,7 +19,8 @@ design-patterns design-patterns-2 solid - dip + dip + backoff-jitter diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 708d2b3c76..e7c93bc4e5 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -4,7 +4,7 @@ com.baeldung java-cassandra 1.0.0-SNAPSHOT - java-cassandra + java-cassandra com.baeldung @@ -29,6 +29,19 @@ ${cassandra-unit.version} + + + com.datastax.oss + java-driver-core + ${datastax-cassandra.version} + + + + io.netty + netty-handler + ${io-netty.version} + + @@ -39,6 +52,8 @@ 3.1.2 3.1.1.0 + 4.1.0 + 4.1.34.Final 18.0 diff --git a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java new file mode 100644 index 0000000000..23140e0455 --- /dev/null +++ b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java @@ -0,0 +1,46 @@ +package com.baeldung.datastax.cassandra; + +import com.baeldung.datastax.cassandra.domain.Video; +import com.baeldung.datastax.cassandra.repository.KeyspaceRepository; +import com.baeldung.datastax.cassandra.repository.VideoRepository; +import com.datastax.oss.driver.api.core.CqlSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; + +public class Application { + + private static final Logger LOG = LoggerFactory.getLogger(Application.class); + + public static void main(String[] args) { + new Application().run(); + } + + public void run() { + CassandraConnector connector = new CassandraConnector(); + connector.connect("127.0.0.1", 9042, "datacenter1"); + CqlSession session = connector.getSession(); + + KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session); + + keyspaceRepository.createKeyspace("testKeyspace", "SimpleStrategy", 1); + keyspaceRepository.useKeyspace("testKeyspace"); + + VideoRepository videoRepository = new VideoRepository(session); + + videoRepository.createTable(); + + videoRepository.insertVideo(new Video("Video Title 1", Instant.now())); + videoRepository.insertVideo(new Video("Video Title 2", + Instant.now().minus(1, ChronoUnit.DAYS))); + + List