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/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/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/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/jmh/pom.xml b/jmh/pom.xml new file mode 100644 index 0000000000..8ecfaa9651 --- /dev/null +++ b/jmh/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + com.baeldung + jmh + jar + 1.0-SNAPSHOT + jmh + http://maven.apache.org + + + UTF-8 + UTF-8 + 1.8 + + + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + junit + junit + 3.8.1 + test + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.Application + + + + + + + + \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/Application.java b/jmh/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..28e70740e0 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/Application.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import java.io.IOException; + +import org.openjdk.jmh.Main; +import org.openjdk.jmh.runner.RunnerException; + +public class Application { + + public static void main(String[] args) throws RunnerException, IOException { + Main.main(args); + } + +} diff --git a/jmh/src/main/java/com/baeldung/BenchMark.java b/jmh/src/main/java/com/baeldung/BenchMark.java new file mode 100644 index 0000000000..f2b984d211 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/BenchMark.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.openjdk.jmh.annotations.Benchmark; + +public class BenchMark { + + @Benchmark + public void init() { + + } + +} diff --git a/jmh/src/main/resources/META-INF/BenchmarkList b/jmh/src/main/resources/META-INF/BenchmarkList new file mode 100644 index 0000000000..e69de29bb2 diff --git a/jmh/src/test/java/com/baeldung/AppTest.java b/jmh/src/test/java/com/baeldung/AppTest.java new file mode 100644 index 0000000000..c9f61455bd --- /dev/null +++ b/jmh/src/test/java/com/baeldung/AppTest.java @@ -0,0 +1,38 @@ +package com.baeldung; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/libraries/README.md b/libraries/README.md index f69885a30f..81d716cf48 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -16,6 +16,7 @@ - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) - [Introduction to HikariCP](http://www.baeldung.com/hikaricp) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) +- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 12511a243a..8285323f07 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -70,6 +70,32 @@ + + 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 + + diff --git a/libraries/src/docs/asciidoc/test.adoc b/libraries/src/docs/asciidoc/test.adoc new file mode 100644 index 0000000000..5a86a00440 --- /dev/null +++ b/libraries/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/libraries/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java b/libraries/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java index a986c35126..6ecf4ff964 100644 --- a/libraries/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java +++ b/libraries/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java @@ -13,21 +13,21 @@ public class AsciidoctorDemo { private final Asciidoctor asciidoctor; - public AsciidoctorDemo() { + AsciidoctorDemo() { asciidoctor = create(); } public void generatePDFFromString(final String input) { final Map options = options().inPlace(true) - .backend("pdf") - .asMap(); + .backend("pdf") + .asMap(); + final String outfile = asciidoctor.convertFile(new File("sample.adoc"), options); } - public String generateHTMLFromString(final String input) { - final String output = asciidoctor.convert("Hello _Baeldung_!", new HashMap()); - return output; + String generateHTMLFromString(final String input) { + return asciidoctor.convert("Hello _Baeldung_!", new HashMap()); } } diff --git a/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java b/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java index bcd585e586..6f1e8bc8cf 100644 --- a/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java +++ b/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java @@ -6,9 +6,7 @@ import org.openjdk.jmh.Main; import org.openjdk.jmh.runner.RunnerException; public class JmhDemo { - public static void main(String[] args) throws RunnerException, IOException { - Main.main(args); + Main.main(args); } - } diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/MainApplication.java b/libraries/src/main/java/com/baeldung/jmh/warmup/MainApplication.java new file mode 100644 index 0000000000..994a22c210 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmh/warmup/MainApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.jmh.warmup; + +public class MainApplication { + + static { + long start = System.nanoTime(); + ManualClassLoader.load(); + long end = System.nanoTime(); + System.out.println("Warm Up time : " + (end - start)); + } + + public static void main(String[] args) { + long start = System.nanoTime(); + ManualClassLoader.load(); + long end = System.nanoTime(); + System.out.println("Total time taken : " + (end - start)); + } + +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java b/libraries/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java new file mode 100644 index 0000000000..07cf7f6bcb --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java @@ -0,0 +1,17 @@ +package com.baeldung.jmh.warmup; + +import com.baeldung.jmh.warmup.dummy.Dummy; + +public class ManualClassLoader { + + public static void load() { + + for (int i = 0; i < 100000; i++) { + // load all(or most) important classes + Dummy dummy = new Dummy(); + dummy.m(); + } + + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java b/libraries/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java new file mode 100644 index 0000000000..d88215548c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java @@ -0,0 +1,9 @@ +package com.baeldung.jmh.warmup.dummy; + +public class Dummy { + + public void m() { + + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java index 39f9907316..97db4ddbe4 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java @@ -2,77 +2,78 @@ package com.baeldung.commons.lang3; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; -import static org.junit.Assert.assertEquals; + import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; public class ArrayUtilsUnitTest { @Test public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = { 2, 3, 4, 5 }; + int[] oldArray = {2, 3, 4, 5}; int[] newArray = ArrayUtils.add(oldArray, 0, 1); - int[] expectedArray = { 1, 2, 3, 4, 5 }; + int[] expectedArray = {1, 2, 3, 4, 5}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingElementAtTheEnd_thenCorrect() { - int[] oldArray = { 2, 3, 4, 5 }; + int[] oldArray = {2, 3, 4, 5}; int[] newArray = ArrayUtils.add(oldArray, 1); - int[] expectedArray = { 2, 3, 4, 5, 1 }; + int[] expectedArray = {2, 3, 4, 5, 1}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() { - int[] oldArray = { 0, 1, 2 }; + int[] oldArray = {0, 1, 2}; int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5); - int[] expectedArray = { 0, 1, 2, 3, 4, 5 }; + int[] expectedArray = {0, 1, 2, 3, 4, 5}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = { 1, 2, 3, 4, 5 }; + int[] oldArray = {1, 2, 3, 4, 5}; int[] newArray = ArrayUtils.remove(oldArray, 1); - int[] expectedArray = { 1, 3, 4, 5 }; + int[] expectedArray = {1, 3, 4, 5}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() { - int[] oldArray = { 1, 2, 3, 4, 5 }; + int[] oldArray = {1, 2, 3, 4, 5}; int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3); - int[] expectedArray = { 1, 3, 5 }; + int[] expectedArray = {1, 3, 5}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAnElement_thenCorrect() { - int[] oldArray = { 1, 2, 3, 3, 4 }; + int[] oldArray = {1, 2, 3, 3, 4}; int[] newArray = ArrayUtils.removeElement(oldArray, 3); - int[] expectedArray = { 1, 2, 3, 4 }; + int[] expectedArray = {1, 2, 3, 4}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElements_thenCorrect() { - int[] oldArray = { 1, 2, 3, 3, 4 }; + int[] oldArray = {1, 2, 3, 3, 4}; int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5); - int[] expectedArray = { 1, 3, 4 }; + int[] expectedArray = {1, 3, 4}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementOccurences_thenCorrect() { - int[] oldArray = { 1, 2, 2, 2, 3 }; + int[] oldArray = {1, 2, 2, 2, 3}; int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2); - int[] expectedArray = { 1, 3 }; + int[] expectedArray = {1, 3}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenCheckingExistingElement_thenCorrect() { - int[] array = { 1, 3, 5, 7, 9 }; + int[] array = {1, 3, 5, 7, 9}; boolean evenContained = ArrayUtils.contains(array, 2); boolean oddContained = ArrayUtils.contains(array, 7); assertEquals(false, evenContained); @@ -81,57 +82,57 @@ public class ArrayUtilsUnitTest { @Test public void givenArray_whenReversingElementsWithinARange_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.reverse(originalArray, 1, 4); - int[] expectedArray = { 1, 4, 3, 2, 5 }; + int[] expectedArray = {1, 4, 3, 2, 5}; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenReversingAllElements_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.reverse(originalArray); - int[] expectedArray = { 5, 4, 3, 2, 1 }; + int[] expectedArray = {5, 4, 3, 2, 1}; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingElementsWithinARange_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.shift(originalArray, 1, 4, 1); - int[] expectedArray = { 1, 4, 2, 3, 5 }; + int[] expectedArray = {1, 4, 2, 3, 5}; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingAllElements_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.shift(originalArray, 1); - int[] expectedArray = { 5, 1, 2, 3, 4 }; + int[] expectedArray = {5, 1, 2, 3, 4}; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenExtractingElements_thenCorrect() { - int[] oldArray = { 1, 2, 3, 4, 5 }; + int[] oldArray = {1, 2, 3, 4, 5}; int[] newArray = ArrayUtils.subarray(oldArray, 2, 7); - int[] expectedArray = { 3, 4, 5 }; + int[] expectedArray = {3, 4, 5}; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenSwapingElementsWithinARange_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.swap(originalArray, 0, 3, 2); - int[] expectedArray = { 4, 5, 3, 1, 2 }; + int[] expectedArray = {4, 5, 3, 1, 2}; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() { - int[] originalArray = { 1, 2, 3, 4, 5 }; + int[] originalArray = {1, 2, 3, 4, 5}; ArrayUtils.swap(originalArray, 0, 3); - int[] expectedArray = { 4, 2, 3, 1, 5 }; + int[] expectedArray = {4, 2, 3, 1, 5}; assertArrayEquals(expectedArray, originalArray); } } diff --git a/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java index b10086eabe..ae92617849 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java @@ -8,7 +8,7 @@ public class ComplexUnitTest { @Test public void whenComplexPow_thenCorrect() { - Complex first = new Complex(1.0, 3.0); + Complex first = new Complex(1.0, 3.0); Complex second = new Complex(2.0, 5.0); Complex power = first.pow(second); diff --git a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java index a5613e2406..f864c5f017 100644 --- a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java @@ -35,9 +35,9 @@ public class WordCountIntegrationTest { //then List> collect = result.collect(); assertThat(collect).containsExactlyInAnyOrder( - new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), - new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), - new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1)); + new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), + new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), + new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1)); } @Test @@ -48,9 +48,9 @@ public class WordCountIntegrationTest { //when List collect = amounts - .filter(a -> a > threshold) - .reduce((integer, t1) -> integer + t1) - .collect(); + .filter(a -> a > threshold) + .reduce((integer, t1) -> integer + t1) + .collect(); //then assertThat(collect.get(0)).isEqualTo(90); @@ -78,13 +78,13 @@ public class WordCountIntegrationTest { Tuple2 fourthPerson = new Tuple2<>(200, "Michael"); Tuple2 firstPerson = new Tuple2<>(1, "Jack"); DataSet> transactions = env.fromElements(fourthPerson, secondPerson, - thirdPerson, firstPerson); + thirdPerson, firstPerson); //when List> sorted = transactions - .sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING) - .collect(); + .sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING) + .collect(); //then assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson); @@ -99,15 +99,15 @@ public class WordCountIntegrationTest { Tuple2 firstTransaction = new Tuple2<>(1, "Transaction_1"); DataSet> transactions = - env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); + env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); //when List, Tuple3>> joined = - transactions.join(addresses) - .where(new IdKeySelectorTransaction()) - .equalTo(new IdKeySelectorAddress()) - .collect(); + transactions.join(addresses) + .where(new IdKeySelectorTransaction()) + .equalTo(new IdKeySelectorAddress()) + .collect(); //then assertThat(joined).hasSize(1); @@ -121,7 +121,7 @@ public class WordCountIntegrationTest { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream text - = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); + = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); SingleOutputStreamOperator upperCase = text.map(String::toUpperCase); @@ -139,8 +139,8 @@ public class WordCountIntegrationTest { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); SingleOutputStreamOperator> windowed = env.fromElements( - new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), - new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond()) + new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), + new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond()) ).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor>(Time.seconds(20)) { @Override public long extractTimestamp(Tuple2 element) { @@ -149,8 +149,8 @@ public class WordCountIntegrationTest { }); SingleOutputStreamOperator> reduced = windowed - .windowAll(TumblingEventTimeWindows.of(Time.seconds(5))) - .maxBy(0, true); + .windowAll(TumblingEventTimeWindows.of(Time.seconds(5))) + .maxBy(0, true); reduced.print(); diff --git a/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java b/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java index 0e29e3390a..1a1c5ef868 100644 --- a/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java @@ -1,9 +1,9 @@ package com.baeldung.hikaricp; -import java.util.List; - import org.junit.Test; +import java.util.List; + import static org.junit.Assert.assertEquals; public class HikariCPUnitTest { diff --git a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java index dd1d1dbcf3..30c034aa5e 100644 --- a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java @@ -4,7 +4,15 @@ package com.baeldung.javassist; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.NotFoundException; -import javassist.bytecode.*; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Mnemonic; import org.junit.Test; import java.io.DataOutputStream; @@ -66,7 +74,7 @@ public class JavasisstUnitTest { //then assertEquals(operations, - Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); + Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); } @@ -112,7 +120,7 @@ public class JavasisstUnitTest { } assertEquals(operations, - Arrays.asList("aload_0", "invokespecial", "return")); + Arrays.asList("aload_0", "invokespecial", "return")); } diff --git a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java index c99b4d28a2..a341d5957a 100644 --- a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java @@ -1,10 +1,5 @@ package com.baeldung.javatuples; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; - import org.javatuples.KeyValue; import org.javatuples.LabelValue; import org.javatuples.Pair; @@ -13,6 +8,11 @@ import org.javatuples.Triplet; import org.javatuples.Unit; import org.junit.Test; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + public class JavaTuplesUnitTest { @SuppressWarnings("unused") @@ -26,7 +26,7 @@ public class JavaTuplesUnitTest { Pair pairFromList = Pair.fromIterable(collectionOfNames, 2); - String[] names = new String[] { "john", "doe", "anne" }; + String[] names = new String[]{"john", "doe", "anne"}; Triplet triplet2 = Triplet.fromArray(names); } diff --git a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java index f261174062..3cdb833953 100644 --- a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java @@ -74,11 +74,11 @@ public class JaversUnitTest { Javers javers = JaversBuilder.javers().build(); PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", - Arrays.asList(new Address("England"), new Address("USA"))); + new PersonWithAddress(1, "Tom", + Arrays.asList(new Address("England"), new Address("USA"))); //when @@ -96,10 +96,10 @@ public class JaversUnitTest { Javers javers = JaversBuilder.javers().build(); PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", Collections.emptyList()); + new PersonWithAddress(1, "Tom", Collections.emptyList()); //when diff --git a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index 65f89d75b2..578f9ff902 100644 --- a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -24,14 +24,14 @@ public class GuideToJDOIntegrationTest { pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence"); pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); - pumd.addProperty("datanucleus.autoCreateSchema", "true"); + pumd.addProperty("datanucleus.autoCreateSchema", "true"); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - for (int i = 0; i < 100; i++){ + for (int i = 0; i < 100; i++) { String nam = "Product-" + i; Product productx = new Product(nam, (double) i); pm.makePersistent(productx); @@ -58,7 +58,7 @@ public class GuideToJDOIntegrationTest { pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence"); pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); - pumd.addProperty("datanucleus.autoCreateSchema", "true"); + pumd.addProperty("datanucleus.autoCreateSchema", "true"); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); @@ -93,9 +93,7 @@ public class GuideToJDOIntegrationTest { Query q = pm2.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price == 200"); @SuppressWarnings("unchecked") List products = (List) q.execute(); - Iterator iter = products.iterator(); - while (iter.hasNext()) { - Product p = iter.next(); + for (Product p : products) { assertEquals("Laptop", p.name); } diff --git a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index 38595e49d9..bdbc101b15 100644 --- a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -1,8 +1,6 @@ package com.baeldung.jsonassert; -import static org.assertj.core.api.Assertions.assertThat; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -13,6 +11,8 @@ import org.skyscreamer.jsonassert.RegularExpressionValueMatcher; import org.skyscreamer.jsonassert.comparator.ArraySizeComparator; import org.skyscreamer.jsonassert.comparator.CustomComparator; +import static org.assertj.core.api.Assertions.assertThat; + public class JsonAssertUnitTest { @Test @@ -44,7 +44,7 @@ public class JsonAssertUnitTest { @Test public void givenDifferentOrderForJsonObject_whenAssertEquals_thenPass() throws JSONException { String result = "{id:1,name:\"John\"}"; - + JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.STRICT); JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.LENIENT); } @@ -55,7 +55,7 @@ public class JsonAssertUnitTest { JSONObject actual = new JSONObject(); expected.put("id", Integer.valueOf(12345)); actual.put("id", Double.valueOf(12345)); - + JSONAssert.assertEquals(expected, actual, false); JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT); } @@ -63,11 +63,11 @@ public class JsonAssertUnitTest { @Test public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException { String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}"; + + "state:\"LA\", zip:91601}}"; JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}", result, false); + + "state:\"LA\", zip:91601}}", result, false); } - + @Test public void whenMessageUsedInAssertion_thenDisplayMessageOnFailure() throws JSONException { String actual = "{id:123,name:\"John\"}"; @@ -94,36 +94,36 @@ public class JsonAssertUnitTest { JSONAssert.assertNotEquals("[1,2,3]", result, JSONCompareMode.LENIENT); JSONAssert.assertNotEquals("[1,2,3,4,5,6]", result, JSONCompareMode.LENIENT); } - + @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; JSONAssert.assertEquals( - "{names:[4]}", - names, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + "{names:[4]}", + names, + new ArraySizeComparator(JSONCompareMode.LENIENT)); } - + @Test public void whenComparingContentsOfArray_thenPass() throws JSONException { String ratings = "{ratings:[3.2,3.5,4.1,5,1]}"; JSONAssert.assertEquals( - "{ratings:[1,5]}", - ratings, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + "{ratings:[1,5]}", + ratings, + new ArraySizeComparator(JSONCompareMode.LENIENT)); } - + @Test public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException { - JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", - new CustomComparator( - JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); - - JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", - new CustomComparator(JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); + JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", + new CustomComparator( + JSONCompareMode.STRICT, + new Customization("entry.id", + new RegularExpressionValueMatcher("\\d")))); + + JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", + new CustomComparator(JSONCompareMode.STRICT, + new Customization("entry.id", + new RegularExpressionValueMatcher("\\d")))); } } diff --git a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index c9141a6e57..1c95956761 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -1,13 +1,12 @@ package com.baeldung.junitparams; -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.runner.RunWith; - import junitparams.FileParameters; import junitparams.JUnitParamsRunner; import junitparams.Parameters; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertEquals; @RunWith(JUnitParamsRunner.class) public class SafeAdditionUtilTest { @@ -15,7 +14,7 @@ public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) + @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -27,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test @@ -37,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test diff --git a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java index d318345a56..08a472502e 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; } public static Object[] provideEdgeCaseData() { - return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; + return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; } } diff --git a/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java b/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java index a38791fd61..38bc8e002b 100644 --- a/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java +++ b/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java @@ -1,15 +1,5 @@ package com.baeldung.opennlp; -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; - import opennlp.tools.chunker.ChunkerME; import opennlp.tools.chunker.ChunkerModel; import opennlp.tools.cmdline.postag.POSModelLoader; @@ -31,14 +21,23 @@ import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.TrainingParameters; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertEquals; public class OpenNLPTests { private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south."; - private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." }; - + private final static String sentence[] = new String[]{"James", "Jordan", "live", "in", "Oklahoma", "city", "."}; + @Test - public void givenText_WhenDetectSentences_ThenCountSentences(){ + public void givenText_WhenDetectSentences_ThenCountSentences() { InputStream is; SentenceModel model; try { @@ -48,15 +47,13 @@ public class OpenNLPTests { String sentences[] = sdetector.sentDetect(text); assertEquals(4, sentences.length); is.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Test - public void givenText_WhenDetectTokens_ThenVerifyNames(){ + public void givenText_WhenDetectTokens_ThenVerifyNames() { InputStream is; TokenNameFinderModel model; try { @@ -68,15 +65,13 @@ public class OpenNLPTests { String[] names = Span.spansToStrings(nameSpans, sentence); assertEquals(1, names.length); assertEquals("James Jordan", names[0]); - } catch (FileNotFoundException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Test - public void givenText_WhenDetectTokens_ThenVerifyLocations(){ + public void givenText_WhenDetectTokens_ThenVerifyLocations() { InputStream is; TokenNameFinderModel model; try { @@ -88,15 +83,13 @@ public class OpenNLPTests { String[] locations = Span.spansToStrings(locationSpans, sentence); assertEquals(1, locations.length); assertEquals("Oklahoma", locations[0]); - } catch (FileNotFoundException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } - + @Test - public void givenText_WhenCategorizeDocument_ThenVerifyDocumentContent(){ + public void givenText_WhenCategorizeDocument_ThenVerifyDocumentContent() { DoccatModel docCatModel; try { InputStreamFactory isf = new InputStreamFactory() { @@ -118,7 +111,7 @@ public class OpenNLPTests { } @Test - public void givenText_WhenTagDocument_ThenVerifyTaggedString(){ + public void givenText_WhenTagDocument_ThenVerifyTaggedString() { try { POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin")); POSTaggerME posTaggerME = new POSTaggerME(posModel); @@ -140,19 +133,19 @@ public class OpenNLPTests { e.printStackTrace(); } } - + @Test - public void givenText_WhenChunked_ThenCountChunks(){ + public void givenText_WhenChunked_ThenCountChunks() { try { InputStream is = new FileInputStream("OpenNLP/en-chunker.bin"); ChunkerModel cModel = new ChunkerModel(is); ChunkerME chunkerME = new ChunkerME(cModel); - String pos[] = new String[] { "NNP", "NNP", "NNP", "POS", "NNP", "NN", "VBD"}; + String pos[] = new String[]{"NNP", "NNP", "NNP", "POS", "NNP", "NN", "VBD"}; String chunks[] = chunkerME.chunk(sentence, pos); assertEquals(7, chunks.length); } catch (IOException e) { e.printStackTrace(); } } - + } diff --git a/libraries/src/test/java/com/baeldung/serenity/GithubUserProfilePayloadIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/GithubUserProfilePayloadIntegrationTest.java index bfec945e63..09db11a184 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GithubUserProfilePayloadIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GithubUserProfilePayloadIntegrationTest.java @@ -2,9 +2,6 @@ package com.baeldung.serenity; import net.serenitybdd.jbehave.SerenityStory; -/** - * @author aiet - */ public class GithubUserProfilePayloadIntegrationTest extends SerenityStory { } diff --git a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java index 5fcd1bd458..1ebbd49e79 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java @@ -13,13 +13,11 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; -/** - * @author aiet - */ @RunWith(SerenityRunner.class) public class GoogleSearchLiveTest { - @Managed(driver = "chrome") private WebDriver browser; + @Managed(driver = "chrome") + private WebDriver browser; @Test public void whenGoogleBaeldungThenShouldSeeEugen() { diff --git a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchPageObjectLiveTest.java b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchPageObjectLiveTest.java index 1018281687..47fcdd5403 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchPageObjectLiveTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchPageObjectLiveTest.java @@ -7,15 +7,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; -/** - * @author aiet - */ @RunWith(SerenityRunner.class) public class GoogleSearchPageObjectLiveTest { - @Managed(driver = "chrome") private WebDriver browser; + @Managed(driver = "chrome") + private WebDriver browser; - GoogleSearchPageObject googleSearch; + private GoogleSearchPageObject googleSearch; @Test public void whenGoogleBaeldungThenShouldSeeEugen() { diff --git a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchScreenplayLiveTest.java b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchScreenplayLiveTest.java index e07c82943c..63a70ddff4 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchScreenplayLiveTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchScreenplayLiveTest.java @@ -12,19 +12,20 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; -import static net.serenitybdd.screenplay.GivenWhenThen.*; +import static net.serenitybdd.screenplay.GivenWhenThen.givenThat; +import static net.serenitybdd.screenplay.GivenWhenThen.seeThat; +import static net.serenitybdd.screenplay.GivenWhenThen.then; +import static net.serenitybdd.screenplay.GivenWhenThen.when; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.hasItem; -/** - * Unit test for simple App. - */ @RunWith(SerenityRunner.class) public class GoogleSearchScreenplayLiveTest { - @Managed(driver = "chrome") WebDriver browser; + @Managed(driver = "chrome") + private WebDriver browser; - Actor kitty = Actor.named("kitty"); + private Actor kitty = Actor.named("kitty"); @Before public void setup() { diff --git a/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java index 30faf92c6e..18488f9380 100644 --- a/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java @@ -16,7 +16,8 @@ import static com.baeldung.serenity.membership.MemberGrade.Silver; @RunWith(SerenityRunner.class) public class MemberStatusIntegrationTest { - @Steps MemberStatusSteps memberSteps; + @Steps + private MemberStatusSteps memberSteps; @Test public void membersShouldStartWithBronzeStatus() { @@ -42,7 +43,7 @@ public class MemberStatusIntegrationTest { @Test @Title("Members with 50,000 points can exchange a MacBook Pro") - public void memberWith50000PointsCanExchangeAMacbookpro(){ + public void memberWith50000PointsCanExchangeAMacbookpro() { memberSteps.aMemberHasPointsOf(50_000); memberSteps.aMemberExchangeA(MacBookPro); memberSteps.memberShouldHavePointsLeft(); @@ -55,7 +56,7 @@ public class MemberStatusIntegrationTest { @Test @Ignore @Title("Members with 500 points should have a Gold status when added 4,000 points ($40,000)") - public void memberWith500PointsEarnsGoldAfterSpends$40000(){ + public void memberWith500PointsEarnsGoldAfterSpends$40000() { memberSteps.aMemberHasPointsOf(500); memberSteps.theMemberSpends(40_000); memberSteps.theMemberShouldHaveAStatusOf(Gold); @@ -64,7 +65,7 @@ public class MemberStatusIntegrationTest { @Test @Ignore @Title("Members with 100 points would have a Gold status when added 10,000 points ($100,000)") - public void memberWith100EarnsGoldAfterSpends$100000(){ + public void memberWith100EarnsGoldAfterSpends$100000() { memberSteps.aMemberHasPointsOf(100); memberSteps.theMemberSpends(100_000); memberSteps.theMemberShouldHaveAStatusOf(Gold); diff --git a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestAssuredUserAPISteps.java b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestAssuredUserAPISteps.java index cc434d6d19..eba406a8b5 100644 --- a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestAssuredUserAPISteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestAssuredUserAPISteps.java @@ -8,25 +8,22 @@ import java.io.IOException; import static net.serenitybdd.rest.SerenityRest.rest; import static net.serenitybdd.rest.SerenityRest.then; -/** - * @author aiet - */ -public class GithubRestAssuredUserAPISteps { +class GithubRestAssuredUserAPISteps { private String api; @Step("Given the github REST API for user profile") - public void withUserProfileAPIEndpoint() { + void withUserProfileAPIEndpoint() { api = "https://api.github.com/users/{username}"; } @Step("When looking for {0} via the api") - public void getProfileOfUser(String username) throws IOException { + void getProfileOfUser(String username) throws IOException { rest().get(api, username); } @Step("Then there should be a login field with value {0} in payload of user {0}") - public void profilePayloadShouldContainLoginValue(String username) { + void profilePayloadShouldContainLoginValue(String username) { then().body("login", Matchers.equalTo(username)); } diff --git a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java index 6e7fbace49..2ba5b1c8ed 100644 --- a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java @@ -14,9 +14,6 @@ import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; -/** - * @author aiet - */ public class GithubRestUserAPISteps { private String api; diff --git a/libraries/src/test/java/com/baeldung/serenity/github/GithubUserProfilePayloadStepDefinitions.java b/libraries/src/test/java/com/baeldung/serenity/github/GithubUserProfilePayloadStepDefinitions.java index f3b374b66c..959f462dbd 100644 --- a/libraries/src/test/java/com/baeldung/serenity/github/GithubUserProfilePayloadStepDefinitions.java +++ b/libraries/src/test/java/com/baeldung/serenity/github/GithubUserProfilePayloadStepDefinitions.java @@ -9,11 +9,8 @@ import java.io.IOException; public class GithubUserProfilePayloadStepDefinitions { -// @Steps -// GithubRestUserAPISteps userAPISteps; - @Steps - GithubRestAssuredUserAPISteps userAPISteps; + private GithubRestAssuredUserAPISteps userAPISteps; @Given("github user profile api") public void givenGithubUserProfileApi() { diff --git a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java index 02b3f0130e..49ed8cae7d 100644 --- a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java @@ -6,12 +6,9 @@ import net.thucydides.core.annotations.Step; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ public class MemberStatusSteps { - Member member; + private Member member; @Step("Given a member has {0} points") public void aMemberHasPointsOf(int points) { @@ -35,7 +32,7 @@ public class MemberStatusSteps { @Pending @Step("When the member exchange {}") - public void aMemberExchangeA(Commodity commodity){ + public void aMemberExchangeA(Commodity commodity) { //TODO } diff --git a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java index 72569d86b5..bdba8a69bc 100644 --- a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java +++ b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java @@ -10,15 +10,14 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -/** - * @author aiet - */ @DefaultUrl("https://www.google.com/ncr") public class GoogleSearchPageObject extends PageObject { - @FindBy(name = "q") private WebElement search; + @FindBy(name = "q") + private WebElement search; - @FindBy(css = "._ksh") private WebElement result; + @FindBy(css = "._ksh") + private WebElement result; public void searchFor(String keyword) { search.sendKeys(keyword, Keys.ENTER); diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java index 0573e52ca4..b60c929c05 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java @@ -8,13 +8,13 @@ import net.thucydides.core.annotations.DefaultUrl; * @author baoqiang */ @DefaultUrl("https://www.google.com/ncr") -public class GoogleSearchPage extends PageObject { +class GoogleSearchPage extends PageObject { - public static final Target SEARCH_RESULT_TITLES = Target + static final Target SEARCH_RESULT_TITLES = Target .the("search results") .locatedBy("._ksh"); - public static final Target SEARCH_INPUT_BOX = Target + static final Target SEARCH_INPUT_BOX = Target .the("search input box") .locatedBy("#lst-ib"); diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java index 1cbcb22166..38990e13b6 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java @@ -6,9 +6,6 @@ import net.serenitybdd.screenplay.questions.Text; import java.util.List; -/** - * @author baoqiang - */ public class GoogleSearchResults implements Question> { public static Question> displayed() { diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java index 2783f14e51..1628ef8ed7 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java @@ -7,9 +7,6 @@ import net.serenitybdd.screenplay.actions.Enter; import net.thucydides.core.annotations.Step; import org.openqa.selenium.Keys; -/** - * @author baoqiang - */ public class SearchForKeyword implements Task { @Step("{0} searches for '#keyword'") diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java index ae9de5d798..52c6d07fda 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java @@ -7,9 +7,6 @@ import net.thucydides.core.annotations.Step; import static net.serenitybdd.screenplay.Tasks.instrumented; -/** - * @author baoqiang - */ public class StartWith implements Task { public static StartWith googleSearchPage() { diff --git a/libraries/src/test/java/com/baeldung/stm/AccountTest.java b/libraries/src/test/java/com/baeldung/stm/AccountTest.java index d45490df94..be3edf058c 100644 --- a/libraries/src/test/java/com/baeldung/stm/AccountTest.java +++ b/libraries/src/test/java/com/baeldung/stm/AccountTest.java @@ -1,9 +1,7 @@ package com.baeldung.stm; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java index f35073e9d9..e14a91ce67 100644 --- a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java @@ -17,10 +17,10 @@ public class JoolMergeStreamsTest { Stream seq2 = Stream.of(2, 4, 6); Stream resultingSeq = Seq.ofType(seq1, Integer.class) - .append(seq2); + .append(seq2); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingSeq.collect(Collectors.toList())); + resultingSeq.collect(Collectors.toList())); } @Test @@ -30,10 +30,10 @@ public class JoolMergeStreamsTest { Stream closingBracketSeq = Stream.of("]"); Stream resultingStream = Seq.ofType(seq, String.class) - .append(closingBracketSeq) - .prepend(openingBracketSeq); + .append(closingBracketSeq) + .prepend(openingBracketSeq); Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java index 217d2b5b64..23110947b6 100644 --- a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java @@ -17,10 +17,10 @@ public class MergeStreamsTest { Stream stream2 = Stream.of(2, 4, 6); Stream resultingStream = Stream.concat(stream1, - stream2); + stream2); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } @Test @@ -30,11 +30,11 @@ public class MergeStreamsTest { Stream stream3 = Stream.of(18, 15, 36); Stream resultingStream = Stream.concat(Stream.concat(stream1, - stream2), - stream3); + stream2), + stream3); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } @Test @@ -47,7 +47,7 @@ public class MergeStreamsTest { Stream resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity()); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java index 6ac3cc14cb..5104ec0682 100644 --- a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java @@ -19,7 +19,7 @@ public class StreamExMergeStreamsTest { Stream resultingStream = StreamEx.of(stream1).append(stream2); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } @Test @@ -30,12 +30,12 @@ public class StreamExMergeStreamsTest { Stream stream4 = Stream.of(99); Stream resultingStream = StreamEx.of(stream1) - .append(stream2) - .append(stream3) - .append(stream4); + .append(stream2) + .append(stream3) + .append(stream4); assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } @@ -46,10 +46,10 @@ public class StreamExMergeStreamsTest { Stream closingBracketStream = Stream.of("]"); Stream resultingStream = StreamEx.of(stream1) - .append(closingBracketStream) - .prepend(openingBracketStream); + .append(closingBracketStream) + .prepend(openingBracketStream); assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + resultingStream.collect(Collectors.toList())); } } diff --git a/spring-5/README.md b/spring-5/README.md index 31f665f4a2..510ee45f03 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -7,3 +7,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) +- [Exploring the Spring MVC URL Matching Improvements](http://www.baeldung.com/spring-mvc-url-matching) diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 605dbe39e1..4b373923ef 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -177,6 +177,7 @@ 1.0.0-M4 5.0.0-M4 2.20 + 5.0.0.RC2 diff --git a/spring-5/src/main/java/com/baeldung/Spring5Application.java b/spring-5/src/main/java/com/baeldung/Spring5Application.java index 41b5c1eed1..aaff1797ff 100644 --- a/spring-5/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/Spring5Application.java @@ -2,8 +2,10 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication +@ComponentScan(basePackages = {"com.baeldung.web"}) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java new file mode 100644 index 0000000000..b7436c5ba7 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -0,0 +1,61 @@ +package com.baeldung.functional; + +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; + +public class ExploreSpring5URLPatternUsingRouterFunctions { + + private RouterFunction routingFunction() { + + return route(GET("/p?ths"), serverRequest -> ok().body(fromObject("/p?ths"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("id")))) + .andRoute(GET("/*card"), serverRequest -> ok().body(fromObject("/*card path was accessed"))) + .andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2")))) + .andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromObject("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung")))) + .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/"))); + } + + WebServer start() throws Exception { + WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) + .prependFilter(new IndexRewriteFilter()) + .build(); + + Tomcat tomcat = new Tomcat(); + tomcat.setHostname("localhost"); + tomcat.setPort(9090); + Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); + ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); + Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); + + TomcatWebServer server = new TomcatWebServer(tomcat); + server.start(); + return server; + + } + + public static void main(String[] args) { + try { + new FunctionalWebApplication().start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index 258a23a2bf..8a808fc83a 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -15,6 +15,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import reactor.core.publisher.Flux; @@ -58,7 +59,7 @@ public class FunctionalSpringBootApplication { @Bean public ServletRegistrationBean servletRegistrationBean() throws Exception { HttpHandler httpHandler = WebHttpHandlerBuilder - .webHandler(toHttpHandler(routingFunction())) + .webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter()) .build(); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 573813b166..29f9ea43da 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -50,7 +50,7 @@ public class FunctionalWebApplication { } WebServer start() throws Exception { - WebHandler webHandler = toHttpHandler(routingFunction()); + WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder .webHandler(webHandler) .prependFilter(new IndexRewriteFilter()) diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index 3e19f81943..d218bba581 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -19,7 +19,7 @@ class IndexRewriteFilter implements WebFilter { .mutate() .request(builder -> builder .method(request.getMethod()) - .contextPath(request.getContextPath()) + .contextPath(request.getPath().toString()) .path("/test")) .build()); } diff --git a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java index 54892c829f..922809e563 100644 --- a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java +++ b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java @@ -23,12 +23,13 @@ import static org.springframework.web.reactive.function.server.RequestPredicates import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; import static org.springframework.web.reactive.function.server.ServerResponse.ok; +import org.springframework.web.server.WebHandler; public class RootServlet extends ServletHttpHandlerAdapter { public RootServlet() { this(WebHttpHandlerBuilder - .webHandler(toHttpHandler(routingFunction())) + .webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter()) .build()); } diff --git a/spring-5/src/main/java/com/baeldung/web/PathPatternController.java b/spring-5/src/main/java/com/baeldung/web/PathPatternController.java new file mode 100644 index 0000000000..15b689257a --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/web/PathPatternController.java @@ -0,0 +1,40 @@ +package com.baeldung.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class PathPatternController { + + @GetMapping("/spring5/{*id}") + public String URIVariableHandler(@PathVariable String id) { + return id; + } + + @GetMapping("/s?ring5") + public String wildcardTakingExactlyOneChar() { + return "/s?ring5"; + } + + @GetMapping("/spring5/*id") + public String wildcardTakingZeroOrMoreChar() { + return "/spring5/*id"; + } + + @GetMapping("/resources/**") + public String wildcardTakingZeroOrMorePathSegments() { + return "/resources/**"; + } + + @GetMapping("/{baeldung:[a-z]+}") + public String regexInPathVariable(@PathVariable String baeldung) { + return baeldung; + } + + @GetMapping("/{var1}_{var2}") + public String multiplePathVariablesInSameSegment(@PathVariable String var1, @PathVariable String var2) { + return "Two variables are var1=" + var1 + " and var2=" + var2; + } +} diff --git a/spring-5/src/main/resources/files/test/test.txt b/spring-5/src/main/resources/files/test/test.txt new file mode 100644 index 0000000000..30d74d2584 --- /dev/null +++ b/spring-5/src/main/resources/files/test/test.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java index 1ce96de4ef..cbb7a2867b 100644 --- a/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java @@ -9,14 +9,14 @@ public class ParallelIntegrationTest { @Test public void runTests() { - final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; + final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; JUnitCore.runClasses(new Computer(), classes); } @Test public void runTestsInParallel() { - final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; + final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; JUnitCore.runClasses(new ParallelComputer(true, true), classes); } diff --git a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java index 938ee7fd43..a155de20fa 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java @@ -15,9 +15,6 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = Spring5JUnit4ConcurrentIntegrationTest.SimpleConfiguration.class) public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContextAware, InitializingBean { diff --git a/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java b/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java new file mode 100644 index 0000000000..7a38fa697f --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java @@ -0,0 +1,110 @@ +package com.baeldung.functional; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.boot.web.server.WebServer; +import org.springframework.test.web.reactive.server.WebTestClient; + +public class ExploreSpring5URLPatternUsingRouterFunctionsTest { + + private static WebTestClient client; + private static WebServer server; + + @BeforeClass + public static void setup() throws Exception { + server = new ExploreSpring5URLPatternUsingRouterFunctions().start(); + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .build(); + } + + @AfterClass + public static void destroy() { + server.stop(); + } + + @Test + public void givenRouter_whenGetPathWithSingleCharWildcard_thenGotPathPattern() throws Exception { + client.get() + .uri("/paths") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("/p?ths"); + } + + @Test + public void givenRouter_whenMultipleURIVariablePattern_thenGotPathVariable() throws Exception { + client.get() + .uri("/test/ab/cd") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("/ab/cd"); + } + + @Test + public void givenRouter_whenGetMultipleCharWildcard_thenGotPathPattern() throws Exception { + + client.get() + .uri("/wildcard") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("/*card path was accessed"); + } + + @Test + public void givenRouter_whenGetMultiplePathVaribleInSameSegment_thenGotPathVariables() throws Exception { + + client.get() + .uri("/baeldung_tutorial") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("baeldung , tutorial"); + } + + @Test + public void givenRouter_whenGetRegexInPathVarible_thenGotPathVariable() throws Exception { + + client.get() + .uri("/abcd") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("/{baeldung:[a-z]+} was accessed and baeldung=abcd"); + + client.get() + .uri("/1234") + .exchange() + .expectStatus() + .is4xxClientError(); + } + + @Test + public void givenResources_whenAccess_thenGot() throws Exception { + client.get() + .uri("/files/test/test.txt") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("test"); + + client.get() + .uri("/files/hello.txt") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("hello"); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index cf1029c12f..6f39f11b00 100644 --- a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -8,7 +8,6 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.test.web.reactive.server.WebTestClient; - import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java index b90012edf6..42d27b90f4 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java @@ -16,10 +16,10 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class Spring5JUnit5ComposedAnnotationIntegrationTest { @Autowired - Task task; + private Task task; @Autowired - List tasks; + private List tasks; @Test @DisplayName("ApplicationContext injected into method") diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java index f0cc55fc80..0f00a85832 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.jupiter; import com.baeldung.web.reactive.Task; - +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -10,14 +10,12 @@ import org.springframework.test.context.ContextConfiguration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.jupiter.api.Test; - @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = TestConfig.class) class Spring5JUnit5IntegrationTest { @Autowired - Task task; + private Task task; @Test void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMetho(ApplicationContext applicationContext) { diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java index 1794da45f5..fb6bb27684 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java @@ -7,10 +7,10 @@ import org.junit.jupiter.api.Test; import org.junit.runner.Computer; import org.junit.runner.JUnitCore; -public class Spring5JUnit5ParallelIntegrationTest { +class Spring5JUnit5ParallelIntegrationTest { @Test - public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { + void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; @@ -19,7 +19,7 @@ public class Spring5JUnit5ParallelIntegrationTest { } @Test - public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { + void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java index 97efa19255..2c3a71fb3e 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java @@ -1,25 +1,25 @@ package com.baeldung.jupiter; import org.junit.jupiter.api.Test; + import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; + import static org.junit.jupiter.api.Assertions.assertEquals; -public class Spring5Java8NewFeaturesIntegrationTest { +class Spring5Java8NewFeaturesIntegrationTest { @FunctionalInterface public interface FunctionalInterfaceExample { Result reverseString(Input input); } - public class StringUtils{ - public FunctionalInterfaceExample - functionLambdaString = s -> { - return Pattern.compile(" +").splitAsStream(s) - .map(word->new StringBuilder(word).reverse()) + public class StringUtils { + FunctionalInterfaceExample + functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) + .map(word -> new StringBuilder(word).reverse()) .collect(Collectors.joining(" ")); - }; } @Test diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java index c44728c856..5c289c3e34 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java @@ -3,16 +3,8 @@ package com.baeldung.jupiter; import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.ClientRequest; -import org.springframework.web.reactive.function.client.ExchangeFunction; -import org.springframework.web.reactive.function.client.ExchangeFunctions; -import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; @@ -21,10 +13,8 @@ import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; -import java.net.URI; import java.time.Duration; -import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; diff --git a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java new file mode 100644 index 0000000000..90e3e7c445 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.web; + +import com.baeldung.Spring5Application; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class PathPatternsUsingHandlerMethodIntegrationTest { + + private static WebTestClient client; + + @BeforeClass + public static void setUp() { + client = WebTestClient.bindToController(new PathPatternController()) + .build(); + } + + @Test + public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() { + + client.get() + .uri("/spring5/ab/cd") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/ab/cd"); + } + + @Test + public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() { + + client.get() + .uri("/spring5/userid") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/spring5/*id"); + } + + @Test + public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() { + + client.get() + .uri("/string5") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/s?ring5"); + } + + @Test + public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() { + + client.get() + .uri("/resources/baeldung") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/resources/**"); + } + + @Test + public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() { + + client.get() + .uri("/abc") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("abc"); + + client.get() + .uri("/123") + .exchange() + .expectStatus() + .is4xxClientError(); + } + + @Test + public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() { + + client.get() + .uri("/baeldung_tutorial") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("Two variables are var1=baeldung and var2=tutorial"); + } + +} diff --git a/spring-core/README.md b/spring-core/README.md index 3f2abe42a1..380b3138fe 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -5,3 +5,4 @@ - [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring) - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) +- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 70002bf3c1..85cf4573aa 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -58,12 +58,17 @@ lombok ${lombok.version} + + org.springframework.boot + spring-boot-starter + 1.5.2.RELEASE + org.springframework.boot spring-boot-test ${mockito.spring.boot.version} test - + diff --git a/spring-core/src/main/java/com/baeldung/yaml/MyApplication.java b/spring-core/src/main/java/com/baeldung/yaml/MyApplication.java new file mode 100644 index 0000000000..4a585df998 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/yaml/MyApplication.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.yaml; + +import java.util.Collections; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MyApplication implements CommandLineRunner { + + @Autowired + private YAMLConfig myConfig; + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(MyApplication.class); + app.run(); + } + + public void run(String... args) throws Exception { + System.out.println("using environment:" + myConfig.getEnvironment()); + System.out.println("name:" + myConfig.getName()); + System.out.println("servers:" + myConfig.getServers()); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/yaml/YAMLConfig.java b/spring-core/src/main/java/com/baeldung/yaml/YAMLConfig.java new file mode 100644 index 0000000000..313b920502 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/yaml/YAMLConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.yaml; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties +@ConfigurationProperties +public class YAMLConfig { + private String name; + private String environment; + private List servers = new ArrayList(); + + public List getServers() { + return servers; + } + + public void setServers(List servers) { + this.servers = servers; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + +} diff --git a/spring-core/src/main/resources/application.properties b/spring-core/src/main/resources/application.properties index fdc6536237..11710b49aa 100644 --- a/spring-core/src/main/resources/application.properties +++ b/spring-core/src/main/resources/application.properties @@ -1,2 +1,2 @@ -someInitialValue=This is only sample value -anotherValue=Another configured value \ No newline at end of file +spring.profiles.active=prod + diff --git a/spring-core/src/main/resources/application.yml b/spring-core/src/main/resources/application.yml new file mode 100644 index 0000000000..6fc6f67cd0 --- /dev/null +++ b/spring-core/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + profiles: test +name: test-YAML +environment: test +servers: + - www.abc.test.com + - www.xyz.test.com + +--- + +spring: + profiles: prod +name: prod-YAML +environment: production +servers: + - www.abc.com + - www.xyz.com diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index e6ae05eb0f..763465be8c 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -1,8 +1,7 @@ 4.0.0 - com.baeldung - sprin-jooq + spring-jooq 0.0.1-SNAPSHOT diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java index cf9c83a93d..2503900e69 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java @@ -22,7 +22,7 @@ import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class AopPublishingIntegrationTest { @Before diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java similarity index 98% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/LiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java index dc5c265ed8..a8d273664d 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java @@ -12,7 +12,7 @@ import io.restassured.authentication.FormAuthConfig; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -public class LiveTest { +public class ApplicationLiveTest { private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/spring-security-mvc-boot/login", "username", "password"); diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java index 3dd4b236f9..503354256f 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java @@ -21,22 +21,22 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.context.SpringBootTest; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = { MvcConfig.class, SecurityConfig.class, PersistenceConfig.class }) +@SpringBootTest(classes = {MvcConfig.class, SecurityConfig.class, PersistenceConfig.class}) @WebAppConfiguration public class CustomUserDetailsServiceIntegrationTest { - public static final String USERNAME = "user"; - public static final String PASSWORD = "pass"; - public static final String USERNAME2 = "user2"; + private static final String USERNAME = "user"; + private static final String PASSWORD = "pass"; + private static final String USERNAME2 = "user2"; @Autowired - UserRepository myUserRepository; + private UserRepository myUserRepository; @Autowired - AuthenticationProvider authenticationProvider; + private AuthenticationProvider authenticationProvider; @Autowired - PasswordEncoder passwordEncoder; + private PasswordEncoder passwordEncoder; // diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java new file mode 100644 index 0000000000..9ef09f1f67 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java @@ -0,0 +1,61 @@ +package org.baeldung.web; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; + +import org.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MultipleAuthProvidersApplication.class) +public class MultipleAuthProvidersApplicationIntegrationTest { + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void givenMemUsers_whenGetPingWithValidUser_thenOk() { + ResponseEntity result = makeRestCallToGetPing("memuser", "pass"); + + assertThat(result.getStatusCodeValue()).isEqualTo(200); + assertThat(result.getBody()).isEqualTo("OK"); + } + + @Test + public void givenExternalUsers_whenGetPingWithValidUser_thenOK() { + ResponseEntity result = makeRestCallToGetPing("externaluser", "pass"); + + assertThat(result.getStatusCodeValue()).isEqualTo(200); + assertThat(result.getBody()).isEqualTo("OK"); + } + + @Test + public void givenAuthProviders_whenGetPingWithNoCred_then401() { + ResponseEntity result = makeRestCallToGetPing(); + + assertThat(result.getStatusCodeValue()).isEqualTo(401); + } + + @Test + public void givenAuthProviders_whenGetPingWithBadCred_then401() { + ResponseEntity result = makeRestCallToGetPing("user", "bad_password"); + + assertThat(result.getStatusCodeValue()).isEqualTo(401); + } + + private ResponseEntity makeRestCallToGetPing(String username, String password) { + return restTemplate.withBasicAuth(username, password) + .getForEntity("/api/ping", String.class, Collections.emptyMap()); + } + + private ResponseEntity makeRestCallToGetPing() { + return restTemplate.getForEntity("/api/ping", String.class, Collections.emptyMap()); + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java index 737b716209..157480c3f1 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java @@ -21,6 +21,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock @WebAppConfiguration @SpringBootTest(classes = MultipleEntryPointsApplication.class) public class MultipleEntryPointsIntegrationTest { + @Autowired private WebApplicationContext wac; diff --git a/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java b/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java index 843c88b694..21f1ab7425 100644 --- a/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java +++ b/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java @@ -1,11 +1,7 @@ package com.baeldung.vertxspring.repository; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - import com.baeldung.vertxspring.entity.Article; +import org.springframework.data.jpa.repository.JpaRepository; -@Repository -public interface ArticleRepository extends CrudRepository { - +public interface ArticleRepository extends JpaRepository { } diff --git a/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java b/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java index 55cb8bbfcb..8817701036 100644 --- a/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java +++ b/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java @@ -1,25 +1,20 @@ package com.baeldung.vertxspring.service; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import com.baeldung.vertxspring.entity.Article; import com.baeldung.vertxspring.repository.ArticleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; @Service public class ArticleService { @Autowired - ArticleRepository articleRepository; + private ArticleRepository articleRepository; public List
getAllArticle() { - List
articles = new ArrayList<>(); - articleRepository.findAll() - .forEach(articles::add); - return articles; + return articleRepository.findAll(); } }