diff --git a/.gitignore b/.gitignore
index 60c38ed8f5..1890e8bd0e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,3 +33,11 @@ spring-openid/src/main/resources/application.properties
spring-security-openid/src/main/resources/application.properties
spring-all/*.log
+
+*.jar
+
+SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
+
+spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
+
+spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
diff --git a/akka-streams/README.md b/akka-streams/README.md
new file mode 100644
index 0000000000..7f2751422b
--- /dev/null
+++ b/akka-streams/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Guide to Akka Streams](http://www.baeldung.com/akka-streams)
diff --git a/akka-streams/pom.xml b/akka-streams/pom.xml
new file mode 100644
index 0000000000..b1471641f7
--- /dev/null
+++ b/akka-streams/pom.xml
@@ -0,0 +1,30 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+ akka-streams
+ akka-streams
+
+
+
+ com.typesafe.akka
+ akka-stream_2.11
+ ${akkastreams.version}
+
+
+ com.typesafe.akka
+ akka-stream-testkit_2.11
+ ${akkastreams.version}
+
+
+
+ 2.5.2
+
+
+
\ No newline at end of file
diff --git a/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java b/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java
new file mode 100644
index 0000000000..8cfae6d52a
--- /dev/null
+++ b/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java
@@ -0,0 +1,14 @@
+package com.baeldung.akkastreams;
+
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+
+public class AverageRepository {
+ CompletionStage save(Double average) {
+ return CompletableFuture.supplyAsync(() -> {
+ System.out.println("saving average: " + average);
+ return average;
+ });
+ }
+}
diff --git a/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java b/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java
new file mode 100644
index 0000000000..92701e4e37
--- /dev/null
+++ b/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java
@@ -0,0 +1,74 @@
+package com.baeldung.akkastreams;
+
+
+import akka.Done;
+import akka.NotUsed;
+import akka.actor.ActorSystem;
+import akka.stream.ActorMaterializer;
+import akka.stream.javadsl.Flow;
+import akka.stream.javadsl.Keep;
+import akka.stream.javadsl.Sink;
+import akka.stream.javadsl.Source;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.stream.Collectors;
+
+public class DataImporter {
+ private final ActorSystem actorSystem;
+ private final AverageRepository averageRepository = new AverageRepository();
+
+ public DataImporter(ActorSystem actorSystem) {
+ this.actorSystem = actorSystem;
+
+ }
+
+ private List parseLine(String line) {
+ String[] fields = line.split(";");
+ return Arrays.stream(fields)
+ .map(Integer::parseInt)
+ .collect(Collectors.toList());
+ }
+
+ private Flow parseContent() {
+ return Flow.of(String.class).mapConcat(this::parseLine);
+ }
+
+ private Flow computeAverage() {
+ return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers ->
+ CompletableFuture.supplyAsync(() -> integers
+ .stream()
+ .mapToDouble(v -> v)
+ .average()
+ .orElse(-1.0)));
+ }
+
+ Flow calculateAverage() {
+ return Flow.of(String.class)
+ .via(parseContent())
+ .via(computeAverage());
+ }
+
+ private Sink> storeAverages() {
+ return Flow.of(Double.class)
+ .mapAsyncUnordered(4, averageRepository::save)
+ .toMat(Sink.ignore(), Keep.right());
+ }
+
+
+ CompletionStage calculateAverageForContent(String content) {
+ return Source.single(content)
+ .via(calculateAverage())
+ .runWith(storeAverages(), ActorMaterializer.create(actorSystem))
+ .whenComplete((d, e) -> {
+ if (d != null) {
+ System.out.println("Import finished ");
+ } else {
+ e.printStackTrace();
+ }
+ });
+ }
+
+}
diff --git a/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java b/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java
new file mode 100644
index 0000000000..c47d74eae5
--- /dev/null
+++ b/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.akkastreams;
+
+import akka.NotUsed;
+import akka.actor.ActorSystem;
+import akka.stream.ActorMaterializer;
+import akka.stream.javadsl.Flow;
+import akka.stream.javadsl.Source;
+import akka.stream.testkit.javadsl.TestSink;
+import org.junit.Test;
+
+
+public class DataImporterUnitTest {
+ private final ActorSystem actorSystem = ActorSystem.create();
+
+ @Test
+ public void givenStreamOfIntegers_whenCalculateAverageOfPairs_thenShouldReturnProperResults() {
+ //given
+ Flow tested = new DataImporter(actorSystem).calculateAverage();
+ String input = "1;9;11;0";
+
+ //when
+ Source flow = Source.single(input).via(tested);
+
+ //then
+ flow
+ .runWith(TestSink.probe(actorSystem), ActorMaterializer.create(actorSystem))
+ .request(4)
+ .expectNextUnordered(5d, 5.5);
+ }
+
+ @Test
+ public void givenStreamOfIntegers_whenCalculateAverageAndSaveToSink_thenShouldFinishSuccessfully() {
+ //given
+ DataImporter dataImporter = new DataImporter(actorSystem);
+ String input = "10;90;110;10";
+
+ //when
+ dataImporter.calculateAverageForContent(input)
+ .thenAccept(d -> actorSystem.terminate());
+
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java
similarity index 90%
rename from algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java
index 943b44fe05..0cb11f5138 100644
--- a/algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
/**
* Finite state machine.
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java
similarity index 93%
rename from algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java
index 090e00c73c..1cf06c04b5 100644
--- a/algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
/**
* Default implementation of a finite state machine.
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtState.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java
similarity index 95%
rename from algorithms/src/main/java/com/baeldung/automata/RtState.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java
index b4a5df7961..31cb9b577e 100644
--- a/algorithms/src/main/java/com/baeldung/automata/RtState.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
import java.util.ArrayList;
import java.util.List;
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtTransition.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java
similarity index 93%
rename from algorithms/src/main/java/com/baeldung/automata/RtTransition.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java
index 560011e42a..cb205deacb 100644
--- a/algorithms/src/main/java/com/baeldung/automata/RtTransition.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
/**
diff --git a/algorithms/src/main/java/com/baeldung/automata/State.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java
similarity index 93%
rename from algorithms/src/main/java/com/baeldung/automata/State.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/State.java
index a25af9d03a..1889c4c7f6 100644
--- a/algorithms/src/main/java/com/baeldung/automata/State.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
/**
* State. Part of a finite state machine.
diff --git a/algorithms/src/main/java/com/baeldung/automata/Transition.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java
similarity index 89%
rename from algorithms/src/main/java/com/baeldung/automata/Transition.java
rename to algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java
index d57620f911..68177ba7dd 100644
--- a/algorithms/src/main/java/com/baeldung/automata/Transition.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java
@@ -1,4 +1,4 @@
-package com.baeldung.automata;
+package com.baeldung.algorithms.automata;
/**
* Transition in a finite State machine.
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java
new file mode 100644
index 0000000000..77089636c8
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java
@@ -0,0 +1,189 @@
+package com.baeldung.algorithms.hillclimbing;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Stack;
+
+public class HillClimbing {
+ public static void main(String[] args) {
+ HillClimbing hillClimbing = new HillClimbing();
+ String blockArr[] = { "B", "C", "D", "A" };
+ Stack startState = hillClimbing.getStackWithValues(blockArr);
+ String goalBlockArr[] = { "A", "B", "C", "D" };
+ Stack goalState = hillClimbing.getStackWithValues(goalBlockArr);
+ try {
+ List solutionSequence = hillClimbing.getRouteWithHillClimbing(startState, goalState);
+ solutionSequence.forEach(HillClimbing::printEachStep);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void printEachStep(State state) {
+ List> stackList = state.getState();
+ System.out.println("----------------");
+ stackList.forEach(stack -> {
+ while (!stack.isEmpty()) {
+ System.out.println(stack.pop());
+ }
+ System.out.println(" ");
+ });
+ }
+
+ private Stack getStackWithValues(String[] blocks) {
+ Stack stack = new Stack<>();
+ for (String block : blocks)
+ stack.push(block);
+ return stack;
+ }
+
+ /**
+ * This method prepares path from init state to goal state
+ */
+ public List getRouteWithHillClimbing(Stack initStateStack, Stack goalStateStack) throws Exception {
+ List> initStateStackList = new ArrayList<>();
+ initStateStackList.add(initStateStack);
+ int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
+ State initState = new State(initStateStackList, initStateHeuristics);
+
+ List resultPath = new ArrayList<>();
+ resultPath.add(new State(initState));
+
+ State currentState = initState;
+ boolean noStateFound = false;
+ while (!currentState.getState()
+ .get(0)
+ .equals(goalStateStack) || noStateFound) {
+ noStateFound = true;
+ State nextState = findNextState(currentState, goalStateStack);
+ if (nextState != null) {
+ noStateFound = false;
+ currentState = nextState;
+ resultPath.add(new State(nextState));
+ }
+ }
+
+ return resultPath;
+ }
+
+ /**
+ * This method finds new state from current state based on goal and
+ * heuristics
+ */
+ public State findNextState(State currentState, Stack goalStateStack) {
+ List> listOfStacks = currentState.getState();
+ int currentStateHeuristics = currentState.getHeuristics();
+
+ return listOfStacks.stream()
+ .map(stack -> {
+ return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
+ })
+ .filter(Objects::nonNull)
+ .findFirst()
+ .orElse(null);
+ }
+
+ /**
+ * This method applies operations on the current state to get a new state
+ */
+ public State applyOperationsOnState(List> listOfStacks, Stack stack, int currentStateHeuristics, Stack goalStateStack) {
+ State tempState;
+ List> tempStackList = new ArrayList<>(listOfStacks);
+ String block = stack.pop();
+ if (stack.size() == 0)
+ tempStackList.remove(stack);
+ tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
+ if (tempState == null) {
+ tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
+ }
+ if (tempState == null)
+ stack.push(block);
+ return tempState;
+ }
+
+ /**
+ * Operation to be applied on a state in order to find new states. This
+ * operation pushes an element into a new stack
+ */
+ private State pushElementToNewStack(List> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) {
+ State newState = null;
+ Stack newStack = new Stack<>();
+ newStack.push(block);
+
+ currentStackList.add(newStack);
+ int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
+ if (newStateHeuristics > currentStateHeuristics) {
+ newState = new State(currentStackList, newStateHeuristics);
+ } else {
+ currentStackList.remove(newStack);
+ }
+ return newState;
+ }
+
+ /**
+ * Operation to be applied on a state in order to find new states. This
+ * operation pushes an element into one of the other stacks to explore new
+ * states
+ */
+ private State pushElementToExistingStacks(Stack currentStack, List> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) {
+
+ Optional newState = currentStackList.stream()
+ .filter(stack -> stack != currentStack)
+ .map(stack -> {
+ return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
+ })
+ .filter(Objects::nonNull)
+ .findFirst();
+
+ return newState.orElse(null);
+ }
+
+ /**
+ * This method pushes a block to the stack and returns new state if its closer to goal
+ */
+ private State pushElementToStack(Stack stack, String block, List> currentStackList, int currentStateHeuristics, Stack goalStateStack) {
+ stack.push(block);
+ int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
+ if (newStateHeuristics > currentStateHeuristics) {
+ return new State(currentStackList, newStateHeuristics);
+ }
+ stack.pop();
+ return null;
+ }
+
+ /**
+ * This method returns heuristics value for given state with respect to goal
+ * state
+ */
+ public int getHeuristicsValue(List> currentState, Stack goalStateStack) {
+ Integer heuristicValue;
+ heuristicValue = currentState.stream()
+ .mapToInt(stack -> {
+ return getHeuristicsValueForStack(stack, currentState, goalStateStack);
+ })
+ .sum();
+ return heuristicValue;
+ }
+
+ /**
+ * This method returns heuristics value for a particular stack
+ */
+ public int getHeuristicsValueForStack(Stack stack, List> currentState, Stack goalStateStack) {
+ int stackHeuristics = 0;
+ boolean isPositioneCorrect = true;
+ int goalStartIndex = 0;
+ for (String currentBlock : stack) {
+ if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
+ stackHeuristics += goalStartIndex;
+ } else {
+ stackHeuristics -= goalStartIndex;
+ isPositioneCorrect = false;
+ }
+ goalStartIndex++;
+ }
+ return stackHeuristics;
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java
new file mode 100644
index 0000000000..9180b33b5b
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java
@@ -0,0 +1,43 @@
+package com.baeldung.algorithms.hillclimbing;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Stack;
+
+public class State {
+ private List> state;
+ private int heuristics;
+
+ public State(List> state) {
+ this.state = state;
+ }
+
+ State(List> state, int heuristics) {
+ this.state = state;
+ this.heuristics = heuristics;
+ }
+
+ State(State state) {
+ if (state != null) {
+ this.state = new ArrayList<>();
+ for (Stack s : state.getState()) {
+ Stack s1;
+ s1 = (Stack) s.clone();
+ this.state.add(s1);
+ }
+ this.heuristics = state.getHeuristics();
+ }
+ }
+
+ public List> getState() {
+ return state;
+ }
+
+ public int getHeuristics() {
+ return heuristics;
+ }
+
+ public void setHeuristics(int heuristics) {
+ this.heuristics = heuristics;
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
new file mode 100644
index 0000000000..f428df45d3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
@@ -0,0 +1,109 @@
+package com.baeldung.algorithms.mcts.montecarlo;
+
+import java.util.List;
+
+import com.baeldung.algorithms.mcts.tictactoe.Board;
+import com.baeldung.algorithms.mcts.tree.Node;
+import com.baeldung.algorithms.mcts.tree.Tree;
+
+public class MonteCarloTreeSearch {
+
+ private static final int WIN_SCORE = 10;
+ private int level;
+ private int oponent;
+
+ public MonteCarloTreeSearch() {
+ this.level = 3;
+ }
+
+ public int getLevel() {
+ return level;
+ }
+
+ public void setLevel(int level) {
+ this.level = level;
+ }
+
+ private int getMillisForCurrentLevel() {
+ return 2 * (this.level - 1) + 1;
+ }
+
+ public Board findNextMove(Board board, int playerNo) {
+ long start = System.currentTimeMillis();
+ long end = start + 60 * getMillisForCurrentLevel();
+
+ oponent = 3 - playerNo;
+ Tree tree = new Tree();
+ Node rootNode = tree.getRoot();
+ rootNode.getState().setBoard(board);
+ rootNode.getState().setPlayerNo(oponent);
+
+ while (System.currentTimeMillis() < end) {
+ // Phase 1 - Selection
+ Node promisingNode = selectPromisingNode(rootNode);
+ // Phase 2 - Expansion
+ if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
+ expandNode(promisingNode);
+
+ // Phase 3 - Simulation
+ Node nodeToExplore = promisingNode;
+ if (promisingNode.getChildArray().size() > 0) {
+ nodeToExplore = promisingNode.getRandomChildNode();
+ }
+ int playoutResult = simulateRandomPlayout(nodeToExplore);
+ // Phase 4 - Update
+ backPropogation(nodeToExplore, playoutResult);
+ }
+
+ Node winnerNode = rootNode.getChildWithMaxScore();
+ tree.setRoot(winnerNode);
+ return winnerNode.getState().getBoard();
+ }
+
+ private Node selectPromisingNode(Node rootNode) {
+ Node node = rootNode;
+ while (node.getChildArray().size() != 0) {
+ node = UCT.findBestNodeWithUCT(node);
+ }
+ return node;
+ }
+
+ private void expandNode(Node node) {
+ List possibleStates = node.getState().getAllPossibleStates();
+ possibleStates.forEach(state -> {
+ Node newNode = new Node(state);
+ newNode.setParent(node);
+ newNode.getState().setPlayerNo(node.getState().getOpponent());
+ node.getChildArray().add(newNode);
+ });
+ }
+
+ private void backPropogation(Node nodeToExplore, int playerNo) {
+ Node tempNode = nodeToExplore;
+ while (tempNode != null) {
+ tempNode.getState().incrementVisit();
+ if (tempNode.getState().getPlayerNo() == playerNo)
+ tempNode.getState().addScore(WIN_SCORE);
+ tempNode = tempNode.getParent();
+ }
+ }
+
+ private int simulateRandomPlayout(Node node) {
+ Node tempNode = new Node(node);
+ State tempState = tempNode.getState();
+ int boardStatus = tempState.getBoard().checkStatus();
+
+ if (boardStatus == oponent) {
+ tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
+ return boardStatus;
+ }
+ while (boardStatus == Board.IN_PROGRESS) {
+ tempState.togglePlayer();
+ tempState.randomPlay();
+ boardStatus = tempState.getBoard().checkStatus();
+ }
+
+ return boardStatus;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
new file mode 100644
index 0000000000..d855f775a8
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
@@ -0,0 +1,97 @@
+package com.baeldung.algorithms.mcts.montecarlo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.algorithms.mcts.tictactoe.Board;
+import com.baeldung.algorithms.mcts.tictactoe.Position;
+
+public class State {
+ private Board board;
+ private int playerNo;
+ private int visitCount;
+ private double winScore;
+
+ public State() {
+ board = new Board();
+ }
+
+ public State(State state) {
+ this.board = new Board(state.getBoard());
+ this.playerNo = state.getPlayerNo();
+ this.visitCount = state.getVisitCount();
+ this.winScore = state.getWinScore();
+ }
+
+ public State(Board board) {
+ this.board = new Board(board);
+ }
+
+ Board getBoard() {
+ return board;
+ }
+
+ void setBoard(Board board) {
+ this.board = board;
+ }
+
+ int getPlayerNo() {
+ return playerNo;
+ }
+
+ void setPlayerNo(int playerNo) {
+ this.playerNo = playerNo;
+ }
+
+ int getOpponent() {
+ return 3 - playerNo;
+ }
+
+ public int getVisitCount() {
+ return visitCount;
+ }
+
+ public void setVisitCount(int visitCount) {
+ this.visitCount = visitCount;
+ }
+
+ double getWinScore() {
+ return winScore;
+ }
+
+ void setWinScore(double winScore) {
+ this.winScore = winScore;
+ }
+
+ public List getAllPossibleStates() {
+ List possibleStates = new ArrayList<>();
+ List availablePositions = this.board.getEmptyPositions();
+ availablePositions.forEach(p -> {
+ State newState = new State(this.board);
+ newState.setPlayerNo(3 - this.playerNo);
+ newState.getBoard().performMove(newState.getPlayerNo(), p);
+ possibleStates.add(newState);
+ });
+ return possibleStates;
+ }
+
+ void incrementVisit() {
+ this.visitCount++;
+ }
+
+ void addScore(double score) {
+ if (this.winScore != Integer.MIN_VALUE)
+ this.winScore += score;
+ }
+
+ void randomPlay() {
+ List availablePositions = this.board.getEmptyPositions();
+ int totalPossibilities = availablePositions.size();
+ int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
+ this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
+ }
+
+ void togglePlayer() {
+ this.playerNo = 3 - this.playerNo;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
new file mode 100644
index 0000000000..52707aab55
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
@@ -0,0 +1,24 @@
+package com.baeldung.algorithms.mcts.montecarlo;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import com.baeldung.algorithms.mcts.tree.Node;
+
+public class UCT {
+
+ public static double uctValue(int totalVisit, double nodeWinScore, int nodeVisit) {
+ if (nodeVisit == 0) {
+ return Integer.MAX_VALUE;
+ }
+ return (nodeWinScore / (double) nodeVisit) + 1.41 * Math.sqrt(Math.log(totalVisit) / (double) nodeVisit);
+ }
+
+ static Node findBestNodeWithUCT(Node node) {
+ int parentVisit = node.getState().getVisitCount();
+ return Collections.max(
+ node.getChildArray(),
+ Comparator.comparing(c -> uctValue(parentVisit, c.getState().getWinScore(), c.getState().getVisitCount())));
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
new file mode 100644
index 0000000000..8b47fa0fdf
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
@@ -0,0 +1,155 @@
+package com.baeldung.algorithms.mcts.tictactoe;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class Board {
+ int[][] boardValues;
+ int totalMoves;
+
+ public static final int DEFAULT_BOARD_SIZE = 3;
+
+ public static final int IN_PROGRESS = -1;
+ public static final int DRAW = 0;
+ public static final int P1 = 1;
+ public static final int P2 = 2;
+
+ public Board() {
+ boardValues = new int[DEFAULT_BOARD_SIZE][DEFAULT_BOARD_SIZE];
+ }
+
+ public Board(int boardSize) {
+ boardValues = new int[boardSize][boardSize];
+ }
+
+ public Board(int[][] boardValues) {
+ this.boardValues = boardValues;
+ }
+
+ public Board(int[][] boardValues, int totalMoves) {
+ this.boardValues = boardValues;
+ this.totalMoves = totalMoves;
+ }
+
+ public Board(Board board) {
+ int boardLength = board.getBoardValues().length;
+ this.boardValues = new int[boardLength][boardLength];
+ int[][] boardValues = board.getBoardValues();
+ int n = boardValues.length;
+ for (int i = 0; i < n; i++) {
+ int m = boardValues[i].length;
+ for (int j = 0; j < m; j++) {
+ this.boardValues[i][j] = boardValues[i][j];
+ }
+ }
+ }
+
+ public void performMove(int player, Position p) {
+ this.totalMoves++;
+ boardValues[p.getX()][p.getY()] = player;
+ }
+
+ public int[][] getBoardValues() {
+ return boardValues;
+ }
+
+ public void setBoardValues(int[][] boardValues) {
+ this.boardValues = boardValues;
+ }
+
+ public int checkStatus() {
+ int boardSize = boardValues.length;
+ int maxIndex = boardSize - 1;
+ int[] diag1 = new int[boardSize];
+ int[] diag2 = new int[boardSize];
+
+ for (int i = 0; i < boardSize; i++) {
+ int[] row = boardValues[i];
+ int[] col = new int[boardSize];
+ for (int j = 0; j < boardSize; j++) {
+ col[j] = boardValues[j][i];
+ }
+
+ int checkRowForWin = checkForWin(row);
+ if(checkRowForWin!=0)
+ return checkRowForWin;
+
+ int checkColForWin = checkForWin(col);
+ if(checkColForWin!=0)
+ return checkColForWin;
+
+ diag1[i] = boardValues[i][i];
+ diag2[i] = boardValues[maxIndex - i][i];
+ }
+
+ int checkDia1gForWin = checkForWin(diag1);
+ if(checkDia1gForWin!=0)
+ return checkDia1gForWin;
+
+ int checkDiag2ForWin = checkForWin(diag2);
+ if(checkDiag2ForWin!=0)
+ return checkDiag2ForWin;
+
+ if (getEmptyPositions().size() > 0)
+ return IN_PROGRESS;
+ else
+ return DRAW;
+ }
+
+ private int checkForWin(int[] row) {
+ boolean isEqual = true;
+ int size = row.length;
+ int previous = row[0];
+ for (int i = 0; i < size; i++) {
+ if (previous != row[i]) {
+ isEqual = false;
+ break;
+ }
+ previous = row[i];
+ }
+ if(isEqual)
+ return previous;
+ else
+ return 0;
+ }
+
+ public void printBoard() {
+ int size = this.boardValues.length;
+ for (int i = 0; i < size; i++) {
+ for (int j = 0; j < size; j++) {
+ System.out.print(boardValues[i][j] + " ");
+ }
+ System.out.println();
+ }
+ }
+
+ public List getEmptyPositions() {
+ int size = this.boardValues.length;
+ List emptyPositions = new ArrayList<>();
+ for (int i = 0; i < size; i++) {
+ for (int j = 0; j < size; j++) {
+ if (boardValues[i][j] == 0)
+ emptyPositions.add(new Position(i, j));
+ }
+ }
+ return emptyPositions;
+ }
+
+ public void printStatus() {
+ switch (this.checkStatus()) {
+ case P1:
+ System.out.println("Player 1 wins");
+ break;
+ case P2:
+ System.out.println("Player 2 wins");
+ break;
+ case DRAW:
+ System.out.println("Game Draw");
+ break;
+ case IN_PROGRESS:
+ System.out.println("Game In rogress");
+ break;
+ }
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
new file mode 100644
index 0000000000..94ead4288d
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
@@ -0,0 +1,31 @@
+package com.baeldung.algorithms.mcts.tictactoe;
+
+public class Position {
+ int x;
+ int y;
+
+ public Position() {
+ }
+
+ public Position(int x, int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public int getX() {
+ return x;
+ }
+
+ public void setX(int x) {
+ this.x = x;
+ }
+
+ public int getY() {
+ return y;
+ }
+
+ public void setY(int y) {
+ this.y = y;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
new file mode 100644
index 0000000000..20f9e992b5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
@@ -0,0 +1,78 @@
+package com.baeldung.algorithms.mcts.tree;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import com.baeldung.algorithms.mcts.montecarlo.State;
+
+public class Node {
+ State state;
+ Node parent;
+ List childArray;
+
+ public Node() {
+ this.state = new State();
+ childArray = new ArrayList<>();
+ }
+
+ public Node(State state) {
+ this.state = state;
+ childArray = new ArrayList<>();
+ }
+
+ public Node(State state, Node parent, List childArray) {
+ this.state = state;
+ this.parent = parent;
+ this.childArray = childArray;
+ }
+
+ public Node(Node node) {
+ this.childArray = new ArrayList<>();
+ this.state = new State(node.getState());
+ if (node.getParent() != null)
+ this.parent = node.getParent();
+ List childArray = node.getChildArray();
+ for (Node child : childArray) {
+ this.childArray.add(new Node(child));
+ }
+ }
+
+ public State getState() {
+ return state;
+ }
+
+ public void setState(State state) {
+ this.state = state;
+ }
+
+ public Node getParent() {
+ return parent;
+ }
+
+ public void setParent(Node parent) {
+ this.parent = parent;
+ }
+
+ public List getChildArray() {
+ return childArray;
+ }
+
+ public void setChildArray(List childArray) {
+ this.childArray = childArray;
+ }
+
+ public Node getRandomChildNode() {
+ int noOfPossibleMoves = this.childArray.size();
+ int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
+ return this.childArray.get(selectRandom);
+ }
+
+ public Node getChildWithMaxScore() {
+ return Collections.max(this.childArray, Comparator.comparing(c -> {
+ return c.getState().getVisitCount();
+ }));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
new file mode 100644
index 0000000000..c5543c0ed4
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
@@ -0,0 +1,26 @@
+package com.baeldung.algorithms.mcts.tree;
+
+public class Tree {
+ Node root;
+
+ public Tree() {
+ root = new Node();
+ }
+
+ public Tree(Node root) {
+ this.root = root;
+ }
+
+ public Node getRoot() {
+ return root;
+ }
+
+ public void setRoot(Node root) {
+ this.root = root;
+ }
+
+ public void addChild(Node parent, Node child) {
+ parent.getChildArray().add(child);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
new file mode 100644
index 0000000000..8e14afcf7a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
@@ -0,0 +1,14 @@
+package com.baeldung.algorithms.minimax;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+class GameOfBones {
+ static List getPossibleStates(int noOfBonesInHeap) {
+ return IntStream.rangeClosed(1, 3).boxed()
+ .map(i -> noOfBonesInHeap - i)
+ .filter(newHeapCount -> newHeapCount >= 0)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
new file mode 100644
index 0000000000..ce2ba03af5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
@@ -0,0 +1,60 @@
+package com.baeldung.algorithms.minimax;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class MiniMax {
+ private Tree tree;
+
+ public Tree getTree() {
+ return tree;
+ }
+
+ public void constructTree(int noOfBones) {
+ tree = new Tree();
+ Node root = new Node(noOfBones, true);
+ tree.setRoot(root);
+ constructTree(root);
+ }
+
+ private void constructTree(Node node) {
+ List listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones());
+ boolean isMaxPlayer = !node.isMaxPlayer();
+ listofPossibleHeaps.forEach(n -> {
+ Node newNode = new Node(n, isMaxPlayer);
+ node.addChild(newNode);
+ if (newNode.getNoOfBones() > 0) {
+ constructTree(newNode);
+ }
+ });
+ }
+
+ public boolean checkWin() {
+ Node root = tree.getRoot();
+ checkWin(root);
+ return root.getScore() == 1;
+ }
+
+ private void checkWin(Node node) {
+ List children = node.getChildren();
+ boolean isMaxPlayer = node.isMaxPlayer();
+ children.forEach(child -> {
+ if (child.getNoOfBones() == 0) {
+ child.setScore(isMaxPlayer ? 1 : -1);
+ } else {
+ checkWin(child);
+ }
+ });
+ Node bestChild = findBestChild(isMaxPlayer, children);
+ node.setScore(bestChild.getScore());
+ }
+
+ private Node findBestChild(boolean isMaxPlayer, List children) {
+ Comparator byScoreComparator = Comparator.comparing(Node::getScore);
+
+ return children.stream()
+ .max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed())
+ .orElseThrow(NoSuchElementException::new);
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java
new file mode 100644
index 0000000000..4ceef0073d
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java
@@ -0,0 +1,42 @@
+package com.baeldung.algorithms.minimax;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Node {
+ private int noOfBones;
+ private boolean isMaxPlayer;
+ private int score;
+ private List children;
+
+ public Node(int noOfBones, boolean isMaxPlayer) {
+ this.noOfBones = noOfBones;
+ this.isMaxPlayer = isMaxPlayer;
+ children = new ArrayList<>();
+ }
+
+ int getNoOfBones() {
+ return noOfBones;
+ }
+
+ boolean isMaxPlayer() {
+ return isMaxPlayer;
+ }
+
+ int getScore() {
+ return score;
+ }
+
+ void setScore(int score) {
+ this.score = score;
+ }
+
+ List getChildren() {
+ return children;
+ }
+
+ void addChild(Node newNode) {
+ children.add(newNode);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java
new file mode 100644
index 0000000000..34c56cdd58
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java
@@ -0,0 +1,16 @@
+package com.baeldung.algorithms.minimax;
+
+public class Tree {
+ private Node root;
+
+ Tree() {
+ }
+
+ Node getRoot() {
+ return root;
+ }
+
+ void setRoot(Node root) {
+ this.root = root;
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java
new file mode 100644
index 0000000000..666adbb180
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java
@@ -0,0 +1,58 @@
+package algorithms;
+
+import com.baeldung.algorithms.hillclimbing.HillClimbing;
+import com.baeldung.algorithms.hillclimbing.State;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Stack;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class HillClimbingAlgorithmTest {
+ private Stack initStack;
+ private Stack goalStack;
+
+ @Before
+ public void initStacks() {
+ String blockArr[] = { "B", "C", "D", "A" };
+ String goalBlockArr[] = { "A", "B", "C", "D" };
+ initStack = new Stack<>();
+ for (String block : blockArr)
+ initStack.push(block);
+ goalStack = new Stack<>();
+ for (String block : goalBlockArr)
+ goalStack.push(block);
+ }
+
+ @Test
+ public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
+ HillClimbing hillClimbing = new HillClimbing();
+
+ List path;
+ try {
+ path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
+ assertNotNull(path);
+ assertEquals(path.get(path.size() - 1)
+ .getState()
+ .get(0), goalStack);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
+ HillClimbing hillClimbing = new HillClimbing();
+ List> initList = new ArrayList<>();
+ initList.add(initStack);
+ State currentState = new State(initList);
+ currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
+ State nextState = hillClimbing.findNextState(currentState, goalStack);
+ assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/test/java/algorithms/MCTSTest.java b/algorithms/src/test/java/algorithms/MCTSTest.java
new file mode 100644
index 0000000000..f969c26311
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/MCTSTest.java
@@ -0,0 +1,92 @@
+package algorithms;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
+import com.baeldung.algorithms.mcts.montecarlo.State;
+import com.baeldung.algorithms.mcts.montecarlo.UCT;
+import com.baeldung.algorithms.mcts.tictactoe.Board;
+import com.baeldung.algorithms.mcts.tictactoe.Position;
+import com.baeldung.algorithms.mcts.tree.Tree;
+
+public class MCTSTest {
+ Tree gameTree;
+ MonteCarloTreeSearch mcts;
+
+ @Before
+ public void initGameTree() {
+ gameTree = new Tree();
+ mcts = new MonteCarloTreeSearch();
+ }
+
+ @Test
+ public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
+ double uctValue = 15.79;
+ assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
+ }
+
+ @Test
+ public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
+ State initState = gameTree.getRoot().getState();
+ List possibleStates = initState.getAllPossibleStates();
+ assertTrue(possibleStates.size() > 0);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
+ Board board = new Board();
+ int initAvailablePositions = board.getEmptyPositions().size();
+ board.performMove(Board.P1, new Position(1, 1));
+ int availablePositions = board.getEmptyPositions().size();
+ assertTrue(initAvailablePositions > availablePositions);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
+ Board board = new Board();
+
+ int player = Board.P1;
+ int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
+ for (int i = 0; i < totalMoves; i++) {
+ board = mcts.findNextMove(board, player);
+ if (board.checkStatus() != -1) {
+ break;
+ }
+ player = 3 - player;
+ }
+ int winStatus = board.checkStatus();
+ assertEquals(winStatus, Board.DRAW);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
+ Board board = new Board();
+ MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
+ mcts1.setLevel(1);
+ MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
+ mcts3.setLevel(3);
+
+ int player = Board.P1;
+ int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
+ for (int i = 0; i < totalMoves; i++) {
+ if (player == Board.P1)
+ board = mcts3.findNextMove(board, player);
+ else
+ board = mcts1.findNextMove(board, player);
+
+ if (board.checkStatus() != -1) {
+ break;
+ }
+ player = 3 - player;
+ }
+ int winStatus = board.checkStatus();
+ assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
index c6800e9a64..99e962773f 100644
--- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
+++ b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -1,6 +1,6 @@
package algorithms;
-import com.baeldung.automata.*;
+import com.baeldung.algorithms.automata.*;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java b/algorithms/src/test/java/algorithms/mcts/MCTSTest.java
new file mode 100644
index 0000000000..375f66ab6f
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/mcts/MCTSTest.java
@@ -0,0 +1,92 @@
+package algorithms.mcts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
+import com.baeldung.algorithms.mcts.montecarlo.State;
+import com.baeldung.algorithms.mcts.montecarlo.UCT;
+import com.baeldung.algorithms.mcts.tictactoe.Board;
+import com.baeldung.algorithms.mcts.tictactoe.Position;
+import com.baeldung.algorithms.mcts.tree.Tree;
+
+public class MCTSTest {
+ private Tree gameTree;
+ private MonteCarloTreeSearch mcts;
+
+ @Before
+ public void initGameTree() {
+ gameTree = new Tree();
+ mcts = new MonteCarloTreeSearch();
+ }
+
+ @Test
+ public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
+ double uctValue = 15.79;
+ assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
+ }
+
+ @Test
+ public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
+ State initState = gameTree.getRoot().getState();
+ List possibleStates = initState.getAllPossibleStates();
+ assertTrue(possibleStates.size() > 0);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
+ Board board = new Board();
+ int initAvailablePositions = board.getEmptyPositions().size();
+ board.performMove(Board.P1, new Position(1, 1));
+ int availablePositions = board.getEmptyPositions().size();
+ assertTrue(initAvailablePositions > availablePositions);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
+ Board board = new Board();
+
+ int player = Board.P1;
+ int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
+ for (int i = 0; i < totalMoves; i++) {
+ board = mcts.findNextMove(board, player);
+ if (board.checkStatus() != -1) {
+ break;
+ }
+ player = 3 - player;
+ }
+ int winStatus = board.checkStatus();
+ assertEquals(winStatus, Board.DRAW);
+ }
+
+ @Test
+ public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
+ Board board = new Board();
+ MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
+ mcts1.setLevel(1);
+ MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
+ mcts3.setLevel(3);
+
+ int player = Board.P1;
+ int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
+ for (int i = 0; i < totalMoves; i++) {
+ if (player == Board.P1)
+ board = mcts3.findNextMove(board, player);
+ else
+ board = mcts1.findNextMove(board, player);
+
+ if (board.checkStatus() != -1) {
+ break;
+ }
+ player = 3 - player;
+ }
+ int winStatus = board.checkStatus();
+ assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java b/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
new file mode 100644
index 0000000000..b29c16386c
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
@@ -0,0 +1,36 @@
+package algorithms.minimax;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+import com.baeldung.algorithms.minimax.MiniMax;
+import com.baeldung.algorithms.minimax.Tree;
+
+public class MinimaxTest {
+ private Tree gameTree;
+ private MiniMax miniMax;
+
+ @Before
+ public void initMiniMaxUtility() {
+ miniMax = new MiniMax();
+ }
+
+ @Test
+ public void givenMiniMax_whenConstructTree_thenNotNullTree() {
+ assertNull(gameTree);
+ miniMax.constructTree(6);
+ gameTree = miniMax.getTree();
+ assertNotNull(gameTree);
+ }
+
+ @Test
+ public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
+ miniMax.constructTree(6);
+ boolean result = miniMax.checkWin();
+ assertTrue(result);
+ miniMax.constructTree(8);
+ result = miniMax.checkWin();
+ assertFalse(result);
+ }
+}
diff --git a/asciidoctor/README.md b/asciidoctor/README.md
new file mode 100644
index 0000000000..164200d227
--- /dev/null
+++ b/asciidoctor/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
\ No newline at end of file
diff --git a/spring-boot-kotlin/src/main/resource/application.properties b/asciidoctor/log4j.properties
similarity index 100%
rename from spring-boot-kotlin/src/main/resource/application.properties
rename to asciidoctor/log4j.properties
diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml
new file mode 100644
index 0000000000..989f6e5354
--- /dev/null
+++ b/asciidoctor/pom.xml
@@ -0,0 +1,56 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+
+ asciidoctor
+ asciidoctor
+
+
+
+ org.asciidoctor
+ asciidoctor-maven-plugin
+ 1.5.5
+
+
+ org.asciidoctor
+ asciidoctorj-pdf
+ 1.5.0-alpha.15
+
+
+
+
+ output-pdf
+ generate-resources
+
+ process-asciidoc
+
+
+
+
+ src/docs/asciidoc
+ target/docs/asciidoc
+ pdf
+
+
+
+
+
+
+
+ org.asciidoctor
+ asciidoctorj
+ 1.5.4
+
+
+ org.asciidoctor
+ asciidoctorj-pdf
+ 1.5.0-alpha.11
+
+
+
diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/asciidoctor/src/docs/asciidoc/test.adoc
new file mode 100644
index 0000000000..5a86a00440
--- /dev/null
+++ b/asciidoctor/src/docs/asciidoc/test.adoc
@@ -0,0 +1,3 @@
+== Introduction Section
+
+Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#.
\ No newline at end of file
diff --git a/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java b/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java
new file mode 100644
index 0000000000..6ecf4ff964
--- /dev/null
+++ b/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java
@@ -0,0 +1,33 @@
+package com.baeldung.asciidoctor;
+
+import static org.asciidoctor.Asciidoctor.Factory.create;
+import static org.asciidoctor.OptionsBuilder.options;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.asciidoctor.Asciidoctor;
+
+public class AsciidoctorDemo {
+
+ private final Asciidoctor asciidoctor;
+
+ AsciidoctorDemo() {
+ asciidoctor = create();
+ }
+
+ public void generatePDFFromString(final String input) {
+
+ final Map options = options().inPlace(true)
+ .backend("pdf")
+ .asMap();
+
+
+ final String outfile = asciidoctor.convertFile(new File("sample.adoc"), options);
+ }
+
+ String generateHTMLFromString(final String input) {
+ return asciidoctor.convert("Hello _Baeldung_!", new HashMap());
+ }
+}
diff --git a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java
new file mode 100644
index 0000000000..3e312eb059
--- /dev/null
+++ b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java
@@ -0,0 +1,13 @@
+package com.baeldung.asciidoctor;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class AsciidoctorDemoTest {
+
+ @Test
+ public void givenString_whenConverting_thenResultingHTMLCode() {
+ final AsciidoctorDemo asciidoctorDemo = new AsciidoctorDemo();
+ Assert.assertEquals(asciidoctorDemo.generateHTMLFromString("Hello _Baeldung_!"), "");
+ }
+}
diff --git a/camel-api/README.md b/camel-api/README.md
new file mode 100644
index 0000000000..fe8dadcfe1
--- /dev/null
+++ b/camel-api/README.md
@@ -0,0 +1,15 @@
+Example for the Article on Camel API with SpringBoot
+
+to start up, run:
+ mvn spring-boot:run
+
+them, do a POST http request to:
+ http://localhost:8080/camel/api/bean
+
+with the HEADER: Content-Type: application/json,
+
+and a BODY Payload like {"id": 1,"name": "World"}
+
+and we will get a return code of 201 and the response: Hello, World - if the transform() method from Application class is uncommented and the process() method is commented
+
+or return code of 201 and the response: {"id": 10,"name": "Hello, World"} - if the transform() method from Application class is commented and the process() method is uncommented
diff --git a/camel-api/pom.xml b/camel-api/pom.xml
new file mode 100644
index 0000000000..6db9f9bfd1
--- /dev/null
+++ b/camel-api/pom.xml
@@ -0,0 +1,80 @@
+
+
+
+ 4.0.0
+
+ com.example
+ spring-boot-camel
+ 0.0.1-SNAPSHOT
+
+ Spring-Boot - Camel API
+
+
+ UTF-8
+ 3.6.0
+ 2.19.1
+ 2.19.1
+ 1.5.4.RELEASE
+
+
+
+
+ org.apache.camel
+ camel-servlet-starter
+ ${camel.version}
+
+
+ org.apache.camel
+ camel-jackson-starter
+ ${camel.version}
+
+
+ org.apache.camel
+ camel-swagger-java-starter
+ ${camel.version}
+
+
+ org.apache.camel
+ camel-spring-boot-starter
+ ${camel.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+ ${spring-boot-starter.version}
+
+
+
+
+ spring-boot:run
+
+
+
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ ${spring-boot-starter.version}
+
+
+
+ repackage
+
+
+
+
+
+
+
diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/camel-api/src/main/java/com/baeldung/camel/Application.java
new file mode 100644
index 0000000000..f805385ff9
--- /dev/null
+++ b/camel-api/src/main/java/com/baeldung/camel/Application.java
@@ -0,0 +1,104 @@
+package com.baeldung.camel;
+
+import javax.ws.rs.core.MediaType;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.servlet.CamelHttpTransportServlet;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.model.rest.RestBindingMode;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.ServletRegistrationBean;
+import org.springframework.boot.web.support.SpringBootServletInitializer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.stereotype.Component;
+
+@SpringBootApplication
+@ComponentScan(basePackages="com.baeldung.camel")
+public class Application extends SpringBootServletInitializer {
+
+ @Value("${server.port}")
+ String serverPort;
+
+ @Value("${baeldung.api.path}")
+ String contextPath;
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+ @Bean
+ ServletRegistrationBean servletRegistrationBean() {
+ ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*");
+ servlet.setName("CamelServlet");
+ return servlet;
+ }
+
+
+ @Component
+ class RestApi extends RouteBuilder {
+
+ @Override
+ public void configure() {
+
+ CamelContext context = new DefaultCamelContext();
+
+
+ // http://localhost:8080/camel/api-doc
+ restConfiguration().contextPath(contextPath) //
+ .port(serverPort)
+ .enableCORS(true)
+ .apiContextPath("/api-doc")
+ .apiProperty("api.title", "Test REST API")
+ .apiProperty("api.version", "v1")
+ .apiProperty("cors", "true") // cross-site
+ .apiContextRouteId("doc-api")
+ .component("servlet")
+ .bindingMode(RestBindingMode.json)
+ .dataFormatProperty("prettyPrint", "true");
+/**
+The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
+By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
+You may want to use binding if you develop POJOs that maps to your REST services request and response types.
+This allows you, as a developer, to work with the POJOs in Java code.
+*/
+
+ rest("/api/").description("Teste REST Service")
+ .id("api-route")
+ .post("/bean")
+ .produces(MediaType.APPLICATION_JSON)
+ .consumes(MediaType.APPLICATION_JSON)
+// .get("/hello/{place}")
+ .bindingMode(RestBindingMode.auto)
+ .type(MyBean.class)
+ .enableCORS(true)
+// .outType(OutBean.class)
+
+ .to("direct:remoteService");
+
+
+ from("direct:remoteService")
+ .routeId("direct-route")
+ .tracing()
+ .log(">>> ${body.id}")
+ .log(">>> ${body.name}")
+// .transform().simple("blue ${in.body.name}")
+ .process(new Processor() {
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ MyBean bodyIn = (MyBean) exchange.getIn().getBody();
+
+ ExampleServices.example(bodyIn);
+
+ exchange.getIn().setBody(bodyIn);
+ }
+ })
+ .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201));
+ }
+ }
+}
diff --git a/camel-api/src/main/java/com/baeldung/camel/ExampleServices.java b/camel-api/src/main/java/com/baeldung/camel/ExampleServices.java
new file mode 100644
index 0000000000..ec8f368e68
--- /dev/null
+++ b/camel-api/src/main/java/com/baeldung/camel/ExampleServices.java
@@ -0,0 +1,15 @@
+package com.baeldung.camel;
+
+/**
+ * a Mock class to show how some other layer
+ * (a persistence layer, for instance)
+ * could be used insida a Camel
+ *
+ */
+public class ExampleServices {
+
+ public static void example(MyBean bodyIn) {
+ bodyIn.setName( "Hello, " + bodyIn.getName() );
+ bodyIn.setId(bodyIn.getId()*10);
+ }
+}
diff --git a/camel-api/src/main/java/com/baeldung/camel/MyBean.java b/camel-api/src/main/java/com/baeldung/camel/MyBean.java
new file mode 100644
index 0000000000..5368e40c93
--- /dev/null
+++ b/camel-api/src/main/java/com/baeldung/camel/MyBean.java
@@ -0,0 +1,18 @@
+package com.baeldung.camel;
+
+public class MyBean {
+ private Integer id;
+ private String name;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/camel-api/src/main/resources/application.properties b/camel-api/src/main/resources/application.properties
new file mode 100644
index 0000000000..bce95f8eaf
--- /dev/null
+++ b/camel-api/src/main/resources/application.properties
@@ -0,0 +1,15 @@
+logging.config=classpath:logback.xml
+
+# the options from org.apache.camel.spring.boot.CamelConfigurationProperties can be configured here
+camel.springboot.name=MyCamel
+
+# lets listen on all ports to ensure we can be invoked from the pod IP
+server.address=0.0.0.0
+management.address=0.0.0.0
+
+# lets use a different management port in case you need to listen to HTTP requests on 8080
+management.port=8081
+
+# disable all management enpoints except health
+endpoints.enabled = true
+endpoints.health.enabled = true
\ No newline at end of file
diff --git a/camel-api/src/main/resources/application.yml b/camel-api/src/main/resources/application.yml
new file mode 100644
index 0000000000..3a4b913db7
--- /dev/null
+++ b/camel-api/src/main/resources/application.yml
@@ -0,0 +1,27 @@
+server:
+ port: 8080
+
+# for example purposes of Camel version 2.18 and below
+baeldung:
+ api:
+ path: '/camel'
+
+camel:
+ springboot:
+ # The Camel context name
+ name: ServicesRest
+
+# Binding health checks to a different port
+management:
+ port: 8081
+
+# disable all management enpoints except health
+endpoints:
+ enabled: false
+ health:
+ enabled: true
+
+# The application configuration properties
+quickstart:
+ generateOrderPeriod: 10s
+ processOrderPeriod: 30s
diff --git a/camel-api/src/main/resources/logback.xml b/camel-api/src/main/resources/logback.xml
new file mode 100644
index 0000000000..d0b4334f5a
--- /dev/null
+++ b/camel-api/src/main/resources/logback.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
index 23473ff161..f6792fdbd9 100644
--- a/core-java-9/pom.xml
+++ b/core-java-9/pom.xml
@@ -47,6 +47,13 @@
${mockito.version}
test
+
+ com.jayway.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
+
@@ -90,6 +97,7 @@
1.3
4.12
1.10.19
+ 1.7.0
diff --git a/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java b/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java
new file mode 100644
index 0000000000..bbbb4f3411
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java
@@ -0,0 +1,43 @@
+package com.baeldung.java9.streams.reactive;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.Flow.Subscriber;
+import java.util.concurrent.Flow.Subscription;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class EndSubscriber implements Subscriber {
+ private final AtomicInteger howMuchMessagesToConsume;
+ private Subscription subscription;
+ public List consumedElements = new LinkedList<>();
+
+ public EndSubscriber(Integer howMuchMessagesToConsume) {
+ this.howMuchMessagesToConsume = new AtomicInteger(howMuchMessagesToConsume);
+ }
+
+ @Override
+ public void onSubscribe(Subscription subscription) {
+ this.subscription = subscription;
+ subscription.request(1);
+ }
+
+ @Override
+ public void onNext(T item) {
+ howMuchMessagesToConsume.decrementAndGet();
+ System.out.println("Got : " + item);
+ consumedElements.add(item);
+ if (howMuchMessagesToConsume.get() > 0) {
+ subscription.request(1);
+ }
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void onComplete() {
+ System.out.println("Done");
+ }
+}
\ No newline at end of file
diff --git a/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java b/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java
new file mode 100644
index 0000000000..325979470f
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java
@@ -0,0 +1,38 @@
+package com.baeldung.java9.streams.reactive;
+
+import java.util.concurrent.Flow;
+import java.util.concurrent.SubmissionPublisher;
+import java.util.function.Function;
+
+public class TransformProcessor extends SubmissionPublisher implements Flow.Processor {
+
+ private Function function;
+ private Flow.Subscription subscription;
+
+ public TransformProcessor(Function function) {
+ super();
+ this.function = function;
+ }
+
+ @Override
+ public void onSubscribe(Flow.Subscription subscription) {
+ this.subscription = subscription;
+ subscription.request(1);
+ }
+
+ @Override
+ public void onNext(T item) {
+ submit(function.apply(item));
+ subscription.request(1);
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void onComplete() {
+ close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java
new file mode 100644
index 0000000000..ee4e35a77b
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java
@@ -0,0 +1,43 @@
+package com.baeldung.java9.time;
+
+import java.time.LocalDate;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public class TimeApi {
+
+ public static List getDatesBetweenUsingJava7(Date startDate, Date endDate) {
+ List datesInRange = new ArrayList();
+ Calendar calendar = new GregorianCalendar();
+ calendar.setTime(startDate);
+
+ Calendar endCalendar = new GregorianCalendar();
+ endCalendar.setTime(endDate);
+
+ while (calendar.before(endCalendar)) {
+ Date result = calendar.getTime();
+ datesInRange.add(result);
+ calendar.add(Calendar.DATE, 1);
+ }
+ return datesInRange;
+ }
+
+ public static List getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
+ long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
+ return IntStream.iterate(0, i -> i + 1)
+ .limit(numOfDaysBetween)
+ .mapToObj(i -> startDate.plusDays(i))
+ .collect(Collectors.toList());
+ }
+
+ public static List getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
+ return startDate.datesUntil(endDate).collect(Collectors.toList());
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java b/core-java-9/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java
new file mode 100644
index 0000000000..647557532d
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.java9.streams.reactive;
+
+
+import org.junit.Test;
+
+import java.util.List;
+import java.util.concurrent.SubmissionPublisher;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+
+public class ReactiveStreamsTest {
+
+ @Test
+ public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
+ //given
+ SubmissionPublisher publisher = new SubmissionPublisher<>();
+ EndSubscriber subscriber = new EndSubscriber<>(6);
+ publisher.subscribe(subscriber);
+ List items = List.of("1", "x", "2", "x", "3", "x");
+
+ //when
+ assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
+ items.forEach(publisher::submit);
+ publisher.close();
+
+ //then
+
+ await().atMost(1000, TimeUnit.MILLISECONDS).until(
+ () -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
+ );
+ }
+
+ @Test
+ public void givenPublisher_whenSubscribeAndTransformElements_thenShouldConsumeAllElements() throws InterruptedException {
+ //given
+ SubmissionPublisher publisher = new SubmissionPublisher<>();
+ TransformProcessor transformProcessor = new TransformProcessor<>(Integer::parseInt);
+ EndSubscriber subscriber = new EndSubscriber<>(3);
+ List items = List.of("1", "2", "3");
+ List expectedResult = List.of(1, 2, 3);
+
+ //when
+ publisher.subscribe(transformProcessor);
+ transformProcessor.subscribe(subscriber);
+ items.forEach(publisher::submit);
+ publisher.close();
+
+ //then
+ await().atMost(1000, TimeUnit.MILLISECONDS).until(
+ () -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
+ );
+ }
+
+ @Test
+ public void givenPublisher_whenRequestForOnlyOneElement_thenShouldConsumeOnlyThatOne() throws InterruptedException {
+ //given
+ SubmissionPublisher publisher = new SubmissionPublisher<>();
+ EndSubscriber subscriber = new EndSubscriber<>(1);
+ publisher.subscribe(subscriber);
+ List items = List.of("1", "x", "2", "x", "3", "x");
+ List expected = List.of("1");
+
+ //when
+ assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
+ items.forEach(publisher::submit);
+ publisher.close();
+
+ //then
+ await().atMost(1000, TimeUnit.MILLISECONDS).until(
+ () -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
+ );
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java b/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java
new file mode 100644
index 0000000000..a024db19a8
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.java9.time;
+
+import java.time.LocalDate;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+public class TimeApiTest {
+
+ @Test
+ public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() {
+ Date startDate = Calendar.getInstance().getTime();
+ Calendar endCalendar = Calendar.getInstance();
+ endCalendar.add(Calendar.DATE, 2);
+ Date endDate = endCalendar.getTime();
+
+ List dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
+ assertEquals(dates.size(), 2);
+
+ Calendar calendar = Calendar.getInstance();
+ Date date1 = calendar.getTime();
+ assertEquals(dates.get(0).getDay(), date1.getDay());
+ assertEquals(dates.get(0).getMonth(), date1.getMonth());
+ assertEquals(dates.get(0).getYear(), date1.getYear());
+
+ calendar.add(Calendar.DATE, 1);
+ Date date2 = calendar.getTime();
+ assertEquals(dates.get(1).getDay(), date2.getDay());
+ assertEquals(dates.get(1).getMonth(), date2.getMonth());
+ assertEquals(dates.get(1).getYear(), date2.getYear());
+ }
+
+ @Test
+ public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() {
+ LocalDate startDate = LocalDate.now();
+ LocalDate endDate = LocalDate.now().plusDays(2);
+
+ List dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate);
+ assertEquals(dates.size(), 2);
+ assertEquals(dates.get(0), LocalDate.now());
+ assertEquals(dates.get(1), LocalDate.now().plusDays(1));
+ }
+
+ @Test
+ public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() {
+ LocalDate startDate = LocalDate.now();
+ LocalDate endDate = LocalDate.now().plusDays(2);
+
+ List dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
+ assertEquals(dates.size(), 2);
+ assertEquals(dates.get(0), LocalDate.now());
+ assertEquals(dates.get(1), LocalDate.now().plusDays(1));
+ }
+
+}
diff --git a/core-java/.gitignore b/core-java/.gitignore
index 2a03a0f72e..3de4cc647e 100644
--- a/core-java/.gitignore
+++ b/core-java/.gitignore
@@ -17,9 +17,10 @@
# Files generated by integration tests
*.txt
+backup-pom.xml
/bin/
/temp
#IntelliJ specific
-.idea
+.idea/
*.iml
\ No newline at end of file
diff --git a/core-java/README.md b/core-java/README.md
index 6c671a632d..559507e472 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -102,7 +102,7 @@
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
-- [Guide to UUID in JAVA] (http://www.baeldung.com/guide-to-uuid-in-java)
+- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
@@ -113,4 +113,21 @@
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
-
+- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
+- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
+- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
+- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
+- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
+- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
+- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
+- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
+- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
+- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
+- [Split a String in Java](http://www.baeldung.com/java-split-string)
+- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
+- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
+- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
+- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
+- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
+- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
+- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 5c9bf06a57..84a56c8bc7 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,399 +1,420 @@
- 4.0.0
- com.baeldung
- core-java
- 0.1.0-SNAPSHOT
- jar
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ core-java
+ 0.1.0-SNAPSHOT
+ jar
- core-java
+ core-java
-
+
-
-
- net.sourceforge.collections
- collections-generic
- ${collections-generic.version}
-
-
- com.google.guava
- guava
- ${guava.version}
-
+
+
+ net.sourceforge.collections
+ collections-generic
+ ${collections-generic.version}
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
-
- commons-io
- commons-io
- ${commons-io.version}
-
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
-
- org.decimal4j
- decimal4j
- ${decimal4j.version}
-
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
-
- org.bouncycastle
- bcprov-jdk15on
- ${bouncycastle.version}
-
+
+ org.decimal4j
+ decimal4j
+ ${decimal4j.version}
+
-
- org.unix4j
- unix4j-command
- ${unix4j.version}
-
+
+ org.bouncycastle
+ bcprov-jdk15on
+ ${bouncycastle.version}
+
-
- com.googlecode.grep4j
- grep4j
- ${grep4j.version}
-
-
+
+ org.unix4j
+ unix4j-command
+ ${unix4j.version}
+
-
+
+ com.googlecode.grep4j
+ grep4j
+ ${grep4j.version}
+
+
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
+
-
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
+
-
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
-
- org.hamcrest
- hamcrest-all
- 1.3
- test
-
+
-
- junit
- junit
- ${junit.version}
- test
-
+
+ org.hamcrest
+ hamcrest-all
+ 1.3
+ test
+
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
+
+ junit
+ junit
+ ${junit.version}
+ test
+
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
- com.jayway.awaitility
- awaitility
- ${avaitility.version}
- test
-
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
-
- commons-codec
- commons-codec
- ${commons-codec.version}
-
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
-
- org.javamoney
- moneta
- 1.1
-
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
-
- org.owasp.esapi
- esapi
- 2.1.0.1
-
+
+ org.javamoney
+ moneta
+ 1.1
+
-
+
+ org.owasp.esapi
+ esapi
+ 2.1.0.1
+
-
- core-java
-
-
- src/main/resources
- true
-
-
+
+ com.sun.messaging.mq
+ fscontext
+ ${fscontext.version}
+
+
-
+
+ core-java
+
+
+ src/main/resources
+ true
+
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- **/*IntegrationTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
-
- true
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*IntegrationTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+
+ true
+
+
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ true
+ libs/
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+ ${project.basedir}
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+ jar-with-dependencies
+
+
+
+
+
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+
+
+
+ shade
+
+
+ true
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
+
+ com.jolira
+ onejar-maven-plugin
+
+
+
+ org.baeldung.executable.ExecutableMavenJar
+ true
+ ${project.build.finalName}-onejar.${project.packaging}
+
+
+ one-jar
+
+
+
+
-
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ spring-boot
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
-
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+ java
+ com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
+
+ -Xmx300m
+ -XX:+UseParallelGC
+ -classpath
+
+ com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
+
+
+
+
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
-
-
-
-
-
-
- json
-
-
-
-
-
-
-
+
-
-
- 2.8.5
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
-
- 1.7.21
- 1.1.7
+
+
+ 2.8.5
-
- 21.0
- 3.5
- 1.55
- 1.10
- 3.6.1
- 1.0.3
- 2.5
- 4.1
- 4.01
- 0.4
- 1.8.7
- 1.16.12
+
+ 1.7.21
+ 1.1.7
-
- 1.3
- 4.12
- 1.10.19
- 3.6.1
- 1.7.0
+
+ 21.0
+ 3.5
+ 1.55
+ 1.10
+ 3.6.1
+ 1.0.3
+ 2.5
+ 4.1
+ 4.01
+ 0.4
+ 1.8.7
+ 1.16.12
+ 4.6-b01
-
- 3.6.0
- 2.19.1
+
+ 1.3
+ 4.12
+ 1.10.19
+ 3.6.1
+ 1.7.0
-
+
+ 3.6.0
+ 2.19.1
+
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
index 13fe0c3126..7b261b2b8e 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
@@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
private final BlockingQueue queue;
private final int poisonPill;
- public NumbersConsumer(BlockingQueue queue, int poisonPill) {
+ NumbersConsumer(BlockingQueue queue, int poisonPill) {
this.queue = queue;
this.poisonPill = poisonPill;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
index b262097c63..9dcd0a3e47 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
@@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
private final int poisonPill;
private final int poisonPillPerProducer;
- public NumbersProducer(BlockingQueue numbersQueue, int poisonPill, int poisonPillPerProducer) {
+ NumbersProducer(BlockingQueue numbersQueue, int poisonPill, int poisonPillPerProducer) {
this.numbersQueue = numbersQueue;
this.poisonPill = poisonPill;
this.poisonPillPerProducer = poisonPillPerProducer;
diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java
index 90cd01b69f..d48f317fe7 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java
@@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
private final List outputScraper;
private final CountDownLatch countDownLatch;
- public BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) {
+ BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) {
this.outputScraper = outputScraper;
this.countDownLatch = countDownLatch;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java
index 66be2030e2..4aee5cf89a 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java
@@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
private final CountDownLatch callingThreadBlocker;
private final CountDownLatch completedThreadCounter;
- public WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
+ WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
this.outputScraper = outputScraper;
this.readyThreadCounter = readyThreadCounter;
diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
index e712fc18d6..389e25719b 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
@@ -7,7 +7,7 @@ public class Worker implements Runnable {
private final List outputScraper;
private final CountDownLatch countDownLatch;
- public Worker(final List outputScraper, final CountDownLatch countDownLatch) {
+ Worker(final List outputScraper, final CountDownLatch countDownLatch) {
this.outputScraper = outputScraper;
this.countDownLatch = countDownLatch;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java
new file mode 100644
index 0000000000..977dae4fdb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java
@@ -0,0 +1,81 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CyclicBarrier;
+
+public class CyclicBarrierDemo {
+
+ private CyclicBarrier cyclicBarrier;
+ private List> partialResults = Collections.synchronizedList(new ArrayList<>());
+ private Random random = new Random();
+ private int NUM_PARTIAL_RESULTS;
+ private int NUM_WORKERS;
+
+
+ private void runSimulation(int numWorkers, int numberOfPartialResults) {
+ NUM_PARTIAL_RESULTS = numberOfPartialResults;
+ NUM_WORKERS = numWorkers;
+
+ cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
+ System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
+ + NUM_PARTIAL_RESULTS + " partial results each");
+ for (int i = 0; i < NUM_WORKERS; i++) {
+ Thread worker = new Thread(new NumberCruncherThread());
+ worker.setName("Thread " + i);
+ worker.start();
+ }
+ }
+
+ class NumberCruncherThread implements Runnable {
+
+ @Override
+ public void run() {
+ String thisThreadName = Thread.currentThread().getName();
+ List partialResult = new ArrayList<>();
+ for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
+ Integer num = random.nextInt(10);
+ System.out.println(thisThreadName
+ + ": Crunching some numbers! Final result - " + num);
+ partialResult.add(num);
+ }
+ partialResults.add(partialResult);
+ try {
+ System.out.println(thisThreadName + " waiting for others to reach barrier.");
+ cyclicBarrier.await();
+ } catch (InterruptedException | BrokenBarrierException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ class AggregatorThread implements Runnable {
+
+ @Override
+ public void run() {
+ String thisThreadName = Thread.currentThread().getName();
+ System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
+ + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
+ int sum = 0;
+ for (List threadResult : partialResults) {
+ System.out.print("Adding ");
+ for (Integer partialResult : threadResult) {
+ System.out.print(partialResult+" ");
+ sum += partialResult;
+ }
+ System.out.println();
+ }
+ System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
+ }
+
+ }
+
+ public static void main(String[] args) {
+ CyclicBarrierDemo play = new CyclicBarrierDemo();
+ play.runSimulation(5, 3);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
index aa4ca58d6a..5f72758e71 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
@@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
private String data;
private long startTime;
- public DelayObject(String data, long delayInMilliseconds) {
+ DelayObject(String data, long delayInMilliseconds) {
this.data = data;
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
index 8a969bf7aa..d1c1eae9f2 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
@@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
public class DelayQueueConsumer implements Runnable {
private BlockingQueue queue;
private final Integer numberOfElementsToTake;
- public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
+ final AtomicInteger numberOfConsumedElements = new AtomicInteger();
- public DelayQueueConsumer(BlockingQueue queue, Integer numberOfElementsToTake) {
+ DelayQueueConsumer(BlockingQueue queue, Integer numberOfElementsToTake) {
this.queue = queue;
this.numberOfElementsToTake = numberOfElementsToTake;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
index 617f19b9ac..f24f4bc385 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
@@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
private final Integer numberOfElementsToProduce;
private final Integer delayOfEachProducedMessageMilliseconds;
- public DelayQueueProducer(BlockingQueue queue,
- Integer numberOfElementsToProduce,
- Integer delayOfEachProducedMessageMilliseconds) {
+ DelayQueueProducer(BlockingQueue queue,
+ Integer numberOfElementsToProduce,
+ Integer delayOfEachProducedMessageMilliseconds) {
this.queue = queue;
this.numberOfElementsToProduce = numberOfElementsToProduce;
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java
index 3f1eacd276..c5672706ad 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java
@@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
private final Object leftFork;
private final Object rightFork;
- public Philosopher(Object left, Object right) {
+ Philosopher(Object left, Object right) {
this.leftFork = left;
this.rightFork = right;
}
@@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- return;
}
}
}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java
index 471072b333..35bb2aa497 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java
@@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask {
final private Integer n;
- public FactorialSquareCalculator(Integer n) {
+ FactorialSquareCalculator(Integer n) {
this.n = n;
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java
index bcd559dd3b..3329fa599b 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java
@@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
-public class SquareCalculator {
+class SquareCalculator {
private final ExecutorService executor;
- public SquareCalculator(ExecutorService executor) {
+ SquareCalculator(ExecutorService executor) {
this.executor = executor;
}
- public Future calculate(Integer input) {
+ Future calculate(Integer input) {
return executor.submit(() -> {
Thread.sleep(1000);
return input * input;
diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java b/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java
index 4f061d2efd..f01c675fd2 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java
@@ -13,71 +13,71 @@ import static java.lang.Thread.sleep;
public class ReentrantLockWithCondition {
- static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
+ private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
- Stack stack = new Stack<>();
- int CAPACITY = 5;
+ private Stack stack = new Stack<>();
+ private static final int CAPACITY = 5;
- ReentrantLock lock = new ReentrantLock();
- Condition stackEmptyCondition = lock.newCondition();
- Condition stackFullCondition = lock.newCondition();
+ private ReentrantLock lock = new ReentrantLock();
+ private Condition stackEmptyCondition = lock.newCondition();
+ private Condition stackFullCondition = lock.newCondition();
- public void pushToStack(String item) throws InterruptedException {
- try {
- lock.lock();
- if (stack.size() == CAPACITY) {
- logger.info(Thread.currentThread().getName() + " wait on stack full");
- stackFullCondition.await();
- }
- logger.info("Pushing the item " + item);
- stack.push(item);
- stackEmptyCondition.signalAll();
- } finally {
- lock.unlock();
- }
+ private void pushToStack(String item) throws InterruptedException {
+ try {
+ lock.lock();
+ if (stack.size() == CAPACITY) {
+ LOG.info(Thread.currentThread().getName() + " wait on stack full");
+ stackFullCondition.await();
+ }
+ LOG.info("Pushing the item " + item);
+ stack.push(item);
+ stackEmptyCondition.signalAll();
+ } finally {
+ lock.unlock();
+ }
- }
+ }
- public String popFromStack() throws InterruptedException {
- try {
- lock.lock();
- if (stack.size() == 0) {
- logger.info(Thread.currentThread().getName() + " wait on stack empty");
- stackEmptyCondition.await();
- }
- return stack.pop();
- } finally {
- stackFullCondition.signalAll();
- lock.unlock();
- }
- }
+ private String popFromStack() throws InterruptedException {
+ try {
+ lock.lock();
+ if (stack.size() == 0) {
+ LOG.info(Thread.currentThread().getName() + " wait on stack empty");
+ stackEmptyCondition.await();
+ }
+ return stack.pop();
+ } finally {
+ stackFullCondition.signalAll();
+ lock.unlock();
+ }
+ }
- public static void main(String[] args) {
- final int threadCount = 2;
- ReentrantLockWithCondition object = new ReentrantLockWithCondition();
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- service.execute(() -> {
- for (int i = 0; i < 10; i++) {
- try {
- object.pushToStack("Item " + i);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+ public static void main(String[] args) {
+ final int threadCount = 2;
+ ReentrantLockWithCondition object = new ReentrantLockWithCondition();
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ service.execute(() -> {
+ for (int i = 0; i < 10; i++) {
+ try {
+ object.pushToStack("Item " + i);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
- });
+ });
- service.execute(() -> {
- for (int i = 0; i < 10; i++) {
- try {
- logger.info("Item popped " + object.popFromStack());
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+ service.execute(() -> {
+ for (int i = 0; i < 10; i++) {
+ try {
+ LOG.info("Item popped " + object.popFromStack());
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
- });
+ });
- service.shutdown();
- }
+ service.shutdown();
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java
index b6a4615638..14ae47b2f3 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java
@@ -12,81 +12,77 @@ import static java.lang.Thread.sleep;
public class SharedObjectWithLock {
- Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
- ReentrantLock lock = new ReentrantLock(true);
+ private ReentrantLock lock = new ReentrantLock(true);
- int counter = 0;
+ private int counter = 0;
- public void perform() {
+ void perform() {
- lock.lock();
- logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
- try {
- logger.info("Thread - " + Thread.currentThread().getName() + " processing");
- counter++;
- } catch (Exception exception) {
- logger.error(" Interrupted Exception ", exception);
- } finally {
- lock.unlock();
- logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
- }
- }
+ lock.lock();
+ LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
+ try {
+ LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
+ counter++;
+ } catch (Exception exception) {
+ LOG.error(" Interrupted Exception ", exception);
+ } finally {
+ lock.unlock();
+ LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
+ }
+ }
- public void performTryLock() {
+ private void performTryLock() {
- logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
- try {
- boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
- if (isLockAcquired) {
- try {
- logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
+ LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
+ try {
+ boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
+ if (isLockAcquired) {
+ try {
+ LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
- logger.info("Thread - " + Thread.currentThread().getName() + " processing");
- sleep(1000);
- } finally {
- lock.unlock();
- logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
+ LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
+ sleep(1000);
+ } finally {
+ lock.unlock();
+ LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
- }
- }
- } catch (InterruptedException exception) {
- logger.error(" Interrupted Exception ", exception);
- }
- logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
- }
+ }
+ }
+ } catch (InterruptedException exception) {
+ LOG.error(" Interrupted Exception ", exception);
+ }
+ LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
+ }
- public ReentrantLock getLock() {
- return lock;
- }
+ public ReentrantLock getLock() {
+ return lock;
+ }
- boolean isLocked() {
- return lock.isLocked();
- }
+ boolean isLocked() {
+ return lock.isLocked();
+ }
- boolean hasQueuedThreads() {
- return lock.hasQueuedThreads();
- }
+ boolean hasQueuedThreads() {
+ return lock.hasQueuedThreads();
+ }
- int getCounter() {
- return counter;
- }
+ int getCounter() {
+ return counter;
+ }
- public static void main(String[] args) {
+ public static void main(String[] args) {
- final int threadCount = 2;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- final SharedObjectWithLock object = new SharedObjectWithLock();
+ final int threadCount = 2;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ final SharedObjectWithLock object = new SharedObjectWithLock();
- service.execute(() -> {
- object.perform();
- });
- service.execute(() -> {
- object.performTryLock();
- });
+ service.execute(object::perform);
+ service.execute(object::performTryLock);
- service.shutdown();
+ service.shutdown();
- }
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java b/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java
index 0b0dbc72cb..638bb56b2f 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java
@@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
import static java.lang.Thread.sleep;
public class StampedLockDemo {
- Map map = new HashMap<>();
- Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
+ private Map map = new HashMap<>();
+ private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
- private final StampedLock lock = new StampedLock();
+ private final StampedLock lock = new StampedLock();
- public void put(String key, String value) throws InterruptedException {
- long stamp = lock.writeLock();
+ public void put(String key, String value) throws InterruptedException {
+ long stamp = lock.writeLock();
- try {
- logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
- map.put(key, value);
- } finally {
- lock.unlockWrite(stamp);
- logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
- }
- }
+ try {
+ logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
+ map.put(key, value);
+ } finally {
+ lock.unlockWrite(stamp);
+ logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
+ }
+ }
- public String get(String key) throws InterruptedException {
- long stamp = lock.readLock();
- logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
- try {
- sleep(5000);
- return map.get(key);
+ public String get(String key) throws InterruptedException {
+ long stamp = lock.readLock();
+ logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
+ try {
+ sleep(5000);
+ return map.get(key);
- } finally {
- lock.unlockRead(stamp);
- logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
+ } finally {
+ lock.unlockRead(stamp);
+ logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
- }
+ }
- }
+ }
- public String readWithOptimisticLock(String key) throws InterruptedException {
- long stamp = lock.tryOptimisticRead();
- String value = map.get(key);
+ private String readWithOptimisticLock(String key) throws InterruptedException {
+ long stamp = lock.tryOptimisticRead();
+ String value = map.get(key);
- if (!lock.validate(stamp)) {
- stamp = lock.readLock();
- try {
- sleep(5000);
- return map.get(key);
+ if (!lock.validate(stamp)) {
+ stamp = lock.readLock();
+ try {
+ sleep(5000);
+ return map.get(key);
- } finally {
- lock.unlock(stamp);
- logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
+ } finally {
+ lock.unlock(stamp);
+ logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
- }
- }
- return value;
- }
+ }
+ }
+ return value;
+ }
- public static void main(String[] args) {
- final int threadCount = 4;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- StampedLockDemo object = new StampedLockDemo();
+ public static void main(String[] args) {
+ final int threadCount = 4;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ StampedLockDemo object = new StampedLockDemo();
- Runnable writeTask = () -> {
+ Runnable writeTask = () -> {
- try {
- object.put("key1", "value1");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- };
- Runnable readTask = () -> {
+ try {
+ object.put("key1", "value1");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+ Runnable readTask = () -> {
- try {
- object.get("key1");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- };
- Runnable readOptimisticTask = () -> {
+ try {
+ object.get("key1");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+ Runnable readOptimisticTask = () -> {
- try {
- object.readWithOptimisticLock("key1");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- };
- service.submit(writeTask);
- service.submit(writeTask);
- service.submit(readTask);
- service.submit(readOptimisticTask);
+ try {
+ object.readWithOptimisticLock("key1");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+ service.submit(writeTask);
+ service.submit(writeTask);
+ service.submit(readTask);
+ service.submit(readOptimisticTask);
- service.shutdown();
+ service.shutdown();
- }
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java b/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java
index 83b8b34fe9..eeb7aa4b13 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java
@@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
public class SynchronizedHashMapWithRWLock {
- static Map syncHashMap = new HashMap<>();
- Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
+ private static Map syncHashMap = new HashMap<>();
+ private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
- private final ReadWriteLock lock = new ReentrantReadWriteLock();
- private final Lock readLock = lock.readLock();
- private final Lock writeLock = lock.writeLock();
+ private final ReadWriteLock lock = new ReentrantReadWriteLock();
+ private final Lock readLock = lock.readLock();
+ private final Lock writeLock = lock.writeLock();
- public void put(String key, String value) throws InterruptedException {
+ public void put(String key, String value) throws InterruptedException {
- try {
- writeLock.lock();
- logger.info(Thread.currentThread().getName() + " writing");
- syncHashMap.put(key, value);
- sleep(1000);
- } finally {
- writeLock.unlock();
- }
+ try {
+ writeLock.lock();
+ logger.info(Thread.currentThread().getName() + " writing");
+ syncHashMap.put(key, value);
+ sleep(1000);
+ } finally {
+ writeLock.unlock();
+ }
- }
+ }
- public String get(String key) {
- try {
- readLock.lock();
- logger.info(Thread.currentThread().getName() + " reading");
- return syncHashMap.get(key);
- } finally {
- readLock.unlock();
- }
- }
+ public String get(String key) {
+ try {
+ readLock.lock();
+ logger.info(Thread.currentThread().getName() + " reading");
+ return syncHashMap.get(key);
+ } finally {
+ readLock.unlock();
+ }
+ }
- public String remove(String key) {
- try {
- writeLock.lock();
- return syncHashMap.remove(key);
- } finally {
- writeLock.unlock();
- }
- }
+ public String remove(String key) {
+ try {
+ writeLock.lock();
+ return syncHashMap.remove(key);
+ } finally {
+ writeLock.unlock();
+ }
+ }
- public boolean containsKey(String key) {
- try {
- readLock.lock();
- return syncHashMap.containsKey(key);
- } finally {
- readLock.unlock();
- }
- }
+ public boolean containsKey(String key) {
+ try {
+ readLock.lock();
+ return syncHashMap.containsKey(key);
+ } finally {
+ readLock.unlock();
+ }
+ }
- boolean isReadLockAvailable() {
- return readLock.tryLock();
- }
+ boolean isReadLockAvailable() {
+ return readLock.tryLock();
+ }
- public static void main(String[] args) throws InterruptedException {
+ public static void main(String[] args) throws InterruptedException {
- final int threadCount = 3;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
+ final int threadCount = 3;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
- service.execute(new Thread(new Writer(object), "Writer"));
- service.execute(new Thread(new Reader(object), "Reader1"));
- service.execute(new Thread(new Reader(object), "Reader2"));
+ service.execute(new Thread(new Writer(object), "Writer"));
+ service.execute(new Thread(new Reader(object), "Reader1"));
+ service.execute(new Thread(new Reader(object), "Reader2"));
- service.shutdown();
- }
+ service.shutdown();
+ }
- private static class Reader implements Runnable {
+ private static class Reader implements Runnable {
- SynchronizedHashMapWithRWLock object;
+ SynchronizedHashMapWithRWLock object;
- public Reader(SynchronizedHashMapWithRWLock object) {
- this.object = object;
- }
+ Reader(SynchronizedHashMapWithRWLock object) {
+ this.object = object;
+ }
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- object.get("key" + i);
- }
- }
- }
+ @Override
+ public void run() {
+ for (int i = 0; i < 10; i++) {
+ object.get("key" + i);
+ }
+ }
+ }
- private static class Writer implements Runnable {
+ private static class Writer implements Runnable {
- SynchronizedHashMapWithRWLock object;
+ SynchronizedHashMapWithRWLock object;
- public Writer(SynchronizedHashMapWithRWLock object) {
- this.object = object;
- }
+ public Writer(SynchronizedHashMapWithRWLock object) {
+ this.object = object;
+ }
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- try {
- object.put("key" + i, "value" + i);
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
+ @Override
+ public void run() {
+ for (int i = 0; i < 10; i++) {
+ try {
+ object.put("key" + i, "value" + i);
+ sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java b/core-java/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java
new file mode 100644
index 0000000000..50cd2966ea
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java
@@ -0,0 +1,31 @@
+package com.baeldung.concurrent.semaphores;
+
+import java.util.concurrent.Semaphore;
+
+class CounterUsingMutex {
+
+ private final Semaphore mutex;
+ private int count;
+
+ CounterUsingMutex() {
+ mutex = new Semaphore(1);
+ count = 0;
+ }
+
+ void increase() throws InterruptedException {
+ mutex.acquire();
+ this.count = this.count + 1;
+ Thread.sleep(1000);
+ mutex.release();
+
+ }
+
+ int getCount() {
+ return this.count;
+ }
+
+ boolean hasQueuedThreads() {
+ return mutex.hasQueuedThreads();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java b/core-java/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java
new file mode 100644
index 0000000000..718574d3c8
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java
@@ -0,0 +1,23 @@
+package com.baeldung.concurrent.semaphores;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.lang3.concurrent.TimedSemaphore;
+
+class DelayQueueUsingTimedSemaphore {
+
+ private final TimedSemaphore semaphore;
+
+ DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
+ semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
+ }
+
+ boolean tryAdd() {
+ return semaphore.tryAcquire();
+ }
+
+ int availableSlots() {
+ return semaphore.getAvailablePermits();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java b/core-java/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java
new file mode 100644
index 0000000000..3cf7c45428
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java
@@ -0,0 +1,25 @@
+package com.baeldung.concurrent.semaphores;
+
+import java.util.concurrent.Semaphore;
+
+class LoginQueueUsingSemaphore {
+
+ private final Semaphore semaphore;
+
+ LoginQueueUsingSemaphore(int slotLimit) {
+ semaphore = new Semaphore(slotLimit);
+ }
+
+ boolean tryLogin() {
+ return semaphore.tryAcquire();
+ }
+
+ void logout() {
+ semaphore.release();
+ }
+
+ int availableSlots() {
+ return semaphore.availablePermits();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java
index ce1f57bb93..d5ff5f7842 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java
@@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
-public class Event {
+class Event {
private final ZonedDateTime eventTime;
private final String content;
- public Event(ZonedDateTime eventTime, String content) {
+ Event(ZonedDateTime eventTime, String content) {
this.eventTime = eventTime;
this.content = content;
}
- public ZonedDateTime getEventTime() {
+ ZonedDateTime getEventTime() {
return eventTime;
}
- public String getContent() {
+ String getContent() {
return content;
}
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
index 3aca6b0147..2e501ed368 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
@@ -5,24 +5,24 @@ import java.util.Comparator;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
-public class EventWindowSort {
+class EventWindowSort {
private final ConcurrentSkipListMap events
- = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
+ = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
- public void acceptEvent(Event event) {
+ void acceptEvent(Event event) {
events.put(event.getEventTime(), event.getContent());
}
- public ConcurrentNavigableMap getEventsFromLastMinute() {
+ ConcurrentNavigableMap getEventsFromLastMinute() {
return events.tailMap(ZonedDateTime
- .now()
- .minusMinutes(1));
+ .now()
+ .minusMinutes(1));
}
- public ConcurrentNavigableMap getEventsOlderThatOneMinute() {
+ ConcurrentNavigableMap getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
- .now()
- .minusMinutes(1));
+ .now()
+ .minusMinutes(1));
}
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java
index 0311d9b0b2..90bc4dceed 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java
@@ -13,10 +13,10 @@ public class WaitSleepExample {
private static final Object LOCK = new Object();
public static void main(String... args) throws InterruptedException {
- sleepWaitInSyncronizedBlocks();
+ sleepWaitInSynchronizedBlocks();
}
- private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
+ private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
Thread.sleep(1000); // called on the thread
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
@@ -25,5 +25,5 @@ public class WaitSleepExample {
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
}
}
-
+
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java
index d66cd0d796..332a6d9263 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java
@@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
private int count = 0;
private static int staticCount = 0;
- public void performSynchronisedTask() {
+ void performSynchronisedTask() {
synchronized (this) {
setCount(getCount() + 1);
}
}
- public static void performStaticSyncTask() {
+ static void performStaticSyncTask() {
synchronized (BaeldungSynchronizedBlocks.class) {
setStaticCount(getStaticCount() + 1);
}
@@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
this.count = count;
}
- public static int getStaticCount() {
+ static int getStaticCount() {
return staticCount;
}
- public static void setStaticCount(int staticCount) {
+ private static void setStaticCount(int staticCount) {
BaeldungSynchronizedBlocks.staticCount = staticCount;
}
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java
index 1295140b7c..179c6fb9ef 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java
@@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
private int sum = 0;
private int syncSum = 0;
- public static int staticSum = 0;
+ static int staticSum = 0;
- public void calculate() {
+ void calculate() {
setSum(getSum() + 1);
}
- public synchronized void synchronisedCalculate() {
+ synchronized void synchronisedCalculate() {
setSyncSum(getSyncSum() + 1);
}
- public static synchronized void syncStaticCalculate() {
+ static synchronized void syncStaticCalculate() {
staticSum = staticSum + 1;
}
@@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
this.sum = sum;
}
- public int getSyncSum() {
+ int getSyncSum() {
return syncSum;
}
- public void setSyncSum(int syncSum) {
+ private void setSyncSum(int syncSum) {
this.syncSum = syncSum;
}
}
diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java
index 82f5745b3c..0d727cf0b5 100644
--- a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java
@@ -6,40 +6,40 @@ import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
-public class UseLocalDate {
+class UseLocalDate {
- public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
+ LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
return LocalDate.of(year, month, dayOfMonth);
}
- public LocalDate getLocalDateUsingParseMethod(String representation) {
+ LocalDate getLocalDateUsingParseMethod(String representation) {
return LocalDate.parse(representation);
}
- public LocalDate getLocalDateFromClock() {
+ LocalDate getLocalDateFromClock() {
LocalDate localDate = LocalDate.now();
return localDate;
}
- public LocalDate getNextDay(LocalDate localDate) {
+ LocalDate getNextDay(LocalDate localDate) {
return localDate.plusDays(1);
}
- public LocalDate getPreviousDay(LocalDate localDate) {
+ LocalDate getPreviousDay(LocalDate localDate) {
return localDate.minus(1, ChronoUnit.DAYS);
}
- public DayOfWeek getDayOfWeek(LocalDate localDate) {
+ DayOfWeek getDayOfWeek(LocalDate localDate) {
DayOfWeek day = localDate.getDayOfWeek();
return day;
}
- public LocalDate getFirstDayOfMonth() {
+ LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
- public LocalDateTime getStartOfDay(LocalDate localDate) {
+ LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;
}
diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java
index 9bd8f9706c..8d166c413f 100644
--- a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java
@@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
public class UseLocalTime {
- public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
- LocalTime localTime = LocalTime.of(hour, min, seconds);
- return localTime;
+ LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
+ return LocalTime.of(hour, min, seconds);
}
- public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
- LocalTime localTime = LocalTime.parse(timeRepresentation);
- return localTime;
+ LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
+ return LocalTime.parse(timeRepresentation);
}
- public LocalTime getLocalTimeFromClock() {
- LocalTime localTime = LocalTime.now();
- return localTime;
+ private LocalTime getLocalTimeFromClock() {
+ return LocalTime.now();
}
- public LocalTime addAnHour(LocalTime localTime) {
- LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
- return newTime;
+ LocalTime addAnHour(LocalTime localTime) {
+ return localTime.plus(1, ChronoUnit.HOURS);
}
- public int getHourFromLocalTime(LocalTime localTime) {
+ int getHourFromLocalTime(LocalTime localTime) {
return localTime.getHour();
}
- public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
+ LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
return localTime.withMinute(minute);
}
}
diff --git a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
index 5a42ef83b4..10bc6caec3 100644
--- a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
@@ -3,13 +3,13 @@ package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.Period;
-public class UsePeriod {
+class UsePeriod {
- public LocalDate modifyDates(LocalDate localDate, Period period) {
+ LocalDate modifyDates(LocalDate localDate, Period period) {
return localDate.plus(period);
}
- public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
+ Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
return Period.between(localDate1, localDate2);
}
}
diff --git a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java
index 94154ce5c0..1fa413bbf2 100644
--- a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java
@@ -8,12 +8,10 @@ import java.util.Date;
public class UseToInstant {
public LocalDateTime convertDateToLocalDate(Date date) {
- LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
- return localDateTime;
+ return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
- LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
- return localDateTime;
+ return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
}
}
diff --git a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
index 2d1b17484b..f5e1af0a06 100644
--- a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
@@ -4,10 +4,9 @@ import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
-public class UseZonedDateTime {
+class UseZonedDateTime {
- public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
- ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
- return zonedDateTime;
+ ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
+ return ZonedDateTime.of(localDateTime, zoneId);
}
}
diff --git a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java
new file mode 100644
index 0000000000..d672b9a4f5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java
@@ -0,0 +1,26 @@
+package com.baeldung.deserialization;
+
+import java.io.Serializable;
+
+public class AppleProduct implements Serializable {
+
+ private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
+// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
+
+ public String headphonePort;
+ public String thunderboltPort;
+ public String lighteningPort;
+
+ public String getHeadphonePort() {
+ return headphonePort;
+ }
+
+ public String getThunderboltPort() {
+ return thunderboltPort;
+ }
+
+ public static long getSerialVersionUID() {
+ return serialVersionUID;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java
new file mode 100644
index 0000000000..3ed2b8be1d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java
@@ -0,0 +1,27 @@
+package com.baeldung.deserialization;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.Base64;
+
+public class DeserializationUtility {
+
+ public static void main(String[] args) throws ClassNotFoundException, IOException {
+
+ String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
+ System.out.println("Deserializing AppleProduct...");
+ AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
+ System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
+ System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
+ }
+
+ public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
+ byte[] data = Base64.getDecoder().decode(s);
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
+ Object o = ois.readObject();
+ ois.close();
+ return o;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java
new file mode 100644
index 0000000000..1dbcc40e6b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java
@@ -0,0 +1,30 @@
+package com.baeldung.deserialization;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Base64;
+
+public class SerializationUtility {
+
+ public static void main(String[] args) throws ClassNotFoundException, IOException {
+
+ AppleProduct macBook = new AppleProduct();
+ macBook.headphonePort = "headphonePort2020";
+ macBook.thunderboltPort = "thunderboltPort2020";
+
+ String serializedObj = serializeObjectToString(macBook);
+ System.out.println("Serialized AppleProduct object to string:");
+ System.out.println(serializedObj);
+ }
+
+ public static String serializeObjectToString(Serializable o) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(o);
+ oos.close();
+ return Base64.getEncoder().encodeToString(baos.toByteArray());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java
index f9028bd159..bdc732947f 100644
--- a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java
+++ b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java
@@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
-
- public static final int POLL_INTERVAL = 500;
+ private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
diff --git a/core-java/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java
index b5d2e70abd..dc0b064013 100644
--- a/core-java/src/main/java/com/baeldung/doublecolon/Computer.java
+++ b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java
@@ -6,12 +6,12 @@ public class Computer {
private String color;
private Integer healty;
- public Computer(final int age, final String color) {
+ Computer(final int age, final String color) {
this.age = age;
this.color = color;
}
- public Computer(final Integer age, final String color, final Integer healty) {
+ Computer(final Integer age, final String color, final Integer healty) {
this.age = age;
this.color = color;
this.healty = healty;
@@ -28,7 +28,7 @@ public class Computer {
this.age = age;
}
- public String getColor() {
+ String getColor() {
return color;
}
@@ -36,11 +36,11 @@ public class Computer {
this.color = color;
}
- public Integer getHealty() {
+ Integer getHealty() {
return healty;
}
- public void setHealty(final Integer healty) {
+ void setHealty(final Integer healty) {
this.healty = healty;
}
@@ -72,10 +72,7 @@ public class Computer {
final Computer computer = (Computer) o;
- if (age != null ? !age.equals(computer.age) : computer.age != null) {
- return false;
- }
- return color != null ? color.equals(computer.color) : computer.color == null;
+ return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
}
diff --git a/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
index d181dfcdf7..317808d893 100644
--- a/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
+++ b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
@@ -7,8 +7,8 @@ import java.util.List;
public class ComputerUtils {
- public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
- public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
+ static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
+ static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
public static List filter(final List inventory, final ComputerPredicate p) {
@@ -18,7 +18,7 @@ public class ComputerUtils {
return result;
}
- public static void repair(final Computer computer) {
+ static void repair(final Computer computer) {
if (computer.getHealty() < 50) {
computer.setHealty(100);
}
diff --git a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java
index f5c31e9653..79c8d9e383 100644
--- a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java
+++ b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java
@@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
super(age, color);
}
- public MacbookPro(Integer age, String color, Integer healty) {
+ MacbookPro(Integer age, String color, Integer healty) {
super(age, color, healty);
}
diff --git a/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java
index 942efc50cc..c35b69d075 100644
--- a/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java
+++ b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java
@@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
private Object target;
- public TimingDynamicInvocationHandler(Object target) {
+ TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java
index b9125c3e2f..66de220057 100644
--- a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java
@@ -1,10 +1,10 @@
package com.baeldung.equalshashcode.entities;
-import java.awt.Color;
+import java.awt.*;
public class Square extends Rectangle {
- Color color;
+ private Color color;
public Square(double width, Color color) {
super(width, width);
diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
new file mode 100644
index 0000000000..4afce56e39
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
@@ -0,0 +1,43 @@
+package com.baeldung.filesystem.jndi;
+
+import java.io.File;
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+public class LookupFSJNDI {
+ private InitialContext ctx = null;
+
+ public LookupFSJNDI() throws NamingException {
+ super();
+ init();
+ }
+
+ private void init() throws NamingException {
+ Hashtable env = new Hashtable();
+
+ env.put (Context.INITIAL_CONTEXT_FACTORY,
+ "com.sun.jndi.fscontext.RefFSContextFactory");
+ // URI to namespace (actual directory)
+ env.put(Context.PROVIDER_URL, "file:./src/test/resources");
+
+ ctx = new InitialContext(env);
+ }
+
+ public InitialContext getCtx() {
+ return ctx;
+ }
+
+ public File getFile(String fileName) {
+ File file;
+ try {
+ file = (File)getCtx().lookup(fileName);
+ } catch (NamingException e) {
+ file = null;
+ }
+ return file;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java b/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java
new file mode 100644
index 0000000000..3776ef82e2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java
@@ -0,0 +1,23 @@
+package com.baeldung.java.reflection;
+
+import java.lang.annotation.Annotation;
+
+public class DynamicGreeter implements Greeter {
+
+ private String greet;
+
+ public DynamicGreeter(String greet) {
+ this.greet = greet;
+ }
+
+ @Override
+ public Class extends Annotation> annotationType() {
+ return DynamicGreeter.class;
+ }
+
+ @Override
+ public String greet() {
+ return greet;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java
new file mode 100644
index 0000000000..ede269528a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java
@@ -0,0 +1,10 @@
+package com.baeldung.java.reflection;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Greeter {
+
+ public String greet() default "";
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java b/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java
new file mode 100644
index 0000000000..601306f5d2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java
@@ -0,0 +1,58 @@
+package com.baeldung.java.reflection;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class GreetingAnnotation {
+
+ private static final String ANNOTATION_METHOD = "annotationData";
+ private static final String ANNOTATION_FIELDS = "declaredAnnotations";
+ private static final String ANNOTATIONS = "annotations";
+
+ public static void main(String ...args) {
+ Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
+ System.err.println("Hello there, " + greetings.greet() + " !!");
+
+ Greeter targetValue = new DynamicGreeter("Good evening");
+ //alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
+ alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
+
+ greetings = Greetings.class.getAnnotation(Greeter.class);
+ System.err.println("Hello there, " + greetings.greet() + " !!");
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void alterAnnotationValueJDK8(Class> targetClass, Class extends Annotation> targetAnnotation, Annotation targetValue) {
+ try {
+ Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
+ method.setAccessible(true);
+
+ Object annotationData = method.invoke(targetClass);
+
+ Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
+ annotations.setAccessible(true);
+
+ Map, Annotation> map = (Map, Annotation>) annotations.get(annotationData);
+ map.put(targetAnnotation, targetValue);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void alterAnnotationValueJDK7(Class> targetClass, Class extends Annotation> targetAnnotation, Annotation targetValue) {
+ try {
+ Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
+ annotations.setAccessible(true);
+
+ Map, Annotation> map = (Map, Annotation>) annotations.get(targetClass);
+ System.out.println(map);
+ map.put(targetAnnotation, targetValue);
+ System.out.println(map);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java b/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java
new file mode 100644
index 0000000000..4f3a20c3b9
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java
@@ -0,0 +1,6 @@
+package com.baeldung.java.reflection;
+
+@Greeter(greet="Good morning")
+public class Greetings {
+
+}
diff --git a/core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java b/core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java
new file mode 100644
index 0000000000..f8038a7e86
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java
@@ -0,0 +1,69 @@
+package com.baeldung.javanetworking.url;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class URLDemo {
+ private final Logger log = LoggerFactory.getLogger(URLDemo.class);
+
+ String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
+ // parsed locator
+ String URLPROTOCOL = "https";
+ // final static String URLAUTHORITY = "wordpress.org:443";
+ String URLHOST = "wordpress.org";
+ String URLPATH = "/support/topic/page-jumps-within-wordpress/";
+ // final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
+ // final static int URLPORT = 443;
+ int URLDEFAULTPORT = 443;
+ String URLQUERY = "replies=3";
+ String URLREFERENCE = "post-2278484";
+ String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
+
+ URL url;
+ URLConnection urlConnection = null;
+ HttpURLConnection connection = null;
+ BufferedReader in = null;
+ String urlContent = "";
+
+ public String testURL(String urlString) throws IOException, IllegalArgumentException {
+ String urlStringCont = "";
+ // comment the if clause if experiment with URL
+ /*if (!URLSTRING.equals(urlString)) {
+ throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
+ }*/
+ // creating URL object
+ url = new URL(urlString);
+ // get URL connection
+ urlConnection = url.openConnection();
+ connection = null;
+ // we can check, if connection is proper type
+ if (urlConnection instanceof HttpURLConnection) {
+ connection = (HttpURLConnection) urlConnection;
+ } else {
+ log.info("Please enter an HTTP URL");
+ throw new IOException("HTTP URL is not correct");
+ }
+ // we can check response code (200 OK is expected)
+ log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
+ in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+ String current;
+
+ while ((current = in.readLine()) != null) {
+ urlStringCont += current;
+ }
+ return urlStringCont;
+ }
+
+ public static void main(String[] args) throws Exception {
+ URLDemo demo = new URLDemo();
+ String content = demo.testURL(demo.URLCOMPOUND);
+ demo.log.info(content);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java
new file mode 100644
index 0000000000..2bc078cdb0
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java
@@ -0,0 +1,71 @@
+package com.baeldung.map.iteration;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+public class MapIteration {
+
+ public static void main(String[] args) {
+ MapIteration mapIteration = new MapIteration();
+ Map map = new HashMap<>();
+
+ map.put("One", 1);
+ map.put("Three", 3);
+ map.put("Two", 2);
+
+ System.out.println("Iterating Keys of Map Using KeySet");
+ mapIteration.iterateKeys(map);
+
+ System.out.println("Iterating Map Using Entry Set");
+ mapIteration.iterateUsingEntrySet(map);
+
+ System.out.println("Iterating Using Iterator and Map Entry");
+ mapIteration.iterateUsingIteratorAndEntry(map);
+
+ System.out.println("Iterating Using KeySet and For Each");
+ mapIteration.iterateUsingKeySetAndForeach(map);
+
+ System.out.println("Iterating Map Using Lambda Expression");
+ mapIteration.iterateUsingLambda(map);
+
+ System.out.println("Iterating Using Stream API");
+ mapIteration.iterateUsingStreamAPI(map);
+ }
+
+ public void iterateUsingEntrySet(Map map) {
+ for (Map.Entry entry : map.entrySet()) {
+ System.out.println(entry.getKey() + ":" + entry.getValue());
+ }
+ }
+
+ public void iterateUsingLambda(Map map) {
+ map.forEach((k, v) -> System.out.println((k + ":" + v)));
+ }
+
+ public void iterateUsingIteratorAndEntry(Map map) {
+ Iterator> iterator = map.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry pair = iterator.next();
+ System.out.println(pair.getKey() + ":" + pair.getValue());
+ }
+ }
+
+ public void iterateUsingKeySetAndForeach(Map map) {
+ for (String key : map.keySet()) {
+ System.out.println(key + ":" + map.get(key));
+ }
+ }
+
+ public void iterateUsingStreamAPI(Map map) {
+ map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
+ }
+
+ public void iterateKeys(Map map) {
+ for (String key : map.keySet()) {
+ System.out.println(key);
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java b/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java
new file mode 100644
index 0000000000..1472dd7d6d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java
@@ -0,0 +1,18 @@
+package com.baeldung.maths;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public class BigDecimalImpl {
+
+ public static void main(String[] args) {
+
+ BigDecimal serviceTax = new BigDecimal("56.0084578639");
+ serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
+
+ BigDecimal entertainmentTax = new BigDecimal("23.00689");
+ entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
+
+ BigDecimal totalTax = serviceTax.add(entertainmentTax);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java
new file mode 100644
index 0000000000..dc509429f9
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java
@@ -0,0 +1,16 @@
+package com.baeldung.maths;
+
+import java.math.BigInteger;
+
+public class BigIntegerImpl {
+
+ public static void main(String[] args) {
+
+ BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
+ BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
+
+ BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorExample.java b/core-java/src/main/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorExample.java
index 2c852b5e82..0d02391a73 100644
--- a/core-java/src/main/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorExample.java
+++ b/core-java/src/main/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorExample.java
@@ -11,4 +11,4 @@ public class NoClassDefFoundErrorExample {
test = new ClassWithInitErrors();
return test;
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java b/core-java/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java
new file mode 100644
index 0000000000..a1b4140281
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java
@@ -0,0 +1,19 @@
+package com.baeldung.outofmemoryerror;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+
+public class OutOfMemoryGCLimitExceed {
+ public static void addRandomDataToMap() {
+ Map dataMap = new HashMap<>();
+ Random r = new Random();
+ while (true) {
+ dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
+ }
+ }
+
+ public static void main(String[] args) {
+ OutOfMemoryGCLimitExceed.addRandomDataToMap();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java b/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java
new file mode 100644
index 0000000000..45c13f735d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java
@@ -0,0 +1,39 @@
+package com.baeldung.reflection;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+class BaeldungReflectionUtils {
+
+ private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
+
+ static List getNullPropertiesList(Customer customer) throws Exception {
+ PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
+
+ return Arrays.stream(propDescArr)
+ .filter(nulls(customer))
+ .map(PropertyDescriptor::getName)
+ .collect(Collectors.toList());
+ }
+
+ private static Predicate nulls(Customer customer) {
+ return pd -> {
+ boolean result = false;
+ try {
+ Method getterMethod = pd.getReadMethod();
+ result = (getterMethod != null && getterMethod.invoke(customer) == null);
+ } catch (Exception e) {
+ LOG.error("error invoking getter method");
+ }
+ return result;
+ };
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/reflection/Customer.java b/core-java/src/main/java/com/baeldung/reflection/Customer.java
new file mode 100644
index 0000000000..a0239f7239
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/reflection/Customer.java
@@ -0,0 +1,56 @@
+package com.baeldung.reflection;
+
+public class Customer {
+
+ private Integer id;
+ private String name;
+ private String emailId;
+ private Long phoneNumber;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getEmailId() {
+ return emailId;
+ }
+
+ public void setEmailId(String emailId) {
+ this.emailId = emailId;
+ }
+
+ @Override
+ public String toString() {
+ return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
+ phoneNumber + "]";
+ }
+
+ Customer(Integer id, String name, String emailId, Long phoneNumber) {
+ super();
+ this.id = id;
+ this.name = name;
+ this.emailId = emailId;
+ this.phoneNumber = phoneNumber;
+ }
+
+ public Long getPhoneNumber() {
+ return phoneNumber;
+ }
+
+ public void setPhoneNumber(Long phoneNumber) {
+ this.phoneNumber = phoneNumber;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/serialization/Address.java b/core-java/src/main/java/com/baeldung/serialization/Address.java
index 524ecb1ffc..055b53e70e 100644
--- a/core-java/src/main/java/com/baeldung/serialization/Address.java
+++ b/core-java/src/main/java/com/baeldung/serialization/Address.java
@@ -1,4 +1,4 @@
-package com.baeuldung.serialization;
+package com.baeldung.serialization;
public class Address {
diff --git a/core-java/src/main/java/com/baeldung/serialization/Employee.java b/core-java/src/main/java/com/baeldung/serialization/Employee.java
index 69beeb0b49..0fa3ad2fc8 100644
--- a/core-java/src/main/java/com/baeldung/serialization/Employee.java
+++ b/core-java/src/main/java/com/baeldung/serialization/Employee.java
@@ -1,4 +1,4 @@
-package com.baeuldung.serialization;
+package com.baeldung.serialization;
import java.io.IOException;
import java.io.ObjectInputStream;
diff --git a/core-java/src/main/java/com/baeldung/serialization/Person.java b/core-java/src/main/java/com/baeldung/serialization/Person.java
index 23d0601e03..4fd1a943c1 100644
--- a/core-java/src/main/java/com/baeldung/serialization/Person.java
+++ b/core-java/src/main/java/com/baeldung/serialization/Person.java
@@ -1,4 +1,4 @@
-package com.baeuldung.serialization;
+package com.baeldung.serialization;
import java.io.Serializable;
public class Person implements Serializable {
diff --git a/core-java/src/main/java/com/baeldung/stream/StreamApi.java b/core-java/src/main/java/com/baeldung/stream/StreamApi.java
index ec792314d2..364fdeffbb 100644
--- a/core-java/src/main/java/com/baeldung/stream/StreamApi.java
+++ b/core-java/src/main/java/com/baeldung/stream/StreamApi.java
@@ -5,17 +5,17 @@ import java.util.stream.Stream;
public class StreamApi {
- public String getLastElementUsingReduce(List valueList) {
+ public static String getLastElementUsingReduce(List valueList) {
Stream stream = valueList.stream();
return stream.reduce((first, second) -> second).orElse(null);
}
- public Integer getInfiniteStreamLastElementUsingReduce() {
+ public static Integer getInfiniteStreamLastElementUsingReduce() {
Stream stream = Stream.iterate(0, i -> i + 1);
return stream.limit(20).reduce((first, second) -> second).orElse(null);
}
- public String getLastElementUsingSkip(List valueList) {
+ public static String getLastElementUsingSkip(List valueList) {
long count = valueList.stream().count();
Stream stream = valueList.stream();
return stream.skip(count - 1).findFirst().orElse(null);
diff --git a/core-java/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java b/core-java/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java
new file mode 100644
index 0000000000..79c18916c2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java
@@ -0,0 +1,16 @@
+package com.baeldung.typeerasure;
+
+public class ArrayContentPrintUtil {
+
+ public static void printArray(E[] array) {
+ for (E element : array) {
+ System.out.printf("%s ", element);
+ }
+ }
+
+ public static > void printArray(E[] array) {
+ for (E element : array) {
+ System.out.printf("%s ", element);
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/typeerasure/BoundStack.java b/core-java/src/main/java/com/baeldung/typeerasure/BoundStack.java
new file mode 100644
index 0000000000..6d158fda77
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/typeerasure/BoundStack.java
@@ -0,0 +1,37 @@
+package com.baeldung.typeerasure;
+
+import java.util.Arrays;
+
+public class BoundStack> {
+
+ private E[] stackContent;
+ private int total;
+
+ public BoundStack(int capacity) {
+ this.stackContent = (E[]) new Object[capacity];
+ }
+
+ public void push(E data) {
+ if (total == stackContent.length) {
+ resize(2 * stackContent.length);
+ }
+ stackContent[total++] = data;
+ }
+
+ public E pop() {
+ if (!isEmpty()) {
+ E datum = stackContent[total];
+ stackContent[total--] = null;
+ return datum;
+ }
+ return null;
+ }
+
+ private void resize(int capacity) {
+ Arrays.copyOf(stackContent, capacity);
+ }
+
+ public boolean isEmpty() {
+ return total == 0;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/typeerasure/IntegerStack.java b/core-java/src/main/java/com/baeldung/typeerasure/IntegerStack.java
new file mode 100644
index 0000000000..ad1da1239d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/typeerasure/IntegerStack.java
@@ -0,0 +1,13 @@
+package com.baeldung.typeerasure;
+
+public class IntegerStack extends Stack {
+
+ public IntegerStack(int capacity) {
+ super(capacity);
+ }
+
+ public void push(Integer value) {
+ System.out.println("Pushing into my integerStack");
+ super.push(value);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/typeerasure/Stack.java b/core-java/src/main/java/com/baeldung/typeerasure/Stack.java
new file mode 100644
index 0000000000..b88ef6ad8b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/typeerasure/Stack.java
@@ -0,0 +1,39 @@
+package com.baeldung.typeerasure;
+
+import java.util.Arrays;
+
+public class Stack {
+
+ private E[] stackContent;
+ private int total;
+
+ public Stack(int capacity) {
+ this.stackContent = (E[]) new Object[capacity];
+ }
+
+ public void push(E data) {
+ System.out.println("In base stack push#");
+ if (total == stackContent.length) {
+ resize(2 * stackContent.length);
+ }
+ stackContent[total++] = data;
+ }
+
+ public E pop() {
+ if (!isEmpty()) {
+ E datum = stackContent[total];
+ stackContent[total--] = null;
+ return datum;
+ }
+ return null;
+ }
+
+ private void resize(int capacity) {
+ Arrays.copyOf(stackContent, capacity);
+ }
+
+ public boolean isEmpty() {
+ return total == 0;
+ }
+
+}
diff --git a/core-java/src/main/java/log4j.properties b/core-java/src/main/java/log4j.properties
new file mode 100644
index 0000000000..5fe42d854c
--- /dev/null
+++ b/core-java/src/main/java/log4j.properties
@@ -0,0 +1,9 @@
+# Set root logger level to DEBUG and its only appender to A1.
+log4j.rootLogger=DEBUG, A1
+
+# A1 is set to be a ConsoleAppender.
+log4j.appender.A1=org.apache.log4j.ConsoleAppender
+
+# A1 uses PatternLayout.
+log4j.appender.A1.layout=org.apache.log4j.PatternLayout
+log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
diff --git a/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java
index 6b6f5dbe2a..d9e580acbb 100644
--- a/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java
@@ -9,6 +9,8 @@ import org.junit.Test;
import java.util.Arrays;
+import static org.junit.Assert.assertTrue;
+
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@@ -46,10 +48,10 @@ public class ArrayCopyUtilUnitTest {
System.arraycopy(array, 2, copiedArray, 0, 3);
- Assert.assertTrue(3 == copiedArray.length);
- Assert.assertTrue(copiedArray[0] == array[2]);
- Assert.assertTrue(copiedArray[1] == array[3]);
- Assert.assertTrue(copiedArray[2] == array[4]);
+ assertTrue(3 == copiedArray.length);
+ assertTrue(copiedArray[0] == array[2]);
+ assertTrue(copiedArray[1] == array[3]);
+ assertTrue(copiedArray[2] == array[4]);
}
@Test
@@ -58,10 +60,10 @@ public class ArrayCopyUtilUnitTest {
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
- Assert.assertTrue(3 == copiedArray.length);
- Assert.assertTrue(copiedArray[0] == array[1]);
- Assert.assertTrue(copiedArray[1] == array[2]);
- Assert.assertTrue(copiedArray[2] == array[3]);
+ assertTrue(3 == copiedArray.length);
+ assertTrue(copiedArray[0] == array[1]);
+ assertTrue(copiedArray[1] == array[2]);
+ assertTrue(copiedArray[2] == array[3]);
}
@Test
@@ -73,9 +75,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
- Assert.assertTrue(copiedArray[0] != array[0]);
+ assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
- Assert.assertTrue(copiedArray[1] != array[1]);
+ assertTrue(copiedArray[1] != array[1]);
}
@Test
@@ -85,7 +87,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
- Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@@ -96,9 +98,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
- Assert.assertTrue(copiedArray[0] != array[0]);
+ assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
- Assert.assertTrue(copiedArray[1] != array[1]);
+ assertTrue(copiedArray[1] != array[1]);
}
@Test
@@ -108,7 +110,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
- Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@@ -138,7 +140,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
- Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
diff --git a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java
index a6104e635b..8714d084ab 100644
--- a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java
+++ b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java
@@ -8,4 +8,4 @@ public class ClassNotFoundExceptionTest {
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java
rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java
index 501cb1afa0..0c3a13d176 100644
--- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java
@@ -11,9 +11,9 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-public class CompletableFutureUnitTest {
+public class CompletableFutureLongRunningUnitTest {
- private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test
@@ -24,7 +24,7 @@ public class CompletableFutureUnitTest {
assertEquals("Hello", result);
}
- public Future calculateAsync() throws InterruptedException {
+ private Future calculateAsync() throws InterruptedException {
CompletableFuture completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
@@ -44,7 +44,7 @@ public class CompletableFutureUnitTest {
assertEquals("Hello", result);
}
- public Future calculateAsyncWithCancellation() throws InterruptedException {
+ private Future calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java
index 11c27ff980..2f1abef64e 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java
@@ -24,8 +24,8 @@ public class LongAccumulatorUnitTest {
//when
Runnable accumulateAction = () -> IntStream
- .rangeClosed(0, numberOfIncrements)
- .forEach(accumulator::accumulate);
+ .rangeClosed(0, numberOfIncrements)
+ .forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
diff --git a/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
index 9111403155..3eb1d21872 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
@@ -17,7 +17,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
//given
final CopyOnWriteArrayList numbers =
- new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
+ new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator iterator = numbers.iterator();
@@ -42,7 +42,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
//given
final CopyOnWriteArrayList numbers =
- new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
+ new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator iterator = numbers.iterator();
diff --git a/core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
index 6490c6c094..180f3033ab 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
@@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
-import java.util.concurrent.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.DelayQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertEquals;
@@ -19,7 +23,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 500;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
- = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
+ = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@@ -41,7 +45,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
- = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
+ = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@@ -63,7 +67,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = -10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
- = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
+ = new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java
index a47c44506d..1dff70ffb8 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java
@@ -1,10 +1,10 @@
package com.baeldung.concurrent.future;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class FactorialSquareCalculatorUnitTest {
diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java
index 84d7a55504..5f8b05a974 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java
@@ -8,7 +8,12 @@ import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.*;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java
index 4dccbc3e26..0d4591e624 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java
@@ -9,65 +9,65 @@ import static junit.framework.TestCase.assertEquals;
public class SharedObjectWithLockManualTest {
- @Test
- public void whenLockAcquired_ThenLockedIsTrue() {
- final SharedObjectWithLock object = new SharedObjectWithLock();
+ @Test
+ public void whenLockAcquired_ThenLockedIsTrue() {
+ final SharedObjectWithLock object = new SharedObjectWithLock();
- final int threadCount = 2;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ final int threadCount = 2;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- executeThreads(object, threadCount, service);
+ executeThreads(object, threadCount, service);
- assertEquals(true, object.isLocked());
+ assertEquals(true, object.isLocked());
- service.shutdown();
- }
+ service.shutdown();
+ }
- @Test
- public void whenLocked_ThenQueuedThread() {
- final int threadCount = 4;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- final SharedObjectWithLock object = new SharedObjectWithLock();
+ @Test
+ public void whenLocked_ThenQueuedThread() {
+ final int threadCount = 4;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ final SharedObjectWithLock object = new SharedObjectWithLock();
- executeThreads(object, threadCount, service);
+ executeThreads(object, threadCount, service);
- assertEquals(object.hasQueuedThreads(), true);
+ assertEquals(object.hasQueuedThreads(), true);
- service.shutdown();
+ service.shutdown();
- }
+ }
- public void whenTryLock_ThenQueuedThread() {
- final SharedObjectWithLock object = new SharedObjectWithLock();
+ public void whenTryLock_ThenQueuedThread() {
+ final SharedObjectWithLock object = new SharedObjectWithLock();
- final int threadCount = 2;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ final int threadCount = 2;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- executeThreads(object, threadCount, service);
+ executeThreads(object, threadCount, service);
- assertEquals(true, object.isLocked());
+ assertEquals(true, object.isLocked());
- service.shutdown();
- }
+ service.shutdown();
+ }
- @Test
- public void whenGetCount_ThenCorrectCount() throws InterruptedException {
- final int threadCount = 4;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- final SharedObjectWithLock object = new SharedObjectWithLock();
+ @Test
+ public void whenGetCount_ThenCorrectCount() throws InterruptedException {
+ final int threadCount = 4;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ final SharedObjectWithLock object = new SharedObjectWithLock();
- executeThreads(object, threadCount, service);
- Thread.sleep(1000);
- assertEquals(object.getCounter(), 4);
+ executeThreads(object, threadCount, service);
+ Thread.sleep(1000);
+ assertEquals(object.getCounter(), 4);
- service.shutdown();
+ service.shutdown();
- }
+ }
- private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
- for (int i = 0; i < threadCount; i++) {
- service.execute(object::perform);
- }
- }
+ private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
+ for (int i = 0; i < threadCount; i++) {
+ service.execute(object::perform);
+ }
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java
index fd6cf08442..3014ae38b2 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java
@@ -1,6 +1,5 @@
package com.baeldung.concurrent.locks;
-import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
@@ -10,49 +9,49 @@ import static junit.framework.TestCase.assertEquals;
public class SynchronizedHashMapWithRWLockManualTest {
- @Test
- public void whenWriting_ThenNoReading() {
- SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
- final int threadCount = 3;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ @Test
+ public void whenWriting_ThenNoReading() {
+ SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
+ final int threadCount = 3;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- executeWriterThreads(object, threadCount, service);
+ executeWriterThreads(object, threadCount, service);
- assertEquals(object.isReadLockAvailable(), false);
+ assertEquals(object.isReadLockAvailable(), false);
- service.shutdown();
- }
+ service.shutdown();
+ }
- @Test
- public void whenReading_ThenMultipleReadingAllowed() {
- SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
- final int threadCount = 5;
- final ExecutorService service = Executors.newFixedThreadPool(threadCount);
+ @Test
+ public void whenReading_ThenMultipleReadingAllowed() {
+ SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
+ final int threadCount = 5;
+ final ExecutorService service = Executors.newFixedThreadPool(threadCount);
- executeReaderThreads(object, threadCount, service);
+ executeReaderThreads(object, threadCount, service);
- assertEquals(object.isReadLockAvailable(), true);
+ assertEquals(object.isReadLockAvailable(), true);
- service.shutdown();
- }
+ service.shutdown();
+ }
- private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
- for (int i = 0; i < threadCount; i++) {
- service.execute(() -> {
- try {
- object.put("key" + threadCount, "value" + threadCount);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
- }
- }
+ private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
+ for (int i = 0; i < threadCount; i++) {
+ service.execute(() -> {
+ try {
+ object.put("key" + threadCount, "value" + threadCount);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ });
+ }
+ }
- private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
- for (int i = 0; i < threadCount; i++)
- service.execute(() -> {
- object.get("key" + threadCount);
- });
- }
+ private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
+ for (int i = 0; i < threadCount; i++)
+ service.execute(() -> {
+ object.get("key" + threadCount);
+ });
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
index 9f7b828a9c..d1814c8fc9 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
@@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
try {
Integer poll = queue.take();
LOG.debug("Polled: " + poll);
- } catch (InterruptedException e) {
+ } catch (InterruptedException ignored) {
}
}
});
diff --git a/core-java/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java
new file mode 100644
index 0000000000..8d64bb6809
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java
@@ -0,0 +1,114 @@
+package com.baeldung.concurrent.semaphores;
+
+import org.junit.Test;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class SemaphoresManualTest {
+
+ // ========= login queue ======
+
+ @Test
+ public void givenLoginQueue_whenReachLimit_thenBlocked() {
+ final int slots = 10;
+ final ExecutorService executorService = Executors.newFixedThreadPool(slots);
+ final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
+ IntStream.range(0, slots)
+ .forEach(user -> executorService.execute(loginQueue::tryLogin));
+ executorService.shutdown();
+
+ assertEquals(0, loginQueue.availableSlots());
+ assertFalse(loginQueue.tryLogin());
+ }
+
+ @Test
+ public void givenLoginQueue_whenLogout_thenSlotsAvailable() {
+ final int slots = 10;
+ final ExecutorService executorService = Executors.newFixedThreadPool(slots);
+ final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
+ IntStream.range(0, slots)
+ .forEach(user -> executorService.execute(loginQueue::tryLogin));
+ executorService.shutdown();
+
+ assertEquals(0, loginQueue.availableSlots());
+ loginQueue.logout();
+ assertTrue(loginQueue.availableSlots() > 0);
+ assertTrue(loginQueue.tryLogin());
+ }
+
+ // ========= delay queue =======
+
+ @Test
+ public void givenDelayQueue_whenReachLimit_thenBlocked() {
+ final int slots = 50;
+ final ExecutorService executorService = Executors.newFixedThreadPool(slots);
+ final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
+ IntStream.range(0, slots)
+ .forEach(user -> executorService.execute(delayQueue::tryAdd));
+ executorService.shutdown();
+
+ assertEquals(0, delayQueue.availableSlots());
+ assertFalse(delayQueue.tryAdd());
+ }
+
+ @Test
+ public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
+ final int slots = 50;
+ final ExecutorService executorService = Executors.newFixedThreadPool(slots);
+ final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
+ IntStream.range(0, slots)
+ .forEach(user -> executorService.execute(delayQueue::tryAdd));
+ executorService.shutdown();
+
+ assertEquals(0, delayQueue.availableSlots());
+ Thread.sleep(1000);
+ assertTrue(delayQueue.availableSlots() > 0);
+ assertTrue(delayQueue.tryAdd());
+ }
+
+ // ========== mutex ========
+
+ @Test
+ public void whenMutexAndMultipleThreads_thenBlocked() throws InterruptedException {
+ final int count = 5;
+ final ExecutorService executorService = Executors.newFixedThreadPool(count);
+ final CounterUsingMutex counter = new CounterUsingMutex();
+ IntStream.range(0, count)
+ .forEach(user -> executorService.execute(() -> {
+ try {
+ counter.increase();
+ } catch (final InterruptedException e) {
+ e.printStackTrace();
+ }
+ }));
+ executorService.shutdown();
+
+ assertTrue(counter.hasQueuedThreads());
+ }
+
+ @Test
+ public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount() throws InterruptedException {
+ final int count = 5;
+ final ExecutorService executorService = Executors.newFixedThreadPool(count);
+ final CounterUsingMutex counter = new CounterUsingMutex();
+ IntStream.range(0, count)
+ .forEach(user -> executorService.execute(() -> {
+ try {
+ counter.increase();
+ } catch (final InterruptedException e) {
+ e.printStackTrace();
+ }
+ }));
+ executorService.shutdown();
+ assertTrue(counter.hasQueuedThreads());
+ Thread.sleep(5000);
+ assertFalse(counter.hasQueuedThreads());
+ assertEquals(count, counter.getCount());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java
index 303daa8d26..1f8e8d681a 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java
@@ -1,13 +1,13 @@
package com.baeldung.concurrent.synchronize;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class BaeldungSychronizedBlockTest {
@@ -17,7 +17,7 @@ public class BaeldungSychronizedBlockTest {
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
+ .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
@@ -28,7 +28,7 @@ public class BaeldungSychronizedBlockTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
+ .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
diff --git a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java b/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java
index e829423362..ba7c1f0a7b 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java
@@ -1,14 +1,14 @@
package com.baeldung.concurrent.synchronize;
-import static org.junit.Assert.assertEquals;
+import org.junit.Ignore;
+import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
-import org.junit.Ignore;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class BaeldungSynchronizeMethodsTest {
@@ -19,7 +19,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(method::calculate));
+ .forEach(count -> service.submit(method::calculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSum());
@@ -31,7 +31,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(method::synchronisedCalculate));
+ .forEach(count -> service.submit(method::synchronisedCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSyncSum());
@@ -42,7 +42,7 @@ public class BaeldungSynchronizeMethodsTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
+ .forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java
index 57e1f33280..a10ec66f20 100644
--- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java
@@ -7,13 +7,15 @@ import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
- Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
- Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
+ assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
+ assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
}
}
diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java
index 8f1997e9e8..e158c0fd67 100644
--- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java
@@ -7,48 +7,50 @@ import java.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
- Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
+ assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
- Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
+ assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
}
@Test
public void whenUsingClock_thenLocalDate() {
- Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
+ assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
}
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
- Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
+ assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
- Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
+ assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
- Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
+ assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
}
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
- Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
+ assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
}
@Test
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
- Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
+ assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
}
}
diff --git a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java
new file mode 100644
index 0000000000..887e7e41da
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java
@@ -0,0 +1,67 @@
+package com.baeldung.deserialization;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.io.InvalidClassException;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class DeserializationUnitTest {
+
+ private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
+
+ private static long userDefinedSerialVersionUID = 1234567L;
+
+ /**
+ * Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
+ * @throws ClassNotFoundException
+ * @throws IOException
+ */
+ @Test
+ public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
+
+ assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
+
+ AppleProduct macBook = new AppleProduct();
+ macBook.headphonePort = "headphonePort2020";
+ macBook.thunderboltPort = "thunderboltPort2020";
+
+ // serializes the "AppleProduct" object
+ String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
+
+ // deserializes the "AppleProduct" object
+ AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
+
+ assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
+ assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
+
+ }
+
+ /**
+ * Tests the deserialization of the modified (non-compatible) "AppleProduct".
+ * The test should result in an InvalidClassException being thrown.
+ *
+ * Note: to run this test:
+ * 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
+ * 2. Remove the @Ignore annotation
+ * 3. Run the test individually (do not run the entire set of tests)
+ * 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
+ *
+ * @throws ClassNotFoundException
+ * @throws IOException
+ */
+ @Ignore
+ @Test(expected = InvalidClassException.class)
+ public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
+
+ assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
+
+ // attempts to deserialize the "AppleProduct" object
+ DeserializationUtility.deSerializeObjectFromString(serializedObj);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
index f69e4b03ee..7157dead6e 100644
--- a/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
@@ -83,7 +83,7 @@ public class ComputerUtilsUnitTest {
final TriFunction integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
- Double initialValue = new Double(999.99);
+ Double initialValue = 999.99;
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}
diff --git a/core-java/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsManualTest.java
index 74886bdb53..ea71d1b5c1 100644
--- a/core-java/src/test/java/com/baeldung/file/FileOperationsManualTest.java
+++ b/core-java/src/test/java/com/baeldung/file/FileOperationsManualTest.java
@@ -6,7 +6,12 @@ import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
-import java.io.*;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@@ -14,6 +19,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
public class FileOperationsManualTest {
@Test
@@ -25,7 +34,7 @@ public class FileOperationsManualTest {
InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
- Assert.assertEquals(expectedData, data.trim());
+ assertEquals(expectedData, data.trim());
}
@Test
@@ -36,7 +45,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
- Assert.assertEquals(expectedData, data.trim());
+ assertEquals(expectedData, data.trim());
}
@Test
@@ -47,7 +56,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
- Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
+ assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@@ -61,7 +70,7 @@ public class FileOperationsManualTest {
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
- Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
+ assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@@ -72,7 +81,7 @@ public class FileOperationsManualTest {
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
- Assert.assertEquals(expectedData, data.trim());
+ assertEquals(expectedData, data.trim());
}
@Test
@@ -84,7 +93,7 @@ public class FileOperationsManualTest {
byte[] fileBytes = Files.readAllBytes(path);
String data = new String(fileBytes);
- Assert.assertEquals(expectedData, data.trim());
+ assertEquals(expectedData, data.trim());
}
@Test
@@ -98,7 +107,7 @@ public class FileOperationsManualTest {
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
- Assert.assertEquals(expectedData, data.toString().trim());
+ assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {
diff --git a/core-java/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java b/core-java/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java
new file mode 100644
index 0000000000..330ec3aee3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.filesystem.jndi.test;
+
+import com.baeldung.filesystem.jndi.LookupFSJNDI;
+import org.junit.Test;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import java.io.File;
+
+import static org.junit.Assert.assertNotNull;
+
+public class LookupFSJNDIIntegrationTest {
+ LookupFSJNDI fsjndi;
+ InitialContext ctx = null;
+ final String FILENAME = "test.find";
+
+ public LookupFSJNDIIntegrationTest() {
+ try {
+ fsjndi = new LookupFSJNDI();
+ } catch (NamingException e) {
+ fsjndi = null;
+ }
+ }
+
+ @Test
+ public void whenInitializationLookupFSJNDIIsNotNull_thenSuccess() {
+ assertNotNull("Class LookupFSJNDI has instance", fsjndi);
+ }
+
+ @Test
+ public void givenLookupFSJNDI_whengetInitialContextIsNotNull_thenSuccess() {
+ ctx = fsjndi.getCtx();
+ assertNotNull("Context exists", ctx);
+ }
+
+ @Test
+ public void givenInitialContext_whenLokupFileExists_thenSuccess() {
+ File file = fsjndi.getFile(FILENAME);
+ assertNotNull("File exists", file);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
index 1036df0bb8..811088cc0c 100644
--- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
@@ -25,7 +25,7 @@ public class FunctionalInterfaceUnitTest {
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map nameMap = new HashMap<>();
- Integer value = nameMap.computeIfAbsent("John", s -> s.length());
+ Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);
diff --git a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java
index 270cc8be9a..3c34bf2c6e 100644
--- a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java
@@ -2,7 +2,7 @@ package com.baeldung.hashing;
import org.junit.Test;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
public class SHA256HashingUnitTest {
diff --git a/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java b/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java
index 691615a1b4..acd6536ac4 100644
--- a/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java
+++ b/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java
@@ -2,7 +2,6 @@ package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
-import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@@ -17,6 +16,9 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
public class HttpRequestLiveTest {
@Test
@@ -39,7 +41,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
- StringBuffer content = new StringBuffer();
+ StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
@@ -67,7 +69,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
- StringBuffer content = new StringBuffer();
+ StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
diff --git a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java
new file mode 100644
index 0000000000..9a231a9a3d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.java.currentmethod;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * The class presents various ways of finding the name of currently executed method.
+ */
+public class CurrentlyExecutedMethodFinderTest {
+
+ @Test
+ public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
+ final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
+ assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
+ }
+
+ @Test
+ public void givenException_whenGetStackTrace_thenFindMethod() {
+ String methodName = new Exception().getStackTrace()[0].getMethodName();
+ assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
+ }
+
+ @Test
+ public void givenThrowable_whenGetStacktrace_thenFindMethod() {
+ StackTraceElement[] stackTrace = new Throwable().getStackTrace();
+ assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
+ }
+
+ @Test
+ public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
+ String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
+ assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
+ }
+
+ @Test
+ public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
+ class Local {};
+ String methodName = Local.class.getEnclosingMethod().getName();
+ assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
new file mode 100644
index 0000000000..7098f88f30
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
@@ -0,0 +1,52 @@
+package com.baeldung.java8;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static java.util.Arrays.asList;
+import static org.junit.Assert.assertEquals;
+
+public class Java8MapAndFlatMap {
+
+ @Test
+ public void givenStream_whenCalledMap_thenProduceList() {
+ List myList = Stream.of("a", "b")
+ .map(String::toUpperCase)
+ .collect(Collectors.toList());
+ assertEquals(asList("A", "B"), myList);
+ }
+
+ @Test
+ public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
+ List> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
+ System.out.println(list);
+
+ System.out.println(list
+ .stream().flatMap(Collection::stream)
+ .collect(Collectors.toList()));
+ }
+
+ @Test
+ public void givenOptional_whenCalledMap_thenProduceOptional() {
+ Optional s = Optional.of("test");
+ assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
+ }
+
+ @Test
+ public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
+ assertEquals(Optional.of(Optional.of("STRING")), Optional
+ .of("string")
+ .map(s -> Optional.of("STRING")));
+
+ assertEquals(Optional.of("STRING"), Optional
+ .of("string")
+ .flatMap(s -> Optional.of("STRING")));
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java
new file mode 100644
index 0000000000..293052e842
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java
@@ -0,0 +1,106 @@
+package com.baeldung.javanetworking.url.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.junit.BeforeClass;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.baeldung.javanetworking.url.URLDemo;
+
+@FixMethodOrder
+public class URLDemoTest {
+ private final Logger log = LoggerFactory.getLogger(URLDemo.class);
+ static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
+ // parsed locator
+ static String URLPROTOCOL = "https";
+ String URLAUTHORITY = "wordpress.org:443";
+ static String URLHOST = "wordpress.org";
+ static String URLPATH = "/support/topic/page-jumps-within-wordpress/";
+ String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
+ int URLPORT = 443;
+ static int URLDEFAULTPORT = 443;
+ static String URLQUERY = "replies=3";
+ static String URLREFERENCE = "post-2278484";
+ static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
+
+ static URL url;
+ URLConnection urlConnection = null;
+ HttpURLConnection connection = null;
+ BufferedReader in = null;
+ String urlContent = "";
+
+ @BeforeClass
+ public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException {
+ url = new URL(URLCOMPOUND);
+ }
+
+ // check parsed URL
+ @Test
+ public void givenURL_whenURLIsParsed_thenSuccess() {
+ assertNotNull("URL is null", url);
+ assertEquals("URL string is not equal", url.toString(), URLSTRING);
+ assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL);
+ assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY);
+ assertEquals("Host string is not equal", url.getHost(), URLHOST);
+ assertEquals("Path string is not equal", url.getPath(), URLPATH);
+ assertEquals("File string is not equal", url.getFile(), URLFILENAME);
+ assertEquals("Port number is not equal", url.getPort(), URLPORT);
+ assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT);
+ assertEquals("Query string is not equal", url.getQuery(), URLQUERY);
+ assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE);
+ }
+
+ // Obtain the content from location
+ @Test
+ public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException {
+ try {
+ urlConnection = url.openConnection();
+ } catch (IOException ex) {
+ urlConnection = null;
+ ex.printStackTrace();
+ }
+ assertNotNull("URL Connection is null", urlConnection);
+
+ connection = null;
+ assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection);
+ if (urlConnection instanceof HttpURLConnection) {
+ connection = (HttpURLConnection) urlConnection;
+ }
+ assertNotNull("Connection is null", connection);
+
+ log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
+
+ try {
+ in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+ } catch (IOException ex) {
+ in = null;
+ ex.printStackTrace();
+ }
+ assertNotNull("Input stream failed", in);
+
+ String current;
+ try {
+ while ((current = in.readLine()) != null) {
+ urlContent += current;
+ }
+ } catch (IOException ex) {
+ urlContent = null;
+ ex.printStackTrace();
+ }
+ assertNotNull("Content is null", urlContent);
+ assertTrue("Content is empty", urlContent.length() > 0);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
index 50abb4bc92..3c8f519082 100644
--- a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
@@ -14,7 +14,7 @@ import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListUnitTest {
- List> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
+ private List> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenNestedList_thenFlattenImperatively() {
@@ -36,13 +36,13 @@ public class FlattenNestedListUnitTest {
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
- public List flattenListOfListsImperatively(List> list) {
+ private List flattenListOfListsImperatively(List> list) {
List ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
- public List flattenListOfListsStream(List> list) {
+ private List flattenListOfListsStream(List> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
}
diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
index 75f8b8359f..7a23afa12f 100644
--- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
@@ -1,18 +1,19 @@
package com.baeldung.list.listoflist;
+import org.junit.Before;
+import org.junit.Test;
+
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
-import org.junit.Before;
-import org.junit.Test;
public class ListOfListsUnitTest {
- private List> listOfLists = new ArrayList>();
- private ArrayList penList = new ArrayList<>();
- private ArrayList pencilList = new ArrayList<>();
- private ArrayList rubberList = new ArrayList<>();
+ private List> listOfLists = new ArrayList<>();
+ private List penList = new ArrayList<>();
+ private List pencilList = new ArrayList<>();
+ private List rubberList = new ArrayList<>();
@SuppressWarnings("unchecked")
@Before
@@ -29,11 +30,11 @@ public class ListOfListsUnitTest {
@Test
public void givenListOfLists_thenCheckNames() {
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
- .get(0)).getName());
+ .get(0)).getName());
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
- .get(0)).getName());
+ .get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
- .get(0)).getName());
+ .get(0)).getName());
}
@SuppressWarnings("unchecked")
@@ -43,10 +44,10 @@ public class ListOfListsUnitTest {
((ArrayList) listOfLists.get(1)).remove(0);
listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
- .get(0)).getName());
+ .get(0)).getName());
listOfLists.remove(0);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
- .get(0)).getName());
+ .get(0)).getName());
}
@Test
@@ -60,17 +61,17 @@ public class ListOfListsUnitTest {
ArrayList rubbers = new ArrayList<>();
rubbers.add(new Rubber("Rubber 1"));
rubbers.add(new Rubber("Rubber 2"));
-
+
List> list = new ArrayList>();
list.add(pens);
list.add(pencils);
list.add(rubbers);
-
+
assertEquals("Pen 1", ((Pen) list.get(0)
- .get(0)).getName());
+ .get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1)
- .get(0)).getName());
+ .get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2)
- .get(0)).getName());
+ .get(0)).getName());
}
}
diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
index 22457d196e..3c2d9904d4 100644
--- a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
@@ -47,7 +47,7 @@ public class MappedByteBufferUnitTest {
//when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
- EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
+ EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
@@ -61,7 +61,7 @@ public class MappedByteBufferUnitTest {
}
- public Path getFileURIFromResources(String fileName) throws Exception {
+ private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).getPath());
}
diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java
new file mode 100644
index 0000000000..788fbd7047
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.maths;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public class BigDecimalImplTest {
+
+ @Test
+ public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
+ BigDecimal serviceTax = new BigDecimal("56.0084578639");
+ serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
+
+ BigDecimal entertainmentTax = new BigDecimal("23.00689");
+ entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
+
+ BigDecimal totalTax = serviceTax.add(entertainmentTax);
+ BigDecimal result = BigDecimal.valueOf(79.01);
+
+ Assert.assertEquals(result, totalTax);
+
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java
new file mode 100644
index 0000000000..aa8eaa9909
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.maths;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.math.BigInteger;
+
+public class BigIntegerImplTest {
+
+ @Test
+ public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
+ BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
+ BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
+
+ BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
+ BigInteger result = new BigInteger("14110718640342675608722521633212952");
+
+ Assert.assertEquals(result, totalStars);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundTest.java
index 95db146414..5ce9523e21 100644
--- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java
+++ b/core-java/src/test/java/com/baeldung/maths/RoundTest.java
@@ -5,6 +5,9 @@ import org.decimal4j.util.DoubleRounder;
import org.junit.Assert;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
public class RoundTest {
private double value = 2.03456d;
private int places = 2;
diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java
index 69906543a9..8948d1ebf7 100644
--- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java
@@ -3,13 +3,13 @@ package com.baeldung.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
+import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
-import javax.money.convert.ConversionQueryBuilder;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
@@ -19,7 +19,11 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
public class JavaMoneyUnitTest {
@@ -36,17 +40,16 @@ public class JavaMoneyUnitTest {
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
- fail(); // if no exception
}
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary
- .getDefaultAmountFactory()
- .setCurrency(usd)
- .setNumber(200)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency(usd)
+ .setNumber(200)
+ .create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
@@ -59,10 +62,10 @@ public class JavaMoneyUnitTest {
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
@@ -72,10 +75,10 @@ public class JavaMoneyUnitTest {
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
oneDolar.divide(3);
fail(); // if no exception
}
@@ -85,8 +88,8 @@ public class JavaMoneyUnitTest {
List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts
- .stream()
- .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
+ .stream()
+ .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@@ -97,18 +100,18 @@ public class JavaMoneyUnitTest {
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary
- .getDefaultAmountFactory()
- .setCurrency(usd)
- .setNumber(200.50)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency(usd)
+ .setNumber(200.50)
+ .create();
MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
Money subtractedAmount = Money
- .of(1, "USD")
- .subtract(fstAmtUSD);
+ .of(1, "USD")
+ .subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
@@ -124,22 +127,23 @@ public class JavaMoneyUnitTest {
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary
- .getDefaultAmountFactory()
- .setCurrency("EUR")
- .setNumber(1.30473908)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("EUR")
+ .setNumber(1.30473908)
+ .create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
+ @Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
@@ -152,10 +156,10 @@ public class JavaMoneyUnitTest {
@Test
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
@@ -167,16 +171,16 @@ public class JavaMoneyUnitTest {
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
- .of(Locale.US)
- .set(CurrencyStyle.NAME)
- .set("pattern", "00000.00 ¤")
- .build());
+ .of(Locale.US)
+ .set(CurrencyStyle.NAME)
+ .set("pattern", "00000.00 ¤")
+ .build());
String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat);
diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java
index bb446dc385..aa11aaa788 100644
--- a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java
+++ b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java
@@ -9,4 +9,4 @@ public class NoClassDefFoundErrorTest {
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
sample.getClassWithInitErrors();
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java
new file mode 100644
index 0000000000..bba867f50f
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.reflection;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+
+public class BaeldungReflectionUtilsTest {
+
+ @Test
+ public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
+ Customer customer = new Customer(1, "Himanshu", null, null);
+
+ List result = BaeldungReflectionUtils.getNullPropertiesList(customer);
+ List expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
+
+ assertTrue(result.size() == expectedFieldNames.size());
+ assertTrue(result.containsAll(expectedFieldNames));
+
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java
index f8dbde4c4f..47c9cfc621 100644
--- a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java
+++ b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java
@@ -1,71 +1,73 @@
package com.baeldung.regexp;
-import static junit.framework.TestCase.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.hamcrest.CoreMatchers.*;
+import org.junit.Test;
+
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.junit.Test;
+import static junit.framework.TestCase.assertEquals;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertThat;
public class EscapingCharsTest {
@Test
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
String strInput = "foof";
String strRegex = "foo.";
-
+
assertEquals(true, strInput.matches(strRegex));
}
-
+
@Test
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
String strInput = "foof";
String strRegex = "foo\\.";
-
+
assertEquals(false, strInput.matches(strRegex));
}
-
+
@Test
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "\\Q|\\E";
-
+
assertEquals(4, strInput.split(strRegex).length);
}
-
+
@Test
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "|";
-
- assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
+
+ assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
}
-
+
@Test
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
String strInput = "I gave $50 to my brother."
- + "He bought candy for $35. Now he has $15 left.";
+ + "He bought candy for $35. Now he has $15 left.";
String strRegex = "$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
- + "He bought candy for £35. Now he has £15 left.";
+ + "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
-
+
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
}
-
+
@Test
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
String strInput = "I gave $50 to my brother."
- + "He bought candy for $35. Now he has $15 left.";
+ + "He bought candy for $35. Now he has $15 left.";
String strRegex = "\\$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
- + "He bought candy for £35. Now he has £15 left.";
+ + "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
-
- assertEquals(output,m.replaceAll(strReplacement));
+
+ assertEquals(output, m.replaceAll(strReplacement));
}
}
diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
index fe1a7d4bd4..7f165cec86 100644
--- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
@@ -4,7 +4,11 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import javax.script.*;
+import javax.script.Bindings;
+import javax.script.Invocable;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
diff --git a/core-java/src/test/java/com/baeldung/serialization/PersonUnitTest.java b/core-java/src/test/java/com/baeldung/serialization/PersonUnitTest.java
index 86bd3f9c8d..dbcdf0ec9d 100644
--- a/core-java/src/test/java/com/baeldung/serialization/PersonUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/serialization/PersonUnitTest.java
@@ -1,6 +1,6 @@
-package com.baeuldung.serialization;
+package com.baeldung.serialization;
-import static org.junit.Assert.assertTrue;
+import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -8,57 +8,57 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import org.junit.Test;
+import static org.junit.Assert.assertTrue;
public class PersonUnitTest {
- @Test
- public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
- Person p = new Person();
- p.setAge(20);
- p.setName("Joe");
+ @Test
+ public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
+ Person p = new Person();
+ p.setAge(20);
+ p.setName("Joe");
- FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
- objectOutputStream.writeObject(p);
- objectOutputStream.flush();
- objectOutputStream.close();
+ FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
+ objectOutputStream.writeObject(p);
+ objectOutputStream.flush();
+ objectOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream("yofile.txt");
- ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
- Person p2 = (Person) objectInputStream.readObject();
- objectInputStream.close();
+ FileInputStream fileInputStream = new FileInputStream("yofile.txt");
+ ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
+ Person p2 = (Person) objectInputStream.readObject();
+ objectInputStream.close();
- assertTrue(p2.getAge() == p.getAge());
- assertTrue(p2.getName().equals(p.getName()));
- }
+ assertTrue(p2.getAge() == p.getAge());
+ assertTrue(p2.getName().equals(p.getName()));
+ }
- @Test
- public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
- Person p = new Person();
- p.setAge(20);
- p.setName("Joe");
+ @Test
+ public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
+ Person p = new Person();
+ p.setAge(20);
+ p.setName("Joe");
- Address a = new Address();
- a.setHouseNumber(1);
+ Address a = new Address();
+ a.setHouseNumber(1);
- Employee e = new Employee();
- e.setPerson(p);
- e.setAddress(a);
+ Employee e = new Employee();
+ e.setPerson(p);
+ e.setAddress(a);
- FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
- objectOutputStream.writeObject(e);
- objectOutputStream.flush();
- objectOutputStream.close();
+ FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
+ objectOutputStream.writeObject(e);
+ objectOutputStream.flush();
+ objectOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
- ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
- Employee e2 = (Employee) objectInputStream.readObject();
- objectInputStream.close();
+ FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
+ ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
+ Employee e2 = (Employee) objectInputStream.readObject();
+ objectInputStream.close();
- assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
- assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
- }
+ assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
+ assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
index 7ac8e0a97a..2bf6d142bb 100644
--- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
@@ -1,14 +1,14 @@
package com.baeldung.socket;
-import static org.junit.Assert.assertEquals;
-
-import java.util.concurrent.Executors;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import java.util.concurrent.Executors;
+
+import static org.junit.Assert.assertEquals;
+
public class EchoIntegrationTest {
private static final Integer PORT = 4444;
diff --git a/core-java/src/test/java/com/baeldung/stackoverflowerror/CyclicDependancyManualTest.java b/core-java/src/test/java/com/baeldung/stackoverflowerror/CyclicDependancyManualTest.java
index 9b86770453..1f1de9149a 100644
--- a/core-java/src/test/java/com/baeldung/stackoverflowerror/CyclicDependancyManualTest.java
+++ b/core-java/src/test/java/com/baeldung/stackoverflowerror/CyclicDependancyManualTest.java
@@ -1,11 +1,10 @@
package com.baeldung.stackoverflowerror;
-import static org.junit.Assert.fail;
import org.junit.Test;
public class CyclicDependancyManualTest {
@Test(expected = StackOverflowError.class)
public void whenInstanciatingClassOne_thenThrowsException() {
- ClassOne obj = new ClassOne();
+ ClassOne obj = new ClassOne();
}
}
diff --git a/core-java/src/test/java/com/baeldung/stackoverflowerror/InfiniteRecursionWithTerminationConditionManualTest.java b/core-java/src/test/java/com/baeldung/stackoverflowerror/InfiniteRecursionWithTerminationConditionManualTest.java
index 996d0e9017..3530fa1c3e 100644
--- a/core-java/src/test/java/com/baeldung/stackoverflowerror/InfiniteRecursionWithTerminationConditionManualTest.java
+++ b/core-java/src/test/java/com/baeldung/stackoverflowerror/InfiniteRecursionWithTerminationConditionManualTest.java
@@ -1,9 +1,9 @@
package com.baeldung.stackoverflowerror;
-import static junit.framework.TestCase.assertEquals;
-import static org.junit.Assert.fail;
import org.junit.Test;
+import static junit.framework.TestCase.assertEquals;
+
public class InfiniteRecursionWithTerminationConditionManualTest {
@Test
public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {
@@ -23,9 +23,9 @@ public class InfiniteRecursionWithTerminationConditionManualTest {
@Test(expected = StackOverflowError.class)
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
- int numToCalcFactorial = -1;
- InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
+ int numToCalcFactorial = -1;
+ InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
- irtc.calculateFactorial(numToCalcFactorial);
+ irtc.calculateFactorial(numToCalcFactorial);
}
}
diff --git a/core-java/src/test/java/com/baeldung/stackoverflowerror/RecursionWithCorrectTerminationConditionManualTest.java b/core-java/src/test/java/com/baeldung/stackoverflowerror/RecursionWithCorrectTerminationConditionManualTest.java
index a4269aef56..858cec2ffa 100644
--- a/core-java/src/test/java/com/baeldung/stackoverflowerror/RecursionWithCorrectTerminationConditionManualTest.java
+++ b/core-java/src/test/java/com/baeldung/stackoverflowerror/RecursionWithCorrectTerminationConditionManualTest.java
@@ -1,9 +1,9 @@
package com.baeldung.stackoverflowerror;
-import static junit.framework.TestCase.assertEquals;
-
import org.junit.Test;
+import static junit.framework.TestCase.assertEquals;
+
public class RecursionWithCorrectTerminationConditionManualTest {
@Test
public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {
diff --git a/core-java/src/test/java/com/baeldung/stackoverflowerror/UnintendedInfiniteRecursionManualTest.java b/core-java/src/test/java/com/baeldung/stackoverflowerror/UnintendedInfiniteRecursionManualTest.java
index 65126efff2..1e1c245d4d 100644
--- a/core-java/src/test/java/com/baeldung/stackoverflowerror/UnintendedInfiniteRecursionManualTest.java
+++ b/core-java/src/test/java/com/baeldung/stackoverflowerror/UnintendedInfiniteRecursionManualTest.java
@@ -6,25 +6,25 @@ import org.junit.Test;
public class UnintendedInfiniteRecursionManualTest {
@Test(expected = StackOverflowError.class)
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
- int numToCalcFactorial= 1;
+ int numToCalcFactorial = 1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
-
+
uir.calculateFactorial(numToCalcFactorial);
}
-
+
@Test(expected = StackOverflowError.class)
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
- int numToCalcFactorial= 2;
+ int numToCalcFactorial = 2;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
-
+
uir.calculateFactorial(numToCalcFactorial);
}
-
+
@Test(expected = StackOverflowError.class)
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
- int numToCalcFactorial= -1;
+ int numToCalcFactorial = -1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
-
+
uir.calculateFactorial(numToCalcFactorial);
}
}
diff --git a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
index 7ca1d000be..2238012e20 100644
--- a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
@@ -7,7 +7,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
-import static com.baeldung.strategy.Discounter.*;
+import static com.baeldung.strategy.Discounter.christmas;
+import static com.baeldung.strategy.Discounter.easter;
+import static com.baeldung.strategy.Discounter.newYear;
import static org.assertj.core.api.Assertions.assertThat;
public class StrategyDesignPatternUnitTest {
@@ -26,7 +28,7 @@ public class StrategyDesignPatternUnitTest {
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
Discounter staffDiscounter = new Discounter() {
@Override
- public BigDecimal apply( BigDecimal amount) {
+ public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.5));
}
};
diff --git a/core-java/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java
index fa482b8dfe..84c8992557 100644
--- a/core-java/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java
@@ -5,7 +5,6 @@ import org.junit.Test;
import java.util.Arrays;
import java.util.List;
-import java.util.Random;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -22,8 +21,8 @@ public class InfiniteStreamUnitTest {
//when
List collect = infiniteStream
- .limit(10)
- .collect(Collectors.toList());
+ .limit(10)
+ .collect(Collectors.toList());
//then
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
@@ -37,9 +36,9 @@ public class InfiniteStreamUnitTest {
//when
List randomInts = infiniteStreamOfRandomUUID
- .skip(10)
- .limit(10)
- .collect(Collectors.toList());
+ .skip(10)
+ .limit(10)
+ .collect(Collectors.toList());
//then
assertEquals(randomInts.size(), 10);
diff --git a/core-java/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/core-java/src/test/java/com/baeldung/stream/StreamAddUnitTest.java
index 8176d6a60c..d0745b8bc9 100644
--- a/core-java/src/test/java/com/baeldung/stream/StreamAddUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/stream/StreamAddUnitTest.java
@@ -1,10 +1,12 @@
package com.baeldung.stream;
+import org.junit.Test;
+
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+
import static org.junit.Assert.assertEquals;
-import org.junit.Test;
public class StreamAddUnitTest {
@@ -25,7 +27,7 @@ public class StreamAddUnitTest {
Stream newStream = Stream.concat(Stream.of(99), anStream);
assertEquals(newStream.findFirst()
- .get(), (Integer) 99);
+ .get(), (Integer) 99);
}
@Test
@@ -38,7 +40,7 @@ public class StreamAddUnitTest {
assertEquals(resultList.get(3), (Double) 9.9);
}
- public Stream insertInStream(Stream stream, T elem, int index) {
+ private Stream insertInStream(Stream stream, T elem, int index) {
List result = stream.collect(Collectors.toList());
result.add(index, elem);
return result.stream();
diff --git a/core-java/src/test/java/com/baeldung/stream/StreamApiTest.java b/core-java/src/test/java/com/baeldung/stream/StreamApiTest.java
index af52b3ee69..f4d0ac6b08 100644
--- a/core-java/src/test/java/com/baeldung/stream/StreamApiTest.java
+++ b/core-java/src/test/java/com/baeldung/stream/StreamApiTest.java
@@ -1,41 +1,40 @@
package com.baeldung.stream;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class StreamApiTest {
- private StreamApi streamApi = new StreamApi();
@Test
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
- List valueList = new ArrayList();
+ List valueList = new ArrayList<>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
- String last = streamApi.getLastElementUsingReduce(valueList);
+ String last = StreamApi.getLastElementUsingReduce(valueList);
assertEquals("Sean", last);
}
-
+
@Test
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
- Integer last = streamApi.getInfiniteStreamLastElementUsingReduce();
- assertEquals(new Integer(19), last);
+ int last = StreamApi.getInfiniteStreamLastElementUsingReduce();
+ assertEquals(19, last);
}
-
+
@Test
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
- List valueList = new ArrayList();
+ List valueList = new ArrayList<>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
- String last = streamApi.getLastElementUsingSkip(valueList);
+ String last = StreamApi.getLastElementUsingSkip(valueList);
assertEquals("Sean", last);
}
diff --git a/core-java/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java b/core-java/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java
index d58c1026d0..8901bcf9db 100644
--- a/core-java/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java
@@ -1,68 +1,66 @@
package com.baeldung.string;
-import static org.junit.Assert.*;
+import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
-
-import com.baeldung.string.JoinerSplitter;
+import static org.junit.Assert.assertEquals;
public class JoinerSplitterUnitTest {
- @Test
- public void provided_array_convert_to_stream_and_convert_to_string() {
+ @Test
+ public void provided_array_convert_to_stream_and_convert_to_string() {
- String[] programming_languages = {"java", "python", "nodejs", "ruby"};
+ String[] programming_languages = {"java", "python", "nodejs", "ruby"};
- String expectation = "java,python,nodejs,ruby";
-
- String result = JoinerSplitter.join(programming_languages);
- assertEquals(result, expectation);
- }
-
- @Test
- public void givenArray_transformedToStream_convertToPrefixPostfixString() {
+ String expectation = "java,python,nodejs,ruby";
- String[] programming_languages = {"java", "python",
- "nodejs", "ruby"};
- String expectation = "[java,python,nodejs,ruby]";
-
- String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
- assertEquals(result, expectation);
- }
-
- @Test
- public void givenString_transformedToStream_convertToList() {
+ String result = JoinerSplitter.join(programming_languages);
+ assertEquals(result, expectation);
+ }
- String programming_languages = "java,python,nodejs,ruby";
-
- List expectation = new ArrayList();
- expectation.add("java");
- expectation.add("python");
- expectation.add("nodejs");
- expectation.add("ruby");
-
- List result = JoinerSplitter.split(programming_languages);
-
- assertEquals(result, expectation);
- }
-
- @Test
- public void givenString_transformedToStream_convertToListOfChar() {
+ @Test
+ public void givenArray_transformedToStream_convertToPrefixPostfixString() {
+
+ String[] programming_languages = {"java", "python",
+ "nodejs", "ruby"};
+ String expectation = "[java,python,nodejs,ruby]";
+
+ String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
+ assertEquals(result, expectation);
+ }
+
+ @Test
+ public void givenString_transformedToStream_convertToList() {
+
+ String programming_languages = "java,python,nodejs,ruby";
+
+ List expectation = new ArrayList();
+ expectation.add("java");
+ expectation.add("python");
+ expectation.add("nodejs");
+ expectation.add("ruby");
+
+ List result = JoinerSplitter.split(programming_languages);
+
+ assertEquals(result, expectation);
+ }
+
+ @Test
+ public void givenString_transformedToStream_convertToListOfChar() {
+
+ String programming_languages = "java,python,nodejs,ruby";
+
+ List expectation = new ArrayList();
+ char[] charArray = programming_languages.toCharArray();
+ for (char c : charArray) {
+ expectation.add(c);
+ }
+
+ List result = JoinerSplitter.splitToListOfChar(programming_languages);
+ assertEquals(result, expectation);
+
+ }
- String programming_languages = "java,python,nodejs,ruby";
-
- List expectation = new ArrayList();
- char[] charArray = programming_languages.toCharArray();
- for (char c : charArray) {
- expectation.add(c);
- }
-
- List result = JoinerSplitter.splitToListOfChar(programming_languages);
- assertEquals(result, expectation);
-
- }
-
}
diff --git a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java b/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java
index 5d8703db1a..83fd253b97 100644
--- a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java
@@ -2,7 +2,6 @@ package com.baeldung.string;
import com.google.common.base.Splitter;
import org.apache.commons.lang.StringUtils;
-import org.assertj.core.util.Lists;
import org.junit.Test;
import java.util.List;
diff --git a/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java
index 427f02ba16..917ed1c937 100644
--- a/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java
@@ -1,9 +1,10 @@
package com.baeldung.string;
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-import org.apache.commons.lang3.StringUtils;
-import org.junit.Test;
public class StringHelperUnitTest {
@@ -67,7 +68,7 @@ public class StringHelperUnitTest {
assertEquals("abc", StringHelper.removeLastCharOptional(WHITE_SPACE_AT_THE_END_STRING));
assertEquals("abc", StringHelper.removeLastCharRegexOptional(WHITE_SPACE_AT_THE_END_STRING));
}
-
+
@Test
public void givenStringWithNewLineAtTheEnd_whenSubstring_thenGetStringWithoutNewLine() {
assertEquals("abc", StringHelper.removeLastChar(NEW_LINE_AT_THE_END_STRING));
@@ -78,7 +79,7 @@ public class StringHelperUnitTest {
assertEquals("abc", StringHelper.removeLastCharOptional(NEW_LINE_AT_THE_END_STRING));
assertNotEquals("abc", StringHelper.removeLastCharRegexOptional(NEW_LINE_AT_THE_END_STRING));
}
-
+
@Test
public void givenMultiLineString_whenSubstring_thenGetStringWithoutNewLine() {
assertEquals("abc\nde", StringHelper.removeLastChar(MULTIPLE_LINES_STRING));
diff --git a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java
new file mode 100644
index 0000000000..1b02e5d291
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.string;
+
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+
+public class StringToCharStreamUnitTest {
+
+ private String testString = "Tests";
+
+ @Test
+ public void givenTestString_whenChars_thenReturnIntStream() {
+ assertThat(testString.chars(), instanceOf(IntStream.class));
+ }
+
+ @Test
+ public void givenTestString_whenCodePoints_thenReturnIntStream() {
+ assertThat(testString.codePoints(), instanceOf(IntStream.class));
+ }
+
+ @Test
+ public void givenTestString_whenCodePoints_thenShowOccurences() throws Exception {
+ Map map = testString.codePoints()
+ .mapToObj(c -> (char) c)
+ .filter(Character::isLetter)
+ .collect(Collectors.toMap(c -> c, c -> 1, Integer::sum));
+
+ System.out.println(map);
+ }
+
+ @Test
+ public void givenIntStream_whenMapToObj_thenReturnCharacterStream() {
+ Stream characterStream = testString.chars()
+ .mapToObj(c -> (char) c);
+ Stream characterStream1 = testString.codePoints()
+ .mapToObj(c -> (char) c);
+ assertNotNull("IntStream returned by chars() did not map to Stream", characterStream);
+ assertNotNull("IntStream returned by codePoints() did not map to Stream", characterStream1);
+ }
+
+ @Test
+ public void givenIntStream_whenMapToObj_thenReturnStringStream() {
+ List strings = testString.codePoints()
+ .mapToObj(c -> String.valueOf((char) c))
+ .collect(Collectors.toList());
+
+ assertEquals(strings.size(), 5);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueUnitTest.java b/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueUnitTest.java
rename to core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
index 79339d1680..76df3c6450 100644
--- a/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
@@ -12,9 +12,9 @@ import java.util.concurrent.atomic.AtomicInteger;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class SynchronousQueueUnitTest {
+public class SynchronousQueueIntegrationTest {
- private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueUnitTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueIntegrationTest.class);
@Test
diff --git a/core-java/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java b/core-java/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java
new file mode 100644
index 0000000000..060f177265
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.typeerasure;
+
+import org.junit.Test;
+
+public class TypeErasureUnitTest {
+
+ @Test(expected = ClassCastException.class)
+ public void givenIntegerStack_whenStringPushedAndAssignPoppedValueToInteger_shouldFail() {
+ IntegerStack integerStack = new IntegerStack(5);
+ Stack stack = integerStack;
+ stack.push("Hello");
+ Integer data = integerStack.pop();
+ }
+
+ @Test
+ public void givenAnyArray_whenInvokedPrintArray_shouldSucceed() {
+ Integer[] scores = new Integer[] { 100, 200, 10, 99, 20 };
+ ArrayContentPrintUtil.printArray(scores);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java b/core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java
index f5cab88f3d..2f18c38bc7 100644
--- a/core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java
+++ b/core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java
@@ -15,7 +15,7 @@ class OffHeapArray {
return (Unsafe) f.get(null);
}
- public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
+ OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
this.size = size;
address = getUnsafe().allocateMemory(size * BYTE);
}
@@ -32,7 +32,7 @@ class OffHeapArray {
return size;
}
- public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
+ void freeMemory() throws NoSuchFieldException, IllegalAccessException {
getUnsafe().freeMemory(address);
}
diff --git a/core-java/src/test/resources/test.find b/core-java/src/test/resources/test.find
new file mode 100644
index 0000000000..0cb7d51df1
--- /dev/null
+++ b/core-java/src/test/resources/test.find
@@ -0,0 +1 @@
+Test of JNDI on file.
\ No newline at end of file
diff --git a/drools/README.MD b/drools/README.MD
new file mode 100644
index 0000000000..4ece7608fc
--- /dev/null
+++ b/drools/README.MD
@@ -0,0 +1,3 @@
+### Relevant Articles:
+[Introduction to Drools](http://www.baeldung.com/drools)
+[Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
diff --git a/drools/pom.xml b/drools/pom.xml
index b352044fb8..29231f150c 100644
--- a/drools/pom.xml
+++ b/drools/pom.xml
@@ -16,7 +16,7 @@
4.4.6
- 7.0.0.CR1
+ 7.1.0.Beta2
3.13
diff --git a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
index 5f0d619813..e8841b05e2 100644
--- a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
+++ b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
@@ -1,10 +1,15 @@
package com.baeldung.drools.config;
+import org.drools.decisiontable.DecisionTableProviderImpl;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.io.KieResources;
+import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
+import org.kie.internal.builder.DecisionTableConfiguration;
+import org.kie.internal.builder.DecisionTableInputType;
+import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import java.io.IOException;
import java.util.Arrays;
@@ -64,4 +69,39 @@ public class DroolsBeanFactory {
}
-}
\ No newline at end of file
+ public KieSession getKieSession(Resource dt) {
+ KieFileSystem kieFileSystem = kieServices.newKieFileSystem()
+ .write(dt);
+
+ KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem)
+ .buildAll();
+
+ KieRepository kieRepository = kieServices.getRepository();
+
+ ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
+
+ KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);
+
+ KieSession ksession = kieContainer.newKieSession();
+
+ return ksession;
+ }
+
+ /*
+ * Can be used for debugging
+ * Input excelFile example: com/baeldung/drools/rules/Discount.xls
+ */
+ public String getDrlFromExcel(String excelFile) {
+ DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
+ configuration.setInputType(DecisionTableInputType.XLS);
+
+ Resource dt = ResourceFactory.newClassPathResource(excelFile, getClass());
+
+ DecisionTableProviderImpl decisionTableProvider = new DecisionTableProviderImpl();
+
+ String drl = decisionTableProvider.loadFromResource(dt, null);
+
+ return drl;
+ }
+
+}
diff --git a/drools/src/main/java/com/baeldung/drools/model/Customer.java b/drools/src/main/java/com/baeldung/drools/model/Customer.java
new file mode 100644
index 0000000000..e900612b55
--- /dev/null
+++ b/drools/src/main/java/com/baeldung/drools/model/Customer.java
@@ -0,0 +1,44 @@
+package com.baeldung.drools.model;
+
+public class Customer {
+
+ private CustomerType type;
+
+ private int years;
+
+ private int discount;
+
+ public Customer(CustomerType type, int numOfYears) {
+ super();
+ this.type = type;
+ this.years = numOfYears;
+ }
+
+ public CustomerType getType() {
+ return type;
+ }
+
+ public void setType(CustomerType type) {
+ this.type = type;
+ }
+
+ public int getYears() {
+ return years;
+ }
+
+ public void setYears(int years) {
+ this.years = years;
+ }
+
+ public int getDiscount() {
+ return discount;
+ }
+
+ public void setDiscount(int discount) {
+ this.discount = discount;
+ }
+
+ public enum CustomerType {
+ INDIVIDUAL, BUSINESS;
+ }
+}
diff --git a/drools/src/main/resources/com/baeldung/drools/rules/Discount.xls b/drools/src/main/resources/com/baeldung/drools/rules/Discount.xls
new file mode 100644
index 0000000000..198cc8dcda
Binary files /dev/null and b/drools/src/main/resources/com/baeldung/drools/rules/Discount.xls differ
diff --git a/drools/src/test/java/com/baeldung/drools/service/ApplicantServiceIntegrationTest.java b/drools/src/test/java/com/baeldung/drools/service/ApplicantServiceIntegrationTest.java
index 71f33f2db4..f5d74c0a58 100644
--- a/drools/src/test/java/com/baeldung/drools/service/ApplicantServiceIntegrationTest.java
+++ b/drools/src/test/java/com/baeldung/drools/service/ApplicantServiceIntegrationTest.java
@@ -17,37 +17,39 @@ public class ApplicantServiceIntegrationTest {
private ApplicantService applicantService;
@Before
- public void setup(){
+ public void setup() {
applicantService = new ApplicantService();
}
@Test
public void whenCriteriaMatching_ThenSuggestManagerRole() throws IOException {
- Applicant applicant=new Applicant("Davis",37,1600000.0,11);
- SuggestedRole suggestedRole=new SuggestedRole();
- applicantService.suggestARoleForApplicant(applicant,suggestedRole);
- assertEquals("Manager",suggestedRole.getRole());
+ Applicant applicant = new Applicant("Davis", 37, 1600000.0, 11);
+ SuggestedRole suggestedRole = new SuggestedRole();
+ applicantService.suggestARoleForApplicant(applicant, suggestedRole);
+ assertEquals("Manager", suggestedRole.getRole());
}
@Test
public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole() throws IOException {
- Applicant applicant=new Applicant("John",37,1200000.0,8);
- SuggestedRole suggestedRole=new SuggestedRole();
- applicantService.suggestARoleForApplicant(applicant,suggestedRole);
- assertEquals("Senior developer",suggestedRole.getRole());
+ Applicant applicant = new Applicant("John", 37, 1200000.0, 8);
+ SuggestedRole suggestedRole = new SuggestedRole();
+ applicantService.suggestARoleForApplicant(applicant, suggestedRole);
+ assertEquals("Senior developer", suggestedRole.getRole());
}
+
@Test
public void whenCriteriaMatching_ThenSuggestDeveloperRole() throws IOException {
- Applicant applicant=new Applicant("Davis",37,800000.0,3);
- SuggestedRole suggestedRole=new SuggestedRole();
- applicantService.suggestARoleForApplicant(applicant,suggestedRole);
- assertEquals("Developer",suggestedRole.getRole());
+ Applicant applicant = new Applicant("Davis", 37, 800000.0, 3);
+ SuggestedRole suggestedRole = new SuggestedRole();
+ applicantService.suggestARoleForApplicant(applicant, suggestedRole);
+ assertEquals("Developer", suggestedRole.getRole());
}
+
@Test
public void whenCriteriaNotMatching_ThenNoRole() throws IOException {
- Applicant applicant=new Applicant("John",37,1200000.0,5);
- SuggestedRole suggestedRole=new SuggestedRole();
- applicantService.suggestARoleForApplicant(applicant,suggestedRole);
+ Applicant applicant = new Applicant("John", 37, 1200000.0, 5);
+ SuggestedRole suggestedRole = new SuggestedRole();
+ applicantService.suggestARoleForApplicant(applicant, suggestedRole);
assertNull(suggestedRole.getRole());
}
}
diff --git a/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java b/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java
new file mode 100644
index 0000000000..c3c4ebd4f8
--- /dev/null
+++ b/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.drools.service;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.kie.api.io.Resource;
+import org.kie.api.runtime.KieSession;
+import org.kie.internal.io.ResourceFactory;
+
+import com.baeldung.drools.config.DroolsBeanFactory;
+import com.baeldung.drools.model.Customer;
+import com.baeldung.drools.model.Customer.CustomerType;
+
+public class DiscountExcelIntegrationTest {
+
+ private KieSession kSession;
+
+ @Before
+ public void setup() {
+ Resource resource = ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Discount.xls", getClass());
+ kSession = new DroolsBeanFactory().getKieSession(resource);
+ }
+
+ @Test
+ public void giveIndvidualLongStanding_whenFireRule_thenCorrectDiscount() throws Exception {
+ Customer customer = new Customer(CustomerType.INDIVIDUAL, 5);
+ kSession.insert(customer);
+
+ kSession.fireAllRules();
+
+ assertEquals(customer.getDiscount(), 15);
+ }
+
+ @Test
+ public void giveIndvidualRecent_whenFireRule_thenCorrectDiscount() throws Exception {
+
+ Customer customer = new Customer(CustomerType.INDIVIDUAL, 1);
+ kSession.insert(customer);
+
+ kSession.fireAllRules();
+
+ assertEquals(customer.getDiscount(), 5);
+ }
+
+ @Test
+ public void giveBusinessAny_whenFireRule_thenCorrectDiscount() throws Exception {
+ Customer customer = new Customer(CustomerType.BUSINESS, 0);
+ kSession.insert(customer);
+
+ kSession.fireAllRules();
+
+ assertEquals(customer.getDiscount(), 20);
+ }
+
+}
diff --git a/drools/src/test/java/com/baeldung/drools/service/ProductServiceIntegrationTest.java b/drools/src/test/java/com/baeldung/drools/service/ProductServiceIntegrationTest.java
index 08c3fceb7d..73624c2c99 100644
--- a/drools/src/test/java/com/baeldung/drools/service/ProductServiceIntegrationTest.java
+++ b/drools/src/test/java/com/baeldung/drools/service/ProductServiceIntegrationTest.java
@@ -3,6 +3,7 @@ package com.baeldung.drools.service;
import com.baeldung.drools.model.Product;
import org.junit.Before;
import org.junit.Test;
+
import static junit.framework.TestCase.assertEquals;
@@ -11,22 +12,22 @@ public class ProductServiceIntegrationTest {
private ProductService productService;
@Before
- public void setup(){
- productService=new ProductService();
+ public void setup() {
+ productService = new ProductService();
}
@Test
- public void whenProductTypeElectronic_ThenLabelBarcode(){
- Product product=new Product("Microwave","Electronic");
- product=productService.applyLabelToProduct(product);
- assertEquals("BarCode",product.getLabel());
+ public void whenProductTypeElectronic_ThenLabelBarcode() {
+ Product product = new Product("Microwave", "Electronic");
+ product = productService.applyLabelToProduct(product);
+ assertEquals("BarCode", product.getLabel());
}
@Test
- public void whenProductTypeBook_ThenLabelIsbn(){
- Product product=new Product("AutoBiography","Book");
- product=productService.applyLabelToProduct(product);
- assertEquals("ISBN",product.getLabel());
+ public void whenProductTypeBook_ThenLabelIsbn() {
+ Product product = new Product("AutoBiography", "Book");
+ product = productService.applyLabelToProduct(product);
+ assertEquals("ISBN", product.getLabel());
}
}
diff --git a/guava/README.md b/guava/README.md
index f46c4dd3de..56d282560b 100644
--- a/guava/README.md
+++ b/guava/README.md
@@ -25,3 +25,6 @@
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
+- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
+- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
+- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
diff --git a/guest/junit5-example/.gitignore b/guest/junit5-example/.gitignore
new file mode 100644
index 0000000000..60be5b80aa
--- /dev/null
+++ b/guest/junit5-example/.gitignore
@@ -0,0 +1,4 @@
+/target/
+.settings/
+.classpath
+.project
diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml
new file mode 100644
index 0000000000..aec7f9228a
--- /dev/null
+++ b/guest/junit5-example/pom.xml
@@ -0,0 +1,68 @@
+
+ 4.0.0
+ junit5-example
+ junit5-example
+ 0.0.1-SNAPSHOT
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.0.0-M4
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ 5.0.0-M4
+
+
+
+ org.junit.vintage
+ junit-vintage-engine
+ 4.12.0-M4
+
+
+
+ com.h2database
+ h2
+ 1.4.195
+
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.2
+
+
+
+
+
+
+
+ maven-compiler-plugin
+ 3.5
+
+ 1.8
+ 1.8
+
+
+
+ maven-surefire-plugin
+ 2.19.1
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ 1.0.0-M4
+
+
+
+
+ math
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/junit5-example/src/main/java/com/stackify/daos/UserDAO.java b/guest/junit5-example/src/main/java/com/stackify/daos/UserDAO.java
new file mode 100644
index 0000000000..091d077ef6
--- /dev/null
+++ b/guest/junit5-example/src/main/java/com/stackify/daos/UserDAO.java
@@ -0,0 +1,141 @@
+package com.stackify.daos;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.stackify.models.User;
+import com.stackify.utils.ConnectionUtil;
+
+public class UserDAO {
+
+ private Logger logger = LogManager.getLogger(UserDAO.class);
+
+ public void createTable() {
+ try (Connection con = ConnectionUtil.getConnection()) {
+ String createQuery = "CREATE TABLE users(email varchar(50) primary key, name varchar(50))";
+ PreparedStatement pstmt = con.prepareStatement(createQuery);
+
+ pstmt.execute();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+
+ }
+
+ public void add(User user) {
+ try (Connection con = ConnectionUtil.getConnection()) {
+
+ String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
+ PreparedStatement pstmt = con.prepareStatement(insertQuery);
+ pstmt.setString(1, user.getEmail());
+ pstmt.setString(2, user.getName());
+
+ pstmt.executeUpdate();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ }
+
+ public void update(User user) {
+ try (Connection con = ConnectionUtil.getConnection()) {
+
+ String updateQuery = "UPDATE users SET name=? WHERE email=?";
+ PreparedStatement pstmt = con.prepareStatement(updateQuery);
+ pstmt.setString(1, user.getName());
+ pstmt.setString(2, user.getEmail());
+
+ pstmt.executeUpdate();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ }
+
+ public void delete(User user) {
+ try (Connection con = ConnectionUtil.getConnection()) {
+
+ String deleteQuery = "DELETE FROM users WHERE email=?";
+ PreparedStatement pstmt = con.prepareStatement(deleteQuery);
+ pstmt.setString(1, user.getEmail());
+
+ pstmt.executeUpdate();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ }
+
+ public void delete(String email) {
+ try (Connection con = ConnectionUtil.getConnection()) {
+
+ String deleteQuery = "DELETE FROM users WHERE email=?";
+ PreparedStatement pstmt = con.prepareStatement(deleteQuery);
+ pstmt.setString(1, email);
+
+ pstmt.executeUpdate();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ }
+
+ public User findOne(String email) {
+ User user = null;
+
+ try (Connection con = ConnectionUtil.getConnection()) {
+ String query = "SELECT * FROM users WHERE email=?";
+ PreparedStatement pstmt = con.prepareStatement(query);
+ pstmt.setString(1, email);
+
+ ResultSet rs = pstmt.executeQuery();
+ while (rs.next()) {
+ user = new User();
+ user.setEmail(rs.getString("email"));
+ user.setName(rs.getString("name"));
+ }
+
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+
+ return user;
+ }
+
+ public List findAll() {
+ List users = new ArrayList<>();
+
+ try (Connection con = ConnectionUtil.getConnection()) {
+ String query = "SELECT * FROM users";
+ PreparedStatement pstmt = con.prepareStatement(query);
+
+ ResultSet rs = pstmt.executeQuery();
+ while (rs.next()) {
+ User user = new User();
+ user.setEmail(rs.getString("email"));
+ user.setName(rs.getString("name"));
+ users.add(user);
+ }
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+
+ return users;
+ }
+
+ public void deleteAll() {
+ try (Connection con = ConnectionUtil.getConnection()) {
+
+ String deleteQuery = "DELETE FROM users";
+ PreparedStatement pstmt = con.prepareStatement(deleteQuery);
+
+ pstmt.executeUpdate();
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ }
+
+}
diff --git a/guest/junit5-example/src/main/java/com/stackify/models/User.java b/guest/junit5-example/src/main/java/com/stackify/models/User.java
new file mode 100644
index 0000000000..d6951102a7
--- /dev/null
+++ b/guest/junit5-example/src/main/java/com/stackify/models/User.java
@@ -0,0 +1,63 @@
+package com.stackify.models;
+
+public class User {
+ private String email;
+ private String name;
+
+ public User() {
+ }
+
+ public User(String email, String name) {
+ super();
+ this.email = email;
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((email == null) ? 0 : email.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ User other = (User) obj;
+ if (email == null) {
+ if (other.email != null)
+ return false;
+ } else if (!email.equals(other.email))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+}
diff --git a/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironment.java b/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironment.java
new file mode 100644
index 0000000000..2c1fa80f2e
--- /dev/null
+++ b/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironment.java
@@ -0,0 +1,15 @@
+package com.stackify.test.conditions;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.junit.jupiter.api.extension.ExtendWith;
+
+@Target({ ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+@ExtendWith(DisabledOnEnvironmentCondition.class)
+public @interface DisabledOnEnvironment {
+ String[] value();
+}
\ No newline at end of file
diff --git a/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironmentCondition.java b/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironmentCondition.java
new file mode 100644
index 0000000000..adb9d9c09e
--- /dev/null
+++ b/guest/junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironmentCondition.java
@@ -0,0 +1,38 @@
+package com.stackify.test.conditions;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.Properties;
+
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.TestExecutionCondition;
+import org.junit.jupiter.api.extension.TestExtensionContext;
+import org.junit.platform.commons.support.AnnotationSupport;
+
+import com.stackify.utils.ConnectionUtil;
+
+public class DisabledOnEnvironmentCondition implements TestExecutionCondition {
+
+ @Override
+ public ConditionEvaluationResult evaluate(TestExtensionContext context) {
+ Properties props = new Properties();
+ String env = "";
+ try {
+ props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
+ env = props.getProperty("env");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ Optional disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
+ if (disabled.isPresent()) {
+ String[] envs = disabled.get().value();
+ if (Arrays.asList(envs).contains(env)) {
+ return ConditionEvaluationResult.disabled("Disabled on environment " + env);
+ }
+ }
+
+ return ConditionEvaluationResult.enabled("Enabled on environment "+env);
+ }
+
+}
diff --git a/guest/junit5-example/src/main/java/com/stackify/utils/ConnectionUtil.java b/guest/junit5-example/src/main/java/com/stackify/utils/ConnectionUtil.java
new file mode 100644
index 0000000000..bcfe5058a7
--- /dev/null
+++ b/guest/junit5-example/src/main/java/com/stackify/utils/ConnectionUtil.java
@@ -0,0 +1,38 @@
+package com.stackify.utils;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+public class ConnectionUtil {
+
+ private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
+
+ public static Connection getConnection() {
+ try {
+ Properties props = new Properties();
+ props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties"));
+ Class.forName(props.getProperty("jdbc.driver"));
+ Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
+ return con;
+ }
+
+ catch (FileNotFoundException exc) {
+ logger.error(exc.getMessage());
+ } catch (IOException exc) {
+ logger.error(exc.getMessage());
+ } catch (ClassNotFoundException exc) {
+ logger.error(exc.getMessage());
+ } catch (SQLException exc) {
+ logger.error(exc.getMessage());
+ }
+ return null;
+ }
+
+}
diff --git a/guest/junit5-example/src/main/resources/application.properties b/guest/junit5-example/src/main/resources/application.properties
new file mode 100644
index 0000000000..601f964ff3
--- /dev/null
+++ b/guest/junit5-example/src/main/resources/application.properties
@@ -0,0 +1 @@
+env=dev
\ No newline at end of file
diff --git a/guest/junit5-example/src/main/resources/com/stackify/utils/jdbc.properties b/guest/junit5-example/src/main/resources/com/stackify/utils/jdbc.properties
new file mode 100644
index 0000000000..2d9a39b157
--- /dev/null
+++ b/guest/junit5-example/src/main/resources/com/stackify/utils/jdbc.properties
@@ -0,0 +1,4 @@
+jdbc.driver=org.h2.Driver
+jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
+jdbc.user=
+jdbc.password=
\ No newline at end of file
diff --git a/guest/junit5-example/src/main/resources/log4j2.xml b/guest/junit5-example/src/main/resources/log4j2.xml
new file mode 100644
index 0000000000..602b5ab490
--- /dev/null
+++ b/guest/junit5-example/src/main/resources/log4j2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/junit5-example/src/test/java/com/stackify/test/DatabaseConnectionTest.java b/guest/junit5-example/src/test/java/com/stackify/test/DatabaseConnectionTest.java
new file mode 100644
index 0000000000..d8f13b5715
--- /dev/null
+++ b/guest/junit5-example/src/test/java/com/stackify/test/DatabaseConnectionTest.java
@@ -0,0 +1,19 @@
+package com.stackify.test;
+
+import java.sql.Connection;
+
+import org.junit.jupiter.api.Test;
+
+import com.stackify.utils.ConnectionUtil;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public interface DatabaseConnectionTest {
+
+ @Test
+ default void testDatabaseConnection() {
+ Connection con = ConnectionUtil.getConnection();
+ assertNotNull(con);
+ }
+
+}
diff --git a/guest/junit5-example/src/test/java/com/stackify/test/DynamicTests.java b/guest/junit5-example/src/test/java/com/stackify/test/DynamicTests.java
new file mode 100644
index 0000000000..39b3b5aac5
--- /dev/null
+++ b/guest/junit5-example/src/test/java/com/stackify/test/DynamicTests.java
@@ -0,0 +1,38 @@
+package com.stackify.test;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.DynamicTest;
+import org.junit.jupiter.api.TestFactory;
+import org.junit.jupiter.api.function.ThrowingConsumer;
+
+import com.stackify.daos.UserDAO;
+import com.stackify.models.User;
+
+public class DynamicTests {
+
+ @TestFactory
+ public Collection dynamicTestCollection() {
+ return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1)));
+ }
+
+ @TestFactory
+ public Stream dynamicUserTestCollection() {
+ List inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana"));
+
+ Function displayNameGenerator = (input) -> "Saving user: " + input;
+
+ UserDAO userDAO = new UserDAO();
+ ThrowingConsumer testExecutor = (input) -> {
+ userDAO.add(input);
+ assertNotNull(userDAO.findOne(input.getEmail()));
+ };
+
+ return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
+ }
+}
diff --git a/guest/junit5-example/src/test/java/com/stackify/test/IncrementTest.java b/guest/junit5-example/src/test/java/com/stackify/test/IncrementTest.java
new file mode 100644
index 0000000000..a23a5bf20b
--- /dev/null
+++ b/guest/junit5-example/src/test/java/com/stackify/test/IncrementTest.java
@@ -0,0 +1,25 @@
+package com.stackify.test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.RepeatedTest;
+import org.junit.jupiter.api.RepetitionInfo;
+
+public class IncrementTest {
+
+ private static Logger logger = LogManager.getLogger(IncrementTest.class);
+
+ @BeforeEach
+ public void increment() {
+ logger.info("Before Each Test");
+ }
+
+ @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
+ public void test(RepetitionInfo info) {
+ assertTrue(1 == 1);
+ logger.info("Repetition #" + info.getCurrentRepetition());
+ }
+}
diff --git a/guest/junit5-example/src/test/java/com/stackify/test/TaggedTest.java b/guest/junit5-example/src/test/java/com/stackify/test/TaggedTest.java
new file mode 100644
index 0000000000..db3c38ceac
--- /dev/null
+++ b/guest/junit5-example/src/test/java/com/stackify/test/TaggedTest.java
@@ -0,0 +1,16 @@
+package com.stackify.test;
+
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("math")
+public class TaggedTest {
+
+ @Test
+ @Tag("arithmetic")
+ public void testEquals() {
+ assertTrue(1 == 1);
+ }
+
+}
diff --git a/guest/junit5-example/src/test/java/com/stackify/test/UsersTest.java b/guest/junit5-example/src/test/java/com/stackify/test/UsersTest.java
new file mode 100644
index 0000000000..88958a8232
--- /dev/null
+++ b/guest/junit5-example/src/test/java/com/stackify/test/UsersTest.java
@@ -0,0 +1,155 @@
+package com.stackify.test;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import com.stackify.daos.UserDAO;
+import com.stackify.models.User;
+
+import com.stackify.test.conditions.DisabledOnEnvironment;
+
+public class UsersTest implements DatabaseConnectionTest {
+
+ private static UserDAO userDAO;
+
+ private static Logger logger = LogManager.getLogger(UsersTest.class);
+
+ @BeforeAll
+ public static void addData() {
+ userDAO = new UserDAO();
+ userDAO.createTable();
+
+ User user1 = new User("john@gmail.com", "John");
+ User user2 = new User("ana@gmail.com", "Ana");
+ userDAO.add(user1);
+ userDAO.add(user2);
+ }
+
+ @Test
+ @DisplayName("Test Get Users")
+ public void testGetUsersNumber() {
+ assertEquals(2, userDAO.findAll().size());
+
+ }
+
+ @Test
+ @DisplayName("Test Get Users")
+ public void testGetUsersNumberWithInfo(TestInfo testInfo) {
+ assertEquals(2, userDAO.findAll().size());
+ assertEquals("Test Get Users", testInfo.getDisplayName());
+ assertEquals(UsersTest.class, testInfo.getTestClass().get());
+ logger.info("Running test method:" + testInfo.getTestMethod().get().getName());
+ }
+
+ @Test
+ public void testGetUser() {
+ User user = userDAO.findOne("john@gmail.com");
+ assertEquals("John", user.getName(), "User name:" + user.getName() + " incorrect");
+ }
+
+ @Test
+ public void testClassicAssertions() {
+ User user1 = userDAO.findOne("john@gmail.com");
+ User user2 = userDAO.findOne("john@yahoo.com");
+
+ assertNotNull(user1);
+ assertNull(user2);
+
+ user2 = new User("john@yahoo.com", "John");
+ assertEquals(user1.getName(), user2.getName(), "Names are not equal");
+ assertFalse(user1.getEmail().equals(user2.getEmail()), "Emails are equal");
+ assertNotSame(user1, user2);
+ }
+
+ @Test
+ @Disabled
+ public void testGroupedAssertions() {
+ User user = userDAO.findOne("john@gmail.com");
+ assertAll("user", () -> assertEquals("Johnson", user.getName()), () -> assertEquals("johnson@gmail.com", user.getEmail()));
+ }
+
+ @Test
+ public void testIterableEquals() {
+ User user1 = new User("john@gmail.com", "John");
+ User user2 = new User("ana@gmail.com", "Ana");
+
+ List