Merge branch 'master' into master
This commit is contained in:
commit
0dadce5cf7
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finite state machine.
|
* Finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default implementation of a finite state machine.
|
* Default implementation of a finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* State. Part of a finite state machine.
|
* State. Part of a finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transition in a finite State machine.
|
* Transition in a finite State machine.
|
@ -5,7 +5,6 @@ import java.util.List;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class HillClimbing {
|
public class HillClimbing {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@ -22,7 +21,7 @@ public class HillClimbing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void printEachStep(State state) {
|
private static void printEachStep(State state) {
|
||||||
List<Stack<String>> stackList = state.getState();
|
List<Stack<String>> stackList = state.getState();
|
||||||
System.out.println("----------------");
|
System.out.println("----------------");
|
||||||
stackList.forEach(stack -> {
|
stackList.forEach(stack -> {
|
||||||
@ -33,8 +32,8 @@ public class HillClimbing {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stack<String> getStackWithValues(String[] blocks) {
|
private Stack<String> getStackWithValues(String[] blocks) {
|
||||||
Stack<String> stack = new Stack<String>();
|
Stack<String> stack = new Stack<>();
|
||||||
for (String block : blocks)
|
for (String block : blocks)
|
||||||
stack.push(block);
|
stack.push(block);
|
||||||
return stack;
|
return stack;
|
||||||
@ -42,14 +41,9 @@ public class HillClimbing {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* This method prepares path from init state to goal state
|
* This method prepares path from init state to goal state
|
||||||
*
|
|
||||||
* @param initStateStack
|
|
||||||
* @param goalStateStack
|
|
||||||
* @return
|
|
||||||
* @throws Exception
|
|
||||||
*/
|
*/
|
||||||
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
|
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
|
||||||
List<Stack<String>> initStateStackList = new ArrayList<Stack<String>>();
|
List<Stack<String>> initStateStackList = new ArrayList<>();
|
||||||
initStateStackList.add(initStateStack);
|
initStateStackList.add(initStateStack);
|
||||||
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
|
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
|
||||||
State initState = new State(initStateStackList, initStateHeuristics);
|
State initState = new State(initStateStackList, initStateHeuristics);
|
||||||
@ -71,57 +65,51 @@ public class HillClimbing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (noStateFound)
|
|
||||||
throw new Exception("No path found");
|
|
||||||
return resultPath;
|
return resultPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method finds new state from current state based on goal and
|
* This method finds new state from current state based on goal and
|
||||||
* heuristics
|
* heuristics
|
||||||
*
|
|
||||||
* @param currentState
|
|
||||||
* @param goalStateStack
|
|
||||||
* @return a next state
|
|
||||||
*/
|
*/
|
||||||
public State findNextState(State currentState, Stack<String> goalStateStack) {
|
public State findNextState(State currentState, Stack<String> goalStateStack) {
|
||||||
List<Stack<String>> listOfStacks = currentState.getState();
|
List<Stack<String>> listOfStacks = currentState.getState();
|
||||||
int currentStateHeuristics = currentState.getHeuristics();
|
int currentStateHeuristics = currentState.getHeuristics();
|
||||||
|
|
||||||
Optional<State> newState = listOfStacks.stream()
|
return listOfStacks.stream()
|
||||||
.map(stack -> {
|
.map(stack -> {
|
||||||
State tempState = null;
|
return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
|
||||||
List<Stack<String>> tempStackList = new ArrayList<Stack<String>>(listOfStacks);
|
|
||||||
String block = stack.pop();
|
|
||||||
if (stack.size() == 0)
|
|
||||||
tempStackList.remove(stack);
|
|
||||||
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
|
|
||||||
if (tempState == null) {
|
|
||||||
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
|
|
||||||
}
|
|
||||||
if (tempState == null)
|
|
||||||
stack.push(block);
|
|
||||||
return tempState;
|
|
||||||
})
|
})
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.findFirst();
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
return newState.orElse(null);
|
/**
|
||||||
|
* This method applies operations on the current state to get a new state
|
||||||
|
*/
|
||||||
|
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
State tempState;
|
||||||
|
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
|
||||||
|
String block = stack.pop();
|
||||||
|
if (stack.size() == 0)
|
||||||
|
tempStackList.remove(stack);
|
||||||
|
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
|
||||||
|
if (tempState == null) {
|
||||||
|
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
|
||||||
|
}
|
||||||
|
if (tempState == null)
|
||||||
|
stack.push(block);
|
||||||
|
return tempState;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Operation to be applied on a state in order to find new states. This
|
* Operation to be applied on a state in order to find new states. This
|
||||||
* operation pushes an element into a new stack
|
* operation pushes an element into a new stack
|
||||||
*
|
|
||||||
* @param currentStackList
|
|
||||||
* @param block
|
|
||||||
* @param currentStateHeuristics
|
|
||||||
* @param goalStateStack
|
|
||||||
* @return a new state
|
|
||||||
*/
|
*/
|
||||||
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
State newState = null;
|
State newState = null;
|
||||||
Stack<String> newStack = new Stack<String>();
|
Stack<String> newStack = new Stack<>();
|
||||||
newStack.push(block);
|
newStack.push(block);
|
||||||
|
|
||||||
currentStackList.add(newStack);
|
currentStackList.add(newStack);
|
||||||
@ -138,26 +126,13 @@ public class HillClimbing {
|
|||||||
* Operation to be applied on a state in order to find new states. This
|
* Operation to be applied on a state in order to find new states. This
|
||||||
* operation pushes an element into one of the other stacks to explore new
|
* operation pushes an element into one of the other stacks to explore new
|
||||||
* states
|
* states
|
||||||
*
|
|
||||||
* @param stack
|
|
||||||
* @param currentStackList
|
|
||||||
* @param block
|
|
||||||
* @param currentStateHeuristics
|
|
||||||
* @param goalStateStack
|
|
||||||
* @return a new state
|
|
||||||
*/
|
*/
|
||||||
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
|
||||||
Optional<State> newState = currentStackList.stream()
|
Optional<State> newState = currentStackList.stream()
|
||||||
.filter(stack -> stack != currentStack)
|
.filter(stack -> stack != currentStack)
|
||||||
.map(stack -> {
|
.map(stack -> {
|
||||||
stack.push(block);
|
return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
|
||||||
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
|
|
||||||
if (newStateHeuristics > currentStateHeuristics) {
|
|
||||||
return new State(currentStackList, newStateHeuristics);
|
|
||||||
}
|
|
||||||
stack.pop();
|
|
||||||
return null;
|
|
||||||
})
|
})
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.findFirst();
|
.findFirst();
|
||||||
@ -165,35 +140,50 @@ public class HillClimbing {
|
|||||||
return newState.orElse(null);
|
return newState.orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method pushes a block to the stack and returns new state if its closer to goal
|
||||||
|
*/
|
||||||
|
private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
stack.push(block);
|
||||||
|
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
|
||||||
|
if (newStateHeuristics > currentStateHeuristics) {
|
||||||
|
return new State(currentStackList, newStateHeuristics);
|
||||||
|
}
|
||||||
|
stack.pop();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method returns heuristics value for given state with respect to goal
|
* This method returns heuristics value for given state with respect to goal
|
||||||
* state
|
* state
|
||||||
*
|
|
||||||
* @param currentState
|
|
||||||
* @param goalStateStack
|
|
||||||
* @return
|
|
||||||
*/
|
*/
|
||||||
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
|
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
|
||||||
|
Integer heuristicValue;
|
||||||
Integer heuristicValue = 0;
|
|
||||||
heuristicValue = currentState.stream()
|
heuristicValue = currentState.stream()
|
||||||
.mapToInt(stack -> {
|
.mapToInt(stack -> {
|
||||||
int stackHeuristics = 0;
|
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
|
||||||
boolean isPositioneCorrect = true;
|
|
||||||
int goalStartIndex = 0;
|
|
||||||
for (String currentBlock : stack) {
|
|
||||||
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
|
|
||||||
stackHeuristics += goalStartIndex;
|
|
||||||
} else {
|
|
||||||
stackHeuristics -= goalStartIndex;
|
|
||||||
isPositioneCorrect = false;
|
|
||||||
}
|
|
||||||
goalStartIndex++;
|
|
||||||
}
|
|
||||||
return stackHeuristics;
|
|
||||||
})
|
})
|
||||||
.sum();
|
.sum();
|
||||||
return heuristicValue;
|
return heuristicValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method returns heuristics value for a particular stack
|
||||||
|
*/
|
||||||
|
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
|
||||||
|
int stackHeuristics = 0;
|
||||||
|
boolean isPositioneCorrect = true;
|
||||||
|
int goalStartIndex = 0;
|
||||||
|
for (String currentBlock : stack) {
|
||||||
|
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
|
||||||
|
stackHeuristics += goalStartIndex;
|
||||||
|
} else {
|
||||||
|
stackHeuristics -= goalStartIndex;
|
||||||
|
isPositioneCorrect = false;
|
||||||
|
}
|
||||||
|
goalStartIndex++;
|
||||||
|
}
|
||||||
|
return stackHeuristics;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,26 +5,23 @@ import java.util.List;
|
|||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
|
|
||||||
public class State {
|
public class State {
|
||||||
List<Stack<String>> state;
|
private List<Stack<String>> state;
|
||||||
int heuristics;
|
private int heuristics;
|
||||||
|
|
||||||
public State() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public State(List<Stack<String>> state) {
|
public State(List<Stack<String>> state) {
|
||||||
this.state = state;
|
this.state = state;
|
||||||
}
|
}
|
||||||
|
|
||||||
public State(List<Stack<String>> state, int heuristics) {
|
State(List<Stack<String>> state, int heuristics) {
|
||||||
this.state = state;
|
this.state = state;
|
||||||
this.heuristics = heuristics;
|
this.heuristics = heuristics;
|
||||||
}
|
}
|
||||||
|
|
||||||
public State(State state) {
|
State(State state) {
|
||||||
if (state != null) {
|
if (state != null) {
|
||||||
this.state = new ArrayList<Stack<String>>();
|
this.state = new ArrayList<>();
|
||||||
for (Stack s : state.getState()) {
|
for (Stack s : state.getState()) {
|
||||||
Stack s1 = new Stack();
|
Stack s1;
|
||||||
s1 = (Stack) s.clone();
|
s1 = (Stack) s.clone();
|
||||||
this.state.add(s1);
|
this.state.add(s1);
|
||||||
}
|
}
|
||||||
@ -36,10 +33,6 @@ public class State {
|
|||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setState(List<Stack<String>> state) {
|
|
||||||
this.state = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getHeuristics() {
|
public int getHeuristics() {
|
||||||
return heuristics;
|
return heuristics;
|
||||||
}
|
}
|
||||||
|
@ -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<State> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<State> getAllPossibleStates() {
|
||||||
|
List<State> possibleStates = new ArrayList<>();
|
||||||
|
List<Position> 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<Position> 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;
|
||||||
|
}
|
||||||
|
}
|
@ -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())));
|
||||||
|
}
|
||||||
|
}
|
@ -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<Position> getEmptyPositions() {
|
||||||
|
int size = this.boardValues.length;
|
||||||
|
List<Position> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<Node> 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<Node> 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<Node> 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<Node> getChildArray() {
|
||||||
|
return childArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setChildArray(List<Node> 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();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -14,17 +14,17 @@ import static org.junit.Assert.assertNotNull;
|
|||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class HillClimbingAlgorithmTest {
|
public class HillClimbingAlgorithmTest {
|
||||||
Stack<String> initStack;
|
private Stack<String> initStack;
|
||||||
Stack<String> goalStack;
|
private Stack<String> goalStack;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void initStacks() {
|
public void initStacks() {
|
||||||
String blockArr[] = { "B", "C", "D", "A" };
|
String blockArr[] = { "B", "C", "D", "A" };
|
||||||
String goalBlockArr[] = { "A", "B", "C", "D" };
|
String goalBlockArr[] = { "A", "B", "C", "D" };
|
||||||
initStack = new Stack<String>();
|
initStack = new Stack<>();
|
||||||
for (String block : blockArr)
|
for (String block : blockArr)
|
||||||
initStack.push(block);
|
initStack.push(block);
|
||||||
goalStack = new Stack<String>();
|
goalStack = new Stack<>();
|
||||||
for (String block : goalBlockArr)
|
for (String block : goalBlockArr)
|
||||||
goalStack.push(block);
|
goalStack.push(block);
|
||||||
}
|
}
|
||||||
@ -48,7 +48,7 @@ public class HillClimbingAlgorithmTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
|
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
|
||||||
HillClimbing hillClimbing = new HillClimbing();
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
List<Stack<String>> initList = new ArrayList<Stack<String>>();
|
List<Stack<String>> initList = new ArrayList<>();
|
||||||
initList.add(initStack);
|
initList.add(initStack);
|
||||||
State currentState = new State(initList);
|
State currentState = new State(initList);
|
||||||
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
|
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import com.baeldung.automata.*;
|
import com.baeldung.algorithms.automata.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
92
algorithms/src/test/java/algorithms/mcts/MCTSTest.java
Normal file
92
algorithms/src/test/java/algorithms/mcts/MCTSTest.java
Normal file
@ -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<State> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
3
asciidoctor/README.md
Normal file
3
asciidoctor/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
0
asciidoctor/log4j.properties
Normal file
0
asciidoctor/log4j.properties
Normal file
56
asciidoctor/pom.xml
Normal file
56
asciidoctor/pom.xml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>asciidoctor</artifactId>
|
||||||
|
<name>asciidoctor</name>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||||
|
<version>1.5.5</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.15</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>output-pdf</id>
|
||||||
|
<phase>generate-resources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>process-asciidoc</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<sourceDirectory>src/docs/asciidoc</sourceDirectory>
|
||||||
|
<outputDirectory>target/docs/asciidoc</outputDirectory>
|
||||||
|
<backend>pdf</backend>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj</artifactId>
|
||||||
|
<version>1.5.4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.11</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
3
asciidoctor/src/docs/asciidoc/test.adoc
Normal file
3
asciidoctor/src/docs/asciidoc/test.adoc
Normal file
@ -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#.
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.asciidoctor;
|
||||||
|
|
||||||
|
import static org.asciidoctor.Asciidoctor.Factory.create;
|
||||||
|
import static org.asciidoctor.OptionsBuilder.options;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.asciidoctor.Asciidoctor;
|
||||||
|
|
||||||
|
public class AsciidoctorDemo {
|
||||||
|
|
||||||
|
private final Asciidoctor asciidoctor;
|
||||||
|
|
||||||
|
AsciidoctorDemo() {
|
||||||
|
asciidoctor = create();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void generatePDFFromString(final String input) {
|
||||||
|
|
||||||
|
final Map<String, Object> options = options().inPlace(true)
|
||||||
|
.backend("pdf")
|
||||||
|
.asMap();
|
||||||
|
|
||||||
|
|
||||||
|
final String outfile = asciidoctor.convertFile(new File("sample.adoc"), options);
|
||||||
|
}
|
||||||
|
|
||||||
|
String generateHTMLFromString(final String input) {
|
||||||
|
return asciidoctor.convert("Hello _Baeldung_!", new HashMap<String, Object>());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.asciidoctor;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class AsciidoctorDemoTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenString_whenConverting_thenResultingHTMLCode() {
|
||||||
|
final AsciidoctorDemo asciidoctorDemo = new AsciidoctorDemo();
|
||||||
|
Assert.assertEquals(asciidoctorDemo.generateHTMLFromString("Hello _Baeldung_!"), "<div class=\"paragraph\">\n<p>Hello <em>Baeldung</em>!</p>\n</div>");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.java9.time;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class TimeApi {
|
||||||
|
|
||||||
|
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
|
||||||
|
List<Date> datesInRange = new ArrayList<Date>();
|
||||||
|
Calendar calendar = new GregorianCalendar();
|
||||||
|
calendar.setTime(startDate);
|
||||||
|
|
||||||
|
Calendar endCalendar = new GregorianCalendar();
|
||||||
|
endCalendar.setTime(endDate);
|
||||||
|
|
||||||
|
while (calendar.before(endCalendar)) {
|
||||||
|
Date result = calendar.getTime();
|
||||||
|
datesInRange.add(result);
|
||||||
|
calendar.add(Calendar.DATE, 1);
|
||||||
|
}
|
||||||
|
return datesInRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
|
||||||
|
long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
|
||||||
|
return IntStream.iterate(0, i -> i + 1)
|
||||||
|
.limit(numOfDaysBetween)
|
||||||
|
.mapToObj(i -> startDate.plusDays(i))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
|
||||||
|
return startDate.datesUntil(endDate).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.java9.time;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TimeApiTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() {
|
||||||
|
Date startDate = Calendar.getInstance().getTime();
|
||||||
|
Calendar endCalendar = Calendar.getInstance();
|
||||||
|
endCalendar.add(Calendar.DATE, 2);
|
||||||
|
Date endDate = endCalendar.getTime();
|
||||||
|
|
||||||
|
List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
Date date1 = calendar.getTime();
|
||||||
|
assertEquals(dates.get(0).getDay(), date1.getDay());
|
||||||
|
assertEquals(dates.get(0).getMonth(), date1.getMonth());
|
||||||
|
assertEquals(dates.get(0).getYear(), date1.getYear());
|
||||||
|
|
||||||
|
calendar.add(Calendar.DATE, 1);
|
||||||
|
Date date2 = calendar.getTime();
|
||||||
|
assertEquals(dates.get(1).getDay(), date2.getDay());
|
||||||
|
assertEquals(dates.get(1).getMonth(), date2.getMonth());
|
||||||
|
assertEquals(dates.get(1).getYear(), date2.getYear());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() {
|
||||||
|
LocalDate startDate = LocalDate.now();
|
||||||
|
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||||
|
|
||||||
|
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
assertEquals(dates.get(0), LocalDate.now());
|
||||||
|
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() {
|
||||||
|
LocalDate startDate = LocalDate.now();
|
||||||
|
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||||
|
|
||||||
|
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
assertEquals(dates.get(0), LocalDate.now());
|
||||||
|
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
3
core-java/.gitignore
vendored
3
core-java/.gitignore
vendored
@ -17,9 +17,10 @@
|
|||||||
|
|
||||||
# Files generated by integration tests
|
# Files generated by integration tests
|
||||||
*.txt
|
*.txt
|
||||||
|
backup-pom.xml
|
||||||
/bin/
|
/bin/
|
||||||
/temp
|
/temp
|
||||||
|
|
||||||
#IntelliJ specific
|
#IntelliJ specific
|
||||||
.idea
|
.idea/
|
||||||
*.iml
|
*.iml
|
@ -113,4 +113,21 @@
|
|||||||
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
||||||
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
||||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||||
|
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||||
|
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||||
|
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
|
||||||
|
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||||
|
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||||
|
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
|
||||||
|
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
|
||||||
|
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
|
||||||
|
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||||
|
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||||
|
- [Split a String in Java](http://www.baeldung.com/java-split-string)
|
||||||
|
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||||
|
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
|
||||||
|
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
|
||||||
|
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||||
|
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||||
|
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
|
||||||
|
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||||
|
@ -1,405 +1,404 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>core-java</artifactId>
|
<artifactId>core-java</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>core-java</name>
|
<name>core-java</name>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<!-- utils -->
|
<!-- utils -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sourceforge.collections</groupId>
|
<groupId>net.sourceforge.collections</groupId>
|
||||||
<artifactId>collections-generic</artifactId>
|
<artifactId>collections-generic</artifactId>
|
||||||
<version>${collections-generic.version}</version>
|
<version>${collections-generic.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>${guava.version}</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>${commons-io.version}</version>
|
<version>${commons-io.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-math3</artifactId>
|
<artifactId>commons-math3</artifactId>
|
||||||
<version>${commons-math3.version}</version>
|
<version>${commons-math3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.decimal4j</groupId>
|
<groupId>org.decimal4j</groupId>
|
||||||
<artifactId>decimal4j</artifactId>
|
<artifactId>decimal4j</artifactId>
|
||||||
<version>${decimal4j.version}</version>
|
<version>${decimal4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.bouncycastle</groupId>
|
<groupId>org.bouncycastle</groupId>
|
||||||
<artifactId>bcprov-jdk15on</artifactId>
|
<artifactId>bcprov-jdk15on</artifactId>
|
||||||
<version>${bouncycastle.version}</version>
|
<version>${bouncycastle.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.unix4j</groupId>
|
<groupId>org.unix4j</groupId>
|
||||||
<artifactId>unix4j-command</artifactId>
|
<artifactId>unix4j-command</artifactId>
|
||||||
<version>${unix4j.version}</version>
|
<version>${unix4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.googlecode.grep4j</groupId>
|
<groupId>com.googlecode.grep4j</groupId>
|
||||||
<artifactId>grep4j</artifactId>
|
<artifactId>grep4j</artifactId>
|
||||||
<version>${grep4j.version}</version>
|
<version>${grep4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>ch.qos.logback</groupId>
|
<groupId>ch.qos.logback</groupId>
|
||||||
<artifactId>logback-classic</artifactId>
|
<artifactId>logback-classic</artifactId>
|
||||||
<version>${logback.version}</version>
|
<version>${logback.version}</version>
|
||||||
<!-- <scope>runtime</scope> -->
|
<!-- <scope>runtime</scope> -->
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>log4j-over-slf4j</artifactId>
|
<artifactId>log4j-over-slf4j</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<version>${lombok.version}</version>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-all</artifactId>
|
<artifactId>hamcrest-all</artifactId>
|
||||||
<version>1.3</version>
|
<version>1.3</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>${junit.version}</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-core</artifactId>
|
<artifactId>hamcrest-core</artifactId>
|
||||||
<version>${org.hamcrest.version}</version>
|
<version>${org.hamcrest.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-library</artifactId>
|
<artifactId>hamcrest-library</artifactId>
|
||||||
<version>${org.hamcrest.version}</version>
|
<version>${org.hamcrest.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>${assertj.version}</version>
|
<version>${assertj.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
<version>${mockito.version}</version>
|
<version>${mockito.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.jayway.awaitility</groupId>
|
<groupId>com.jayway.awaitility</groupId>
|
||||||
<artifactId>awaitility</artifactId>
|
<artifactId>awaitility</artifactId>
|
||||||
<version>${avaitility.version}</version>
|
<version>${avaitility.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-codec</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
<artifactId>commons-codec</artifactId>
|
<artifactId>commons-codec</artifactId>
|
||||||
<version>${commons-codec.version}</version>
|
<version>${commons-codec.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.javamoney</groupId>
|
<groupId>org.javamoney</groupId>
|
||||||
<artifactId>moneta</artifactId>
|
<artifactId>moneta</artifactId>
|
||||||
<version>1.1</version>
|
<version>1.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.owasp.esapi</groupId>
|
<groupId>org.owasp.esapi</groupId>
|
||||||
<artifactId>esapi</artifactId>
|
<artifactId>esapi</artifactId>
|
||||||
<version>2.1.0.1</version>
|
<version>2.1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.sun.messaging.mq</groupId>
|
<groupId>com.sun.messaging.mq</groupId>
|
||||||
<artifactId>fscontext</artifactId>
|
<artifactId>fscontext</artifactId>
|
||||||
<version>${fscontext.version}</version>
|
<version>${fscontext.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<finalName>core-java</finalName>
|
<finalName>core-java</finalName>
|
||||||
<resources>
|
<resources>
|
||||||
<resource>
|
<resource>
|
||||||
<directory>src/main/resources</directory>
|
<directory>src/main/resources</directory>
|
||||||
<filtering>true</filtering>
|
<filtering>true</filtering>
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</resources>
|
||||||
|
|
||||||
<plugins>
|
<plugins>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
<testFailureIgnore>true</testFailureIgnore>
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-dependency-plugin</artifactId>
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>copy-dependencies</id>
|
<id>copy-dependencies</id>
|
||||||
<phase>prepare-package</phase>
|
<phase>prepare-package</phase>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>copy-dependencies</goal>
|
<goal>copy-dependencies</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
<configuration>
|
<configuration>
|
||||||
<archive>
|
<archive>
|
||||||
<manifest>
|
<manifest>
|
||||||
<addClasspath>true</addClasspath>
|
<addClasspath>true</addClasspath>
|
||||||
<classpathPrefix>libs/</classpathPrefix>
|
<classpathPrefix>libs/</classpathPrefix>
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</manifest>
|
</manifest>
|
||||||
</archive>
|
</archive>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<phase>package</phase>
|
<phase>package</phase>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>single</goal>
|
<goal>single</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||||
<archive>
|
<archive>
|
||||||
<manifest>
|
<manifest>
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</manifest>
|
</manifest>
|
||||||
</archive>
|
</archive>
|
||||||
<descriptorRefs>
|
<descriptorRefs>
|
||||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
</descriptorRefs>
|
</descriptorRefs>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>shade</goal>
|
<goal>shade</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||||
<transformers>
|
<transformers>
|
||||||
<transformer
|
<transformer
|
||||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
</transformers>
|
</transformers>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>com.jolira</groupId>
|
<groupId>com.jolira</groupId>
|
||||||
<artifactId>onejar-maven-plugin</artifactId>
|
<artifactId>onejar-maven-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<configuration>
|
<configuration>
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
<attachToBuild>true</attachToBuild>
|
<attachToBuild>true</attachToBuild>
|
||||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||||
</configuration>
|
</configuration>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>one-jar</goal>
|
<goal>one-jar</goal>
|
||||||
</goals>
|
</goals>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>repackage</goal>
|
<goal>repackage</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<classifier>spring-boot</classifier>
|
<classifier>spring-boot</classifier>
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>integration</id>
|
<id>integration</id>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<phase>integration-test</phase>
|
<phase>integration-test</phase>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>test</goal>
|
<goal>test</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
<includes>
|
<includes>
|
||||||
<include>**/*IntegrationTest.java</include>
|
<include>**/*IntegrationTest.java</include>
|
||||||
</includes>
|
</includes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
<configuration>
|
<configuration>
|
||||||
<systemPropertyVariables>
|
<systemPropertyVariables>
|
||||||
<test.mime>json</test.mime>
|
<test.mime>json</test.mime>
|
||||||
</systemPropertyVariables>
|
</systemPropertyVariables>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</profile>
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.8.5</jackson.version>
|
<jackson.version>2.8.5</jackson.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<logback.version>1.1.7</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>21.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<bouncycastle.version>1.55</bouncycastle.version>
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
<decimal4j.version>1.0.3</decimal4j.version>
|
<decimal4j.version>1.0.3</decimal4j.version>
|
||||||
<commons-io.version>2.5</commons-io.version>
|
<commons-io.version>2.5</commons-io.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
<unix4j.version>0.4</unix4j.version>
|
<unix4j.version>0.4</unix4j.version>
|
||||||
<grep4j.version>1.8.7</grep4j.version>
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
<lombok.version>1.16.12</lombok.version>
|
<lombok.version>1.16.12</lombok.version>
|
||||||
<fscontext.version>4.6-b01</fscontext.version>
|
<fscontext.version>4.6-b01</fscontext.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.baeldung.concurrent.cyclicbarrier;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.BrokenBarrierException;
|
||||||
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by cv on 24/6/17.
|
||||||
|
*/
|
||||||
|
public class CyclicBarrierDemo {
|
||||||
|
|
||||||
|
private CyclicBarrier cyclicBarrier;
|
||||||
|
private List<List<Integer>> partialResults = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
private Random random = new Random();
|
||||||
|
private int NUM_PARTIAL_RESULTS;
|
||||||
|
private int NUM_WORKERS;
|
||||||
|
|
||||||
|
|
||||||
|
public void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||||
|
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||||
|
NUM_WORKERS = numWorkers;
|
||||||
|
|
||||||
|
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
||||||
|
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
|
||||||
|
+ NUM_PARTIAL_RESULTS + " partial results each");
|
||||||
|
for (int i = 0; i < NUM_WORKERS; i++) {
|
||||||
|
Thread worker = new Thread(new NumberCruncherThread());
|
||||||
|
worker.setName("Thread " + i);
|
||||||
|
worker.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class NumberCruncherThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
List<Integer> partialResult = new ArrayList<>();
|
||||||
|
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
||||||
|
Integer num = random.nextInt(10);
|
||||||
|
System.out.println(thisThreadName
|
||||||
|
+ ": Crunching some numbers! Final result - " + num);
|
||||||
|
partialResult.add(num);
|
||||||
|
}
|
||||||
|
partialResults.add(partialResult);
|
||||||
|
try {
|
||||||
|
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||||
|
cyclicBarrier.await();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (BrokenBarrierException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AggregatorThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
|
||||||
|
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
||||||
|
int sum = 0;
|
||||||
|
for (List<Integer> threadResult : partialResults) {
|
||||||
|
System.out.print("Adding ");
|
||||||
|
for (Integer partialResult : threadResult) {
|
||||||
|
System.out.print(partialResult+" ");
|
||||||
|
sum += partialResult;
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
CyclicBarrierDemo play = new CyclicBarrierDemo();
|
||||||
|
play.runSimulation(5, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
|
||||||
|
public class DynamicGreeter implements Greeter {
|
||||||
|
|
||||||
|
private String greet;
|
||||||
|
|
||||||
|
public DynamicGreeter(String greet) {
|
||||||
|
this.greet = greet;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<? extends Annotation> annotationType() {
|
||||||
|
return DynamicGreeter.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String greet() {
|
||||||
|
return greet;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface Greeter {
|
||||||
|
|
||||||
|
public String greet() default "";
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class GreetingAnnotation {
|
||||||
|
|
||||||
|
private static final String ANNOTATION_METHOD = "annotationData";
|
||||||
|
private static final String ANNOTATION_FIELDS = "declaredAnnotations";
|
||||||
|
private static final String ANNOTATIONS = "annotations";
|
||||||
|
|
||||||
|
public static void main(String ...args) {
|
||||||
|
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
|
||||||
|
System.err.println("Hello there, " + greetings.greet() + " !!");
|
||||||
|
|
||||||
|
Greeter targetValue = new DynamicGreeter("Good evening");
|
||||||
|
//alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
|
||||||
|
alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
|
||||||
|
|
||||||
|
greetings = Greetings.class.getAnnotation(Greeter.class);
|
||||||
|
System.err.println("Hello there, " + greetings.greet() + " !!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
|
||||||
|
try {
|
||||||
|
Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
|
||||||
|
method.setAccessible(true);
|
||||||
|
|
||||||
|
Object annotationData = method.invoke(targetClass);
|
||||||
|
|
||||||
|
Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
|
||||||
|
annotations.setAccessible(true);
|
||||||
|
|
||||||
|
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
|
||||||
|
map.put(targetAnnotation, targetValue);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
|
||||||
|
try {
|
||||||
|
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
|
||||||
|
annotations.setAccessible(true);
|
||||||
|
|
||||||
|
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
|
||||||
|
System.out.println(map);
|
||||||
|
map.put(targetAnnotation, targetValue);
|
||||||
|
System.out.println(map);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
@Greeter(greet="Good morning")
|
||||||
|
public class Greetings {
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.javanetworking.url;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class URLDemo {
|
||||||
|
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||||
|
|
||||||
|
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||||
|
// parsed locator
|
||||||
|
String URLPROTOCOL = "https";
|
||||||
|
// final static String URLAUTHORITY = "wordpress.org:443";
|
||||||
|
String URLHOST = "wordpress.org";
|
||||||
|
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||||
|
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||||
|
// final static int URLPORT = 443;
|
||||||
|
int URLDEFAULTPORT = 443;
|
||||||
|
String URLQUERY = "replies=3";
|
||||||
|
String URLREFERENCE = "post-2278484";
|
||||||
|
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||||
|
|
||||||
|
URL url;
|
||||||
|
URLConnection urlConnection = null;
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
BufferedReader in = null;
|
||||||
|
String urlContent = "";
|
||||||
|
|
||||||
|
public String testURL(String urlString) throws IOException, IllegalArgumentException {
|
||||||
|
String urlStringCont = "";
|
||||||
|
// comment the if clause if experiment with URL
|
||||||
|
/*if (!URLSTRING.equals(urlString)) {
|
||||||
|
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
|
||||||
|
}*/
|
||||||
|
// creating URL object
|
||||||
|
url = new URL(urlString);
|
||||||
|
// get URL connection
|
||||||
|
urlConnection = url.openConnection();
|
||||||
|
connection = null;
|
||||||
|
// we can check, if connection is proper type
|
||||||
|
if (urlConnection instanceof HttpURLConnection) {
|
||||||
|
connection = (HttpURLConnection) urlConnection;
|
||||||
|
} else {
|
||||||
|
log.info("Please enter an HTTP URL");
|
||||||
|
throw new IOException("HTTP URL is not correct");
|
||||||
|
}
|
||||||
|
// we can check response code (200 OK is expected)
|
||||||
|
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||||
|
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
|
String current;
|
||||||
|
|
||||||
|
while ((current = in.readLine()) != null) {
|
||||||
|
urlStringCont += current;
|
||||||
|
}
|
||||||
|
return urlStringCont;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
URLDemo demo = new URLDemo();
|
||||||
|
String content = demo.testURL(demo.URLCOMPOUND);
|
||||||
|
demo.log.info(content);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.map.iteration;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MapIteration {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
MapIteration mapIteration = new MapIteration();
|
||||||
|
Map<String, Integer> map = new HashMap<>();
|
||||||
|
|
||||||
|
map.put("One", 1);
|
||||||
|
map.put("Three", 3);
|
||||||
|
map.put("Two", 2);
|
||||||
|
|
||||||
|
System.out.println("Iterating Keys of Map Using KeySet");
|
||||||
|
mapIteration.iterateKeys(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Entry Set");
|
||||||
|
mapIteration.iterateUsingEntrySet(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Iterator and Map Entry");
|
||||||
|
mapIteration.iterateUsingIteratorAndEntry(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using KeySet and For Each");
|
||||||
|
mapIteration.iterateUsingKeySetAndForeach(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Lambda Expression");
|
||||||
|
mapIteration.iterateUsingLambda(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Stream API");
|
||||||
|
mapIteration.iterateUsingStreamAPI(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingEntrySet(Map<String, Integer> map) {
|
||||||
|
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||||
|
System.out.println(entry.getKey() + ":" + entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingLambda(Map<String, Integer> map) {
|
||||||
|
map.forEach((k, v) -> System.out.println((k + ":" + v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||||
|
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Map.Entry<String, Integer> pair = iterator.next();
|
||||||
|
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
||||||
|
for (String key : map.keySet()) {
|
||||||
|
System.out.println(key + ":" + map.get(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||||
|
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateKeys(Map<String, Integer> map) {
|
||||||
|
for (String key : map.keySet()) {
|
||||||
|
System.out.println(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
public class FloatingPointArithmetic {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
double a = 13.22;
|
||||||
|
double b = 4.88;
|
||||||
|
double c = 21.45;
|
||||||
|
|
||||||
|
System.out.println("a = " + a);
|
||||||
|
System.out.println("b = " + b);
|
||||||
|
System.out.println("c = " + c);
|
||||||
|
|
||||||
|
double sum_ab = a + b;
|
||||||
|
System.out.println("a + b = " + sum_ab);
|
||||||
|
|
||||||
|
double abc = a + b + c;
|
||||||
|
System.out.println("a + b + c = " + abc);
|
||||||
|
|
||||||
|
double ab_c = sum_ab + c;
|
||||||
|
System.out.println("ab + c = " + ab_c);
|
||||||
|
|
||||||
|
double sum_ac = a + c;
|
||||||
|
System.out.println("a + c = " + sum_ac);
|
||||||
|
|
||||||
|
double acb = a + c + b;
|
||||||
|
System.out.println("a + c + b = " + acb);
|
||||||
|
|
||||||
|
double ac_b = sum_ac + b;
|
||||||
|
System.out.println("ac + b = " + ac_b);
|
||||||
|
|
||||||
|
double ab = 18.1;
|
||||||
|
double ac = 34.67;
|
||||||
|
double sum_ab_c = ab + c;
|
||||||
|
double sum_ac_b = ac + b;
|
||||||
|
System.out.println("ab + c = " + sum_ab_c);
|
||||||
|
System.out.println("ac + b = " + sum_ac_b);
|
||||||
|
|
||||||
|
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||||
|
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||||
|
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||||
|
|
||||||
|
BigDecimal def = d.add(e).add(f);
|
||||||
|
BigDecimal dfe = d.add(f).add(e);
|
||||||
|
|
||||||
|
System.out.println("d + e + f = " + def);
|
||||||
|
System.out.println("d + f + e = " + dfe);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,39 @@
|
|||||||
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.beans.Introspector;
|
||||||
|
import java.beans.PropertyDescriptor;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
class BaeldungReflectionUtils {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
|
||||||
|
|
||||||
|
static List<String> getNullPropertiesList(Customer customer) throws Exception {
|
||||||
|
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
|
||||||
|
|
||||||
|
return Arrays.stream(propDescArr)
|
||||||
|
.filter(nulls(customer))
|
||||||
|
.map(PropertyDescriptor::getName)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
|
||||||
|
return pd -> {
|
||||||
|
boolean result = false;
|
||||||
|
try {
|
||||||
|
Method getterMethod = pd.getReadMethod();
|
||||||
|
result = (getterMethod != null && getterMethod.invoke(customer) == null);
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOG.error("error invoking getter method");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
|
public class Customer {
|
||||||
|
|
||||||
|
private Integer id;
|
||||||
|
private String name;
|
||||||
|
private String emailId;
|
||||||
|
private Long phoneNumber;
|
||||||
|
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmailId() {
|
||||||
|
return emailId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmailId(String emailId) {
|
||||||
|
this.emailId = emailId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
|
||||||
|
phoneNumber + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
Customer(Integer id, String name, String emailId, Long phoneNumber) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.emailId = emailId;
|
||||||
|
this.phoneNumber = phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getPhoneNumber() {
|
||||||
|
return phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPhoneNumber(Long phoneNumber) {
|
||||||
|
this.phoneNumber = phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeuldung.serialization;
|
package com.baeldung.serialization;
|
||||||
|
|
||||||
public class Address {
|
public class Address {
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeuldung.serialization;
|
package com.baeldung.serialization;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.ObjectInputStream;
|
import java.io.ObjectInputStream;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeuldung.serialization;
|
package com.baeldung.serialization;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
public class Person implements Serializable {
|
public class Person implements Serializable {
|
||||||
|
9
core-java/src/main/java/log4j.properties
Normal file
9
core-java/src/main/java/log4j.properties
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Set root logger level to DEBUG and its only appender to A1.
|
||||||
|
log4j.rootLogger=DEBUG, A1
|
||||||
|
|
||||||
|
# A1 is set to be a ConsoleAppender.
|
||||||
|
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||||
|
|
||||||
|
# A1 uses PatternLayout.
|
||||||
|
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||||
|
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
|
@ -11,9 +11,9 @@ import java.util.stream.Stream;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class CompletableFutureUnitTest {
|
public class CompletableFutureLongRunningUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
@ -11,13 +11,12 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||||
|
|
||||||
public class LookupFSJNDITest {
|
public class LookupFSJNDIIntegrationTest {
|
||||||
LookupFSJNDI fsjndi;
|
LookupFSJNDI fsjndi;
|
||||||
File file;
|
|
||||||
InitialContext ctx = null;
|
InitialContext ctx = null;
|
||||||
final String FILENAME = "test.find";
|
final String FILENAME = "test.find";
|
||||||
|
|
||||||
public LookupFSJNDITest() {
|
public LookupFSJNDIIntegrationTest() {
|
||||||
try {
|
try {
|
||||||
fsjndi = new LookupFSJNDI();
|
fsjndi = new LookupFSJNDI();
|
||||||
} catch (NamingException e) {
|
} catch (NamingException e) {
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.java.currentmethod;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The class presents various ways of finding the name of currently executed method.
|
||||||
|
*/
|
||||||
|
public class CurrentlyExecutedMethodFinderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
|
||||||
|
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||||
|
assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenException_whenGetStackTrace_thenFindMethod() {
|
||||||
|
String methodName = new Exception().getStackTrace()[0].getMethodName();
|
||||||
|
assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
|
||||||
|
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
|
||||||
|
assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
|
||||||
|
String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
|
||||||
|
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
|
||||||
|
class Local {};
|
||||||
|
String methodName = Local.class.getEnclosingMethod().getName();
|
||||||
|
assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.javanetworking.url.test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.FixMethodOrder;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.baeldung.javanetworking.url.URLDemo;
|
||||||
|
|
||||||
|
@FixMethodOrder
|
||||||
|
public class URLDemoTest {
|
||||||
|
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||||
|
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||||
|
// parsed locator
|
||||||
|
static String URLPROTOCOL = "https";
|
||||||
|
String URLAUTHORITY = "wordpress.org:443";
|
||||||
|
static String URLHOST = "wordpress.org";
|
||||||
|
static String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||||
|
String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||||
|
int URLPORT = 443;
|
||||||
|
static int URLDEFAULTPORT = 443;
|
||||||
|
static String URLQUERY = "replies=3";
|
||||||
|
static String URLREFERENCE = "post-2278484";
|
||||||
|
static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||||
|
|
||||||
|
static URL url;
|
||||||
|
URLConnection urlConnection = null;
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
BufferedReader in = null;
|
||||||
|
String urlContent = "";
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException {
|
||||||
|
url = new URL(URLCOMPOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
// check parsed URL
|
||||||
|
@Test
|
||||||
|
public void givenURL_whenURLIsParsed_thenSuccess() {
|
||||||
|
assertNotNull("URL is null", url);
|
||||||
|
assertEquals("URL string is not equal", url.toString(), URLSTRING);
|
||||||
|
assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL);
|
||||||
|
assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY);
|
||||||
|
assertEquals("Host string is not equal", url.getHost(), URLHOST);
|
||||||
|
assertEquals("Path string is not equal", url.getPath(), URLPATH);
|
||||||
|
assertEquals("File string is not equal", url.getFile(), URLFILENAME);
|
||||||
|
assertEquals("Port number is not equal", url.getPort(), URLPORT);
|
||||||
|
assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT);
|
||||||
|
assertEquals("Query string is not equal", url.getQuery(), URLQUERY);
|
||||||
|
assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtain the content from location
|
||||||
|
@Test
|
||||||
|
public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException {
|
||||||
|
try {
|
||||||
|
urlConnection = url.openConnection();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
urlConnection = null;
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
assertNotNull("URL Connection is null", urlConnection);
|
||||||
|
|
||||||
|
connection = null;
|
||||||
|
assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection);
|
||||||
|
if (urlConnection instanceof HttpURLConnection) {
|
||||||
|
connection = (HttpURLConnection) urlConnection;
|
||||||
|
}
|
||||||
|
assertNotNull("Connection is null", connection);
|
||||||
|
|
||||||
|
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||||
|
|
||||||
|
try {
|
||||||
|
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
|
} catch (IOException ex) {
|
||||||
|
in = null;
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
assertNotNull("Input stream failed", in);
|
||||||
|
|
||||||
|
String current;
|
||||||
|
try {
|
||||||
|
while ((current = in.readLine()) != null) {
|
||||||
|
urlContent += current;
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
urlContent = null;
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
assertNotNull("Content is null", urlContent);
|
||||||
|
assertTrue("Content is empty", urlContent.length() > 0);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FloatingPointArithmeticTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||||
|
double a = 13.22;
|
||||||
|
double b = 4.88;
|
||||||
|
double c = 21.45;
|
||||||
|
double result = 39.55;
|
||||||
|
|
||||||
|
double abc = a + b + c;
|
||||||
|
double acb = a + c + b;
|
||||||
|
|
||||||
|
Assert.assertEquals(result, abc, 0);
|
||||||
|
Assert.assertNotEquals(result, acb, 0);
|
||||||
|
|
||||||
|
double ab = 18.1;
|
||||||
|
double ac = 34.67;
|
||||||
|
|
||||||
|
double ab_c = ab + c;
|
||||||
|
double ac_b = ac + b;
|
||||||
|
|
||||||
|
Assert.assertEquals(result, ab_c, 0);
|
||||||
|
Assert.assertNotEquals(result, ac_b, 0);
|
||||||
|
|
||||||
|
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||||
|
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||||
|
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||||
|
BigDecimal sum = new BigDecimal("39.55");
|
||||||
|
|
||||||
|
BigDecimal def = d.add(e).add(f);
|
||||||
|
BigDecimal dfe = d.add(f).add(e);
|
||||||
|
|
||||||
|
Assert.assertEquals(0, def.compareTo(sum));
|
||||||
|
Assert.assertEquals(0, dfe.compareTo(sum));
|
||||||
|
|
||||||
|
Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb))));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class BaeldungReflectionUtilsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
|
||||||
|
Customer customer = new Customer(1, "Himanshu", null, null);
|
||||||
|
|
||||||
|
List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
|
||||||
|
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
|
||||||
|
|
||||||
|
assertTrue(result.size() == expectedFieldNames.size());
|
||||||
|
assertTrue(result.containsAll(expectedFieldNames));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeuldung.serialization;
|
package com.baeldung.serialization;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.string;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
public class StringToCharStreamUnitTest {
|
||||||
|
|
||||||
|
private String testString = "Tests";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTestString_whenChars_thenReturnIntStream() {
|
||||||
|
assertThat(testString.chars(), instanceOf(IntStream.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTestString_whenCodePoints_thenReturnIntStream() {
|
||||||
|
assertThat(testString.codePoints(), instanceOf(IntStream.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTestString_whenCodePoints_thenShowOccurences() throws Exception {
|
||||||
|
Map<Character, Integer> map = testString.codePoints()
|
||||||
|
.mapToObj(c -> (char) c)
|
||||||
|
.filter(Character::isLetter)
|
||||||
|
.collect(Collectors.toMap(c -> c, c -> 1, Integer::sum));
|
||||||
|
|
||||||
|
System.out.println(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntStream_whenMapToObj_thenReturnCharacterStream() {
|
||||||
|
Stream<Character> characterStream = testString.chars()
|
||||||
|
.mapToObj(c -> (char) c);
|
||||||
|
Stream<Character> characterStream1 = testString.codePoints()
|
||||||
|
.mapToObj(c -> (char) c);
|
||||||
|
assertNotNull("IntStream returned by chars() did not map to Stream<Character>", characterStream);
|
||||||
|
assertNotNull("IntStream returned by codePoints() did not map to Stream<Character>", characterStream1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntStream_whenMapToObj_thenReturnStringStream() {
|
||||||
|
List<String> strings = testString.codePoints()
|
||||||
|
.mapToObj(c -> String.valueOf((char) c))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(strings.size(), 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -12,9 +12,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
import static junit.framework.TestCase.assertEquals;
|
import static junit.framework.TestCase.assertEquals;
|
||||||
|
|
||||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
public class SynchronousQueueUnitTest {
|
public class SynchronousQueueIntegrationTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueIntegrationTest.class);
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
3
drools/README.MD
Normal file
3
drools/README.MD
Normal file
@ -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)
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<http-component-version>4.4.6</http-component-version>
|
<http-component-version>4.4.6</http-component-version>
|
||||||
<drools-version>7.0.0.CR1</drools-version>
|
<drools-version>7.1.0.Beta2</drools-version>
|
||||||
<apache-poi-version>3.13</apache-poi-version>
|
<apache-poi-version>3.13</apache-poi-version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -1,10 +1,15 @@
|
|||||||
package com.baeldung.drools.config;
|
package com.baeldung.drools.config;
|
||||||
|
|
||||||
|
import org.drools.decisiontable.DecisionTableProviderImpl;
|
||||||
import org.kie.api.KieServices;
|
import org.kie.api.KieServices;
|
||||||
import org.kie.api.builder.*;
|
import org.kie.api.builder.*;
|
||||||
import org.kie.api.io.KieResources;
|
import org.kie.api.io.KieResources;
|
||||||
|
import org.kie.api.io.Resource;
|
||||||
import org.kie.api.runtime.KieContainer;
|
import org.kie.api.runtime.KieContainer;
|
||||||
import org.kie.api.runtime.KieSession;
|
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 org.kie.internal.io.ResourceFactory;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
@ -64,4 +69,39 @@ public class DroolsBeanFactory {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
44
drools/src/main/java/com/baeldung/drools/model/Customer.java
Normal file
44
drools/src/main/java/com/baeldung/drools/model/Customer.java
Normal file
@ -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;
|
||||||
|
}
|
||||||
|
}
|
BIN
drools/src/main/resources/com/baeldung/drools/rules/Discount.xls
Normal file
BIN
drools/src/main/resources/com/baeldung/drools/rules/Discount.xls
Normal file
Binary file not shown.
@ -17,37 +17,39 @@ public class ApplicantServiceIntegrationTest {
|
|||||||
private ApplicantService applicantService;
|
private ApplicantService applicantService;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup(){
|
public void setup() {
|
||||||
applicantService = new ApplicantService();
|
applicantService = new ApplicantService();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCriteriaMatching_ThenSuggestManagerRole() throws IOException {
|
public void whenCriteriaMatching_ThenSuggestManagerRole() throws IOException {
|
||||||
Applicant applicant=new Applicant("Davis",37,1600000.0,11);
|
Applicant applicant = new Applicant("Davis", 37, 1600000.0, 11);
|
||||||
SuggestedRole suggestedRole=new SuggestedRole();
|
SuggestedRole suggestedRole = new SuggestedRole();
|
||||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||||
assertEquals("Manager",suggestedRole.getRole());
|
assertEquals("Manager", suggestedRole.getRole());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole() throws IOException {
|
public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole() throws IOException {
|
||||||
Applicant applicant=new Applicant("John",37,1200000.0,8);
|
Applicant applicant = new Applicant("John", 37, 1200000.0, 8);
|
||||||
SuggestedRole suggestedRole=new SuggestedRole();
|
SuggestedRole suggestedRole = new SuggestedRole();
|
||||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||||
assertEquals("Senior developer",suggestedRole.getRole());
|
assertEquals("Senior developer", suggestedRole.getRole());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCriteriaMatching_ThenSuggestDeveloperRole() throws IOException {
|
public void whenCriteriaMatching_ThenSuggestDeveloperRole() throws IOException {
|
||||||
Applicant applicant=new Applicant("Davis",37,800000.0,3);
|
Applicant applicant = new Applicant("Davis", 37, 800000.0, 3);
|
||||||
SuggestedRole suggestedRole=new SuggestedRole();
|
SuggestedRole suggestedRole = new SuggestedRole();
|
||||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||||
assertEquals("Developer",suggestedRole.getRole());
|
assertEquals("Developer", suggestedRole.getRole());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCriteriaNotMatching_ThenNoRole() throws IOException {
|
public void whenCriteriaNotMatching_ThenNoRole() throws IOException {
|
||||||
Applicant applicant=new Applicant("John",37,1200000.0,5);
|
Applicant applicant = new Applicant("John", 37, 1200000.0, 5);
|
||||||
SuggestedRole suggestedRole=new SuggestedRole();
|
SuggestedRole suggestedRole = new SuggestedRole();
|
||||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||||
assertNull(suggestedRole.getRole());
|
assertNull(suggestedRole.getRole());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.drools.service;
|
|||||||
import com.baeldung.drools.model.Product;
|
import com.baeldung.drools.model.Product;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertEquals;
|
import static junit.framework.TestCase.assertEquals;
|
||||||
|
|
||||||
|
|
||||||
@ -11,22 +12,22 @@ public class ProductServiceIntegrationTest {
|
|||||||
private ProductService productService;
|
private ProductService productService;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup(){
|
public void setup() {
|
||||||
productService=new ProductService();
|
productService = new ProductService();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenProductTypeElectronic_ThenLabelBarcode(){
|
public void whenProductTypeElectronic_ThenLabelBarcode() {
|
||||||
Product product=new Product("Microwave","Electronic");
|
Product product = new Product("Microwave", "Electronic");
|
||||||
product=productService.applyLabelToProduct(product);
|
product = productService.applyLabelToProduct(product);
|
||||||
assertEquals("BarCode",product.getLabel());
|
assertEquals("BarCode", product.getLabel());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenProductTypeBook_ThenLabelIsbn(){
|
public void whenProductTypeBook_ThenLabelIsbn() {
|
||||||
Product product=new Product("AutoBiography","Book");
|
Product product = new Product("AutoBiography", "Book");
|
||||||
product=productService.applyLabelToProduct(product);
|
product = productService.applyLabelToProduct(product);
|
||||||
assertEquals("ISBN",product.getLabel());
|
assertEquals("ISBN", product.getLabel());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,3 +25,6 @@
|
|||||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||||
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
||||||
|
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
||||||
|
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||||
|
- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
|
||||||
|
4
guest/junit5-example/.gitignore
vendored
Normal file
4
guest/junit5-example/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
/target/
|
||||||
|
.settings/
|
||||||
|
.classpath
|
||||||
|
.project
|
68
guest/junit5-example/pom.xml
Normal file
68
guest/junit5-example/pom.xml
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>junit5-example</groupId>
|
||||||
|
<artifactId>junit5-example</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>5.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
|
<version>5.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
|
<version>4.12.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.195</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.8.2</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.19.1</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>1.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<configuration>
|
||||||
|
<properties>
|
||||||
|
<excludeTags>math</excludeTags>
|
||||||
|
</properties>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -0,0 +1,141 @@
|
|||||||
|
package com.stackify.daos;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
import com.stackify.models.User;
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
public class UserDAO {
|
||||||
|
|
||||||
|
private Logger logger = LogManager.getLogger(UserDAO.class);
|
||||||
|
|
||||||
|
public void createTable() {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String createQuery = "CREATE TABLE users(email varchar(50) primary key, name varchar(50))";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(createQuery);
|
||||||
|
|
||||||
|
pstmt.execute();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(insertQuery);
|
||||||
|
pstmt.setString(1, user.getEmail());
|
||||||
|
pstmt.setString(2, user.getName());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String updateQuery = "UPDATE users SET name=? WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(updateQuery);
|
||||||
|
pstmt.setString(1, user.getName());
|
||||||
|
pstmt.setString(2, user.getEmail());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
pstmt.setString(1, user.getEmail());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String email) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
pstmt.setString(1, email);
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public User findOne(String email) {
|
||||||
|
User user = null;
|
||||||
|
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String query = "SELECT * FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(query);
|
||||||
|
pstmt.setString(1, email);
|
||||||
|
|
||||||
|
ResultSet rs = pstmt.executeQuery();
|
||||||
|
while (rs.next()) {
|
||||||
|
user = new User();
|
||||||
|
user.setEmail(rs.getString("email"));
|
||||||
|
user.setName(rs.getString("name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<User> findAll() {
|
||||||
|
List<User> users = new ArrayList<>();
|
||||||
|
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String query = "SELECT * FROM users";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(query);
|
||||||
|
|
||||||
|
ResultSet rs = pstmt.executeQuery();
|
||||||
|
while (rs.next()) {
|
||||||
|
User user = new User();
|
||||||
|
user.setEmail(rs.getString("email"));
|
||||||
|
user.setName(rs.getString("name"));
|
||||||
|
users.add(user);
|
||||||
|
}
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteAll() {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package com.stackify.models;
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
private String email;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(String email, String name) {
|
||||||
|
super();
|
||||||
|
this.email = email;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||||
|
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
User other = (User) obj;
|
||||||
|
if (email == null) {
|
||||||
|
if (other.email != null)
|
||||||
|
return false;
|
||||||
|
} else if (!email.equals(other.email))
|
||||||
|
return false;
|
||||||
|
if (name == null) {
|
||||||
|
if (other.name != null)
|
||||||
|
return false;
|
||||||
|
} else if (!name.equals(other.name))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.stackify.test.conditions;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
@Target({ ElementType.METHOD })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@ExtendWith(DisabledOnEnvironmentCondition.class)
|
||||||
|
public @interface DisabledOnEnvironment {
|
||||||
|
String[] value();
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.test.conditions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
|
||||||
|
import org.junit.jupiter.api.extension.TestExecutionCondition;
|
||||||
|
import org.junit.jupiter.api.extension.TestExtensionContext;
|
||||||
|
import org.junit.platform.commons.support.AnnotationSupport;
|
||||||
|
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
public class DisabledOnEnvironmentCondition implements TestExecutionCondition {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ConditionEvaluationResult evaluate(TestExtensionContext context) {
|
||||||
|
Properties props = new Properties();
|
||||||
|
String env = "";
|
||||||
|
try {
|
||||||
|
props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
|
||||||
|
env = props.getProperty("env");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
|
||||||
|
if (disabled.isPresent()) {
|
||||||
|
String[] envs = disabled.get().value();
|
||||||
|
if (Arrays.asList(envs).contains(env)) {
|
||||||
|
return ConditionEvaluationResult.disabled("Disabled on environment " + env);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ConditionEvaluationResult.enabled("Enabled on environment "+env);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.utils;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
public class ConnectionUtil {
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
|
||||||
|
|
||||||
|
public static Connection getConnection() {
|
||||||
|
try {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties"));
|
||||||
|
Class.forName(props.getProperty("jdbc.driver"));
|
||||||
|
Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
|
||||||
|
return con;
|
||||||
|
}
|
||||||
|
|
||||||
|
catch (FileNotFoundException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (IOException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (ClassNotFoundException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
env=dev
|
@ -0,0 +1,4 @@
|
|||||||
|
jdbc.driver=org.h2.Driver
|
||||||
|
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
|
||||||
|
jdbc.user=
|
||||||
|
jdbc.password=
|
13
guest/junit5-example/src/main/resources/log4j2.xml
Normal file
13
guest/junit5-example/src/main/resources/log4j2.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="Console" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="info">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public interface DatabaseConnectionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
default void testDatabaseConnection() {
|
||||||
|
Connection con = ConnectionUtil.getConnection();
|
||||||
|
assertNotNull(con);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import org.junit.jupiter.api.DynamicTest;
|
||||||
|
import org.junit.jupiter.api.TestFactory;
|
||||||
|
import org.junit.jupiter.api.function.ThrowingConsumer;
|
||||||
|
|
||||||
|
import com.stackify.daos.UserDAO;
|
||||||
|
import com.stackify.models.User;
|
||||||
|
|
||||||
|
public class DynamicTests {
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
public Collection<DynamicTest> dynamicTestCollection() {
|
||||||
|
return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
public Stream<DynamicTest> dynamicUserTestCollection() {
|
||||||
|
List<User> inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana"));
|
||||||
|
|
||||||
|
Function<User, String> displayNameGenerator = (input) -> "Saving user: " + input;
|
||||||
|
|
||||||
|
UserDAO userDAO = new UserDAO();
|
||||||
|
ThrowingConsumer<User> testExecutor = (input) -> {
|
||||||
|
userDAO.add(input);
|
||||||
|
assertNotNull(userDAO.findOne(input.getEmail()));
|
||||||
|
};
|
||||||
|
|
||||||
|
return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
import org.junit.jupiter.api.RepetitionInfo;
|
||||||
|
|
||||||
|
public class IncrementTest {
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(IncrementTest.class);
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void increment() {
|
||||||
|
logger.info("Before Each Test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
|
||||||
|
public void test(RepetitionInfo info) {
|
||||||
|
assertTrue(1 == 1);
|
||||||
|
logger.info("Repetition #" + info.getCurrentRepetition());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import org.junit.jupiter.api.Tag;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
@Tag("math")
|
||||||
|
public class TaggedTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Tag("arithmetic")
|
||||||
|
public void testEquals() {
|
||||||
|
assertTrue(1 == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,155 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.TestInfo;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.stackify.daos.UserDAO;
|
||||||
|
import com.stackify.models.User;
|
||||||
|
|
||||||
|
import com.stackify.test.conditions.DisabledOnEnvironment;
|
||||||
|
|
||||||
|
public class UsersTest implements DatabaseConnectionTest {
|
||||||
|
|
||||||
|
private static UserDAO userDAO;
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(UsersTest.class);
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void addData() {
|
||||||
|
userDAO = new UserDAO();
|
||||||
|
userDAO.createTable();
|
||||||
|
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
User user2 = new User("ana@gmail.com", "Ana");
|
||||||
|
userDAO.add(user1);
|
||||||
|
userDAO.add(user2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Get Users")
|
||||||
|
public void testGetUsersNumber() {
|
||||||
|
assertEquals(2, userDAO.findAll().size());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Get Users")
|
||||||
|
public void testGetUsersNumberWithInfo(TestInfo testInfo) {
|
||||||
|
assertEquals(2, userDAO.findAll().size());
|
||||||
|
assertEquals("Test Get Users", testInfo.getDisplayName());
|
||||||
|
assertEquals(UsersTest.class, testInfo.getTestClass().get());
|
||||||
|
logger.info("Running test method:" + testInfo.getTestMethod().get().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetUser() {
|
||||||
|
User user = userDAO.findOne("john@gmail.com");
|
||||||
|
assertEquals("John", user.getName(), "User name:" + user.getName() + " incorrect");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testClassicAssertions() {
|
||||||
|
User user1 = userDAO.findOne("john@gmail.com");
|
||||||
|
User user2 = userDAO.findOne("john@yahoo.com");
|
||||||
|
|
||||||
|
assertNotNull(user1);
|
||||||
|
assertNull(user2);
|
||||||
|
|
||||||
|
user2 = new User("john@yahoo.com", "John");
|
||||||
|
assertEquals(user1.getName(), user2.getName(), "Names are not equal");
|
||||||
|
assertFalse(user1.getEmail().equals(user2.getEmail()), "Emails are equal");
|
||||||
|
assertNotSame(user1, user2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Disabled
|
||||||
|
public void testGroupedAssertions() {
|
||||||
|
User user = userDAO.findOne("john@gmail.com");
|
||||||
|
assertAll("user", () -> assertEquals("Johnson", user.getName()), () -> assertEquals("johnson@gmail.com", user.getEmail()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testIterableEquals() {
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
User user2 = new User("ana@gmail.com", "Ana");
|
||||||
|
|
||||||
|
List<User> users = new ArrayList<>();
|
||||||
|
users.add(user1);
|
||||||
|
users.add(user2);
|
||||||
|
|
||||||
|
assertIterableEquals(users, userDAO.findAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLinesMatch() {
|
||||||
|
List<String> expectedLines = Collections.singletonList("(.*)@(.*)");
|
||||||
|
List<String> emails = Arrays.asList("john@gmail.com");
|
||||||
|
assertLinesMatch(expectedLines, emails);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testThrows() {
|
||||||
|
User user = null;
|
||||||
|
Exception exception = assertThrows(NullPointerException.class, () -> user.getName());
|
||||||
|
logger.info(exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisabledOnEnvironment({ "dev", "prod")
|
||||||
|
void testFail() {
|
||||||
|
fail("this test fails");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAssumptions() {
|
||||||
|
List<User> users = userDAO.findAll();
|
||||||
|
assumeFalse(users == null);
|
||||||
|
assumeTrue(users.size() > 0);
|
||||||
|
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
|
||||||
|
assumingThat(users.contains(user1), () -> assertTrue(users.size() > 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = { "john@gmail.com", "ana@gmail.com" })
|
||||||
|
public void testParameterized(String email) {
|
||||||
|
assertNotNull(userDAO.findOne(email));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void removeData() {
|
||||||
|
userDAO.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class DeleteUsersTest {
|
||||||
|
@Test
|
||||||
|
public void addUser() {
|
||||||
|
User user = new User("bob@gmail.com", "Bob");
|
||||||
|
userDAO.add(user);
|
||||||
|
assertNotNull(userDAO.findOne("bob@gmail.com"));
|
||||||
|
|
||||||
|
userDAO.delete("bob@gmail.com");
|
||||||
|
assertNull(userDAO.findOne("bob@gmail.com"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
39
guest/memory-leaks/pom.xml
Normal file
39
guest/memory-leaks/pom.xml
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>memory-leaks</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources/</directory>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</resource>
|
||||||
|
<resource>
|
||||||
|
<directory>src/test/resources/</directory>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
11
guest/memory-leaks/src/test/java/com/baeldung/Key.java
Normal file
11
guest/memory-leaks/src/test/java/com/baeldung/Key.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
public class Key {
|
||||||
|
|
||||||
|
public static String key;
|
||||||
|
|
||||||
|
public Key(String key) {
|
||||||
|
Key.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,86 @@
|
|||||||
|
//package com.baeldung;
|
||||||
|
//
|
||||||
|
//import java.io.BufferedReader;
|
||||||
|
//import java.io.File;
|
||||||
|
//import java.io.IOException;
|
||||||
|
//import java.io.InputStream;
|
||||||
|
//import java.io.InputStreamReader;
|
||||||
|
//import java.net.URISyntaxException;
|
||||||
|
//import java.net.URL;
|
||||||
|
//import java.net.URLConnection;
|
||||||
|
//import java.nio.charset.StandardCharsets;
|
||||||
|
//import java.nio.file.Files;
|
||||||
|
//import java.nio.file.Paths;
|
||||||
|
//import java.nio.file.StandardOpenOption;
|
||||||
|
//import java.util.ArrayList;
|
||||||
|
//import java.util.Map;
|
||||||
|
//import java.util.Random;
|
||||||
|
//import java.util.Scanner;
|
||||||
|
//
|
||||||
|
//import org.junit.FixMethodOrder;
|
||||||
|
//import org.junit.Test;
|
||||||
|
//import org.junit.runner.RunWith;
|
||||||
|
//import org.junit.runners.JUnit4;
|
||||||
|
//import org.junit.runners.MethodSorters;
|
||||||
|
//
|
||||||
|
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
|
//@RunWith(JUnit4.class)
|
||||||
|
//public class MemoryLeaksTest {
|
||||||
|
|
||||||
|
// private Random random = new Random();
|
||||||
|
// public static final ArrayList<Double> list = new ArrayList<Double>(1000000);
|
||||||
|
//
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenStaticField_whenLotsOfOperations_thenMemoryLeak() throws InterruptedException {
|
||||||
|
// while (true) {
|
||||||
|
// int k = random.nextInt(100000);
|
||||||
|
// System.out.println(k);
|
||||||
|
// Thread.sleep(10000); //to allow GC do its job
|
||||||
|
// for (int i = 0; i < k; i++) {
|
||||||
|
// list.add(random.nextDouble());
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @SuppressWarnings({ "resource" })
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenLengthString_whenIntern_thenOutOfMemory() throws IOException {
|
||||||
|
// String str = new Scanner(new File("src/test/resources/large.txt"), "UTF-8").useDelimiter("\\A")
|
||||||
|
// .next();
|
||||||
|
// str.intern();
|
||||||
|
// System.out.println("Done");
|
||||||
|
// }
|
||||||
|
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenURL_whenUnclosedStream_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// String str = "";
|
||||||
|
// URLConnection conn = new URL("http://norvig.com/big.txt").openConnection();
|
||||||
|
// BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||||
|
// while (br.readLine() != null) {
|
||||||
|
// str += br.readLine();
|
||||||
|
// }
|
||||||
|
// Files.write(Paths.get("src/main/resources/"), str.getBytes(), StandardOpenOption.CREATE);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @SuppressWarnings("unused")
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenConnection_whenUnclosed_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// URL url = new URL("ftp://speedtest.tele2.net");
|
||||||
|
// URLConnection urlc = url.openConnection();
|
||||||
|
// InputStream is = urlc.getInputStream();
|
||||||
|
// String str = "";
|
||||||
|
// while (true) {
|
||||||
|
// str += is.toString()
|
||||||
|
// .intern();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// @Test(expected = OutOfMemoryError.class)
|
||||||
|
// public void givenMap_whenNoEqualsNoHashCodeMethods_thenOutOfMemory() throws IOException, URISyntaxException {
|
||||||
|
// Map<Object, Object> map = System.getProperties();
|
||||||
|
// while (true) {
|
||||||
|
// map.put(new Key("key"), "value");
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
5391
guest/memory-leaks/src/test/resources/large.txt
Normal file
5391
guest/memory-leaks/src/test/resources/large.txt
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,3 @@
|
|||||||
|
Manifest-Version: 1.0
|
||||||
|
Class-Path:
|
||||||
|
|
27
guest/webservices/rest-client/pom.xml
Normal file
27
guest/webservices/rest-client/pom.xml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.stackify</groupId>
|
||||||
|
<artifactId>rest-client</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<version>2.6</version>
|
||||||
|
<configuration>
|
||||||
|
<warSourceDirectory>WebContent</warSourceDirectory>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
57
guest/webservices/rest-client/rest-client/.angular-cli.json
Normal file
57
guest/webservices/rest-client/rest-client/.angular-cli.json
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
|
"project": {
|
||||||
|
"name": "rest-client"
|
||||||
|
},
|
||||||
|
"apps": [
|
||||||
|
{
|
||||||
|
"root": "src",
|
||||||
|
"outDir": "dist",
|
||||||
|
"assets": [
|
||||||
|
"assets",
|
||||||
|
"favicon.ico"
|
||||||
|
],
|
||||||
|
"index": "index.html",
|
||||||
|
"main": "main.ts",
|
||||||
|
"polyfills": "polyfills.ts",
|
||||||
|
"test": "test.ts",
|
||||||
|
"tsconfig": "tsconfig.app.json",
|
||||||
|
"testTsconfig": "tsconfig.spec.json",
|
||||||
|
"prefix": "app",
|
||||||
|
"styles": [
|
||||||
|
"styles.css"
|
||||||
|
],
|
||||||
|
"scripts": [],
|
||||||
|
"environmentSource": "environments/environment.ts",
|
||||||
|
"environments": {
|
||||||
|
"dev": "environments/environment.ts",
|
||||||
|
"prod": "environments/environment.prod.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"e2e": {
|
||||||
|
"protractor": {
|
||||||
|
"config": "./protractor.conf.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"lint": [
|
||||||
|
{
|
||||||
|
"project": "src/tsconfig.app.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"project": "src/tsconfig.spec.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"project": "e2e/tsconfig.e2e.json"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"test": {
|
||||||
|
"karma": {
|
||||||
|
"config": "./karma.conf.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"defaults": {
|
||||||
|
"styleExt": "css",
|
||||||
|
"component": {}
|
||||||
|
}
|
||||||
|
}
|
13
guest/webservices/rest-client/rest-client/.editorconfig
Normal file
13
guest/webservices/rest-client/rest-client/.editorconfig
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# Editor configuration, see http://editorconfig.org
|
||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
max_line_length = off
|
||||||
|
trim_trailing_whitespace = false
|
42
guest/webservices/rest-client/rest-client/.gitignore
vendored
Normal file
42
guest/webservices/rest-client/rest-client/.gitignore
vendored
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
# See http://help.github.com/ignore-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# compiled output
|
||||||
|
/dist
|
||||||
|
/tmp
|
||||||
|
/out-tsc
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
/.idea
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
|
||||||
|
# misc
|
||||||
|
/.sass-cache
|
||||||
|
/connect.lock
|
||||||
|
/coverage
|
||||||
|
/libpeerconnection.log
|
||||||
|
npm-debug.log
|
||||||
|
testem.log
|
||||||
|
/typings
|
||||||
|
|
||||||
|
# e2e
|
||||||
|
/e2e/*.js
|
||||||
|
/e2e/*.map
|
||||||
|
|
||||||
|
# System Files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
28
guest/webservices/rest-client/rest-client/README.md
Normal file
28
guest/webservices/rest-client/rest-client/README.md
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
# RestClient
|
||||||
|
|
||||||
|
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.1.3.
|
||||||
|
|
||||||
|
## Development server
|
||||||
|
|
||||||
|
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
|
||||||
|
|
||||||
|
## Code scaffolding
|
||||||
|
|
||||||
|
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|module`.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.
|
||||||
|
|
||||||
|
## Running unit tests
|
||||||
|
|
||||||
|
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
|
||||||
|
|
||||||
|
## Running end-to-end tests
|
||||||
|
|
||||||
|
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
|
||||||
|
Before running the tests make sure you are serving the app via `ng serve`.
|
||||||
|
|
||||||
|
## Further help
|
||||||
|
|
||||||
|
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
|
@ -0,0 +1,14 @@
|
|||||||
|
import { RestClientPage } from './app.po';
|
||||||
|
|
||||||
|
describe('rest-client App', () => {
|
||||||
|
let page: RestClientPage;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
page = new RestClientPage();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should display welcome message', () => {
|
||||||
|
page.navigateTo();
|
||||||
|
expect(page.getParagraphText()).toEqual('Welcome to app!!');
|
||||||
|
});
|
||||||
|
});
|
11
guest/webservices/rest-client/rest-client/e2e/app.po.ts
Normal file
11
guest/webservices/rest-client/rest-client/e2e/app.po.ts
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { browser, by, element } from 'protractor';
|
||||||
|
|
||||||
|
export class RestClientPage {
|
||||||
|
navigateTo() {
|
||||||
|
return browser.get('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
getParagraphText() {
|
||||||
|
return element(by.css('app-root h1')).getText();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"extends": "../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "../out-tsc/e2e",
|
||||||
|
"module": "commonjs",
|
||||||
|
"target": "es5",
|
||||||
|
"types": [
|
||||||
|
"jasmine",
|
||||||
|
"node"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
33
guest/webservices/rest-client/rest-client/karma.conf.js
Normal file
33
guest/webservices/rest-client/rest-client/karma.conf.js
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
// Karma configuration file, see link for more information
|
||||||
|
// https://karma-runner.github.io/0.13/config/configuration-file.html
|
||||||
|
|
||||||
|
module.exports = function (config) {
|
||||||
|
config.set({
|
||||||
|
basePath: '',
|
||||||
|
frameworks: ['jasmine', '@angular/cli'],
|
||||||
|
plugins: [
|
||||||
|
require('karma-jasmine'),
|
||||||
|
require('karma-chrome-launcher'),
|
||||||
|
require('karma-jasmine-html-reporter'),
|
||||||
|
require('karma-coverage-istanbul-reporter'),
|
||||||
|
require('@angular/cli/plugins/karma')
|
||||||
|
],
|
||||||
|
client:{
|
||||||
|
clearContext: false // leave Jasmine Spec Runner output visible in browser
|
||||||
|
},
|
||||||
|
coverageIstanbulReporter: {
|
||||||
|
reports: [ 'html', 'lcovonly' ],
|
||||||
|
fixWebpackSourcePaths: true
|
||||||
|
},
|
||||||
|
angularCli: {
|
||||||
|
environment: 'dev'
|
||||||
|
},
|
||||||
|
reporters: ['progress', 'kjhtml'],
|
||||||
|
port: 9876,
|
||||||
|
colors: true,
|
||||||
|
logLevel: config.LOG_INFO,
|
||||||
|
autoWatch: true,
|
||||||
|
browsers: ['Chrome'],
|
||||||
|
singleRun: false
|
||||||
|
});
|
||||||
|
};
|
48
guest/webservices/rest-client/rest-client/package.json
Normal file
48
guest/webservices/rest-client/rest-client/package.json
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"name": "rest-client",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"license": "MIT",
|
||||||
|
"scripts": {
|
||||||
|
"ng": "ng",
|
||||||
|
"start": "ng serve",
|
||||||
|
"build": "ng build",
|
||||||
|
"test": "ng test",
|
||||||
|
"lint": "ng lint",
|
||||||
|
"e2e": "ng e2e"
|
||||||
|
},
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@angular/animations": "^4.0.0",
|
||||||
|
"@angular/common": "^4.0.0",
|
||||||
|
"@angular/compiler": "^4.0.0",
|
||||||
|
"@angular/core": "^4.0.0",
|
||||||
|
"@angular/forms": "^4.0.0",
|
||||||
|
"@angular/http": "^4.0.0",
|
||||||
|
"@angular/platform-browser": "^4.0.0",
|
||||||
|
"@angular/platform-browser-dynamic": "^4.0.0",
|
||||||
|
"@angular/router": "^4.0.0",
|
||||||
|
"core-js": "^2.4.1",
|
||||||
|
"rxjs": "^5.1.0",
|
||||||
|
"zone.js": "^0.8.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@angular/cli": "1.1.3",
|
||||||
|
"@angular/compiler-cli": "^4.0.0",
|
||||||
|
"@angular/language-service": "^4.0.0",
|
||||||
|
"@types/jasmine": "2.5.45",
|
||||||
|
"@types/node": "~6.0.60",
|
||||||
|
"codelyzer": "~3.0.1",
|
||||||
|
"jasmine-core": "~2.6.2",
|
||||||
|
"jasmine-spec-reporter": "~4.1.0",
|
||||||
|
"karma": "~1.7.0",
|
||||||
|
"karma-chrome-launcher": "~2.1.1",
|
||||||
|
"karma-cli": "~1.0.1",
|
||||||
|
"karma-coverage-istanbul-reporter": "^1.2.1",
|
||||||
|
"karma-jasmine": "~1.1.0",
|
||||||
|
"karma-jasmine-html-reporter": "^0.2.2",
|
||||||
|
"protractor": "~5.1.2",
|
||||||
|
"ts-node": "~3.0.4",
|
||||||
|
"tslint": "~5.3.2",
|
||||||
|
"typescript": "~2.3.3"
|
||||||
|
}
|
||||||
|
}
|
28
guest/webservices/rest-client/rest-client/protractor.conf.js
Normal file
28
guest/webservices/rest-client/rest-client/protractor.conf.js
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
// Protractor configuration file, see link for more information
|
||||||
|
// https://github.com/angular/protractor/blob/master/lib/config.ts
|
||||||
|
|
||||||
|
const { SpecReporter } = require('jasmine-spec-reporter');
|
||||||
|
|
||||||
|
exports.config = {
|
||||||
|
allScriptsTimeout: 11000,
|
||||||
|
specs: [
|
||||||
|
'./e2e/**/*.e2e-spec.ts'
|
||||||
|
],
|
||||||
|
capabilities: {
|
||||||
|
'browserName': 'chrome'
|
||||||
|
},
|
||||||
|
directConnect: true,
|
||||||
|
baseUrl: 'http://localhost:4200/',
|
||||||
|
framework: 'jasmine',
|
||||||
|
jasmineNodeOpts: {
|
||||||
|
showColors: true,
|
||||||
|
defaultTimeoutInterval: 30000,
|
||||||
|
print: function() {}
|
||||||
|
},
|
||||||
|
onPrepare() {
|
||||||
|
require('ts-node').register({
|
||||||
|
project: 'e2e/tsconfig.e2e.json'
|
||||||
|
});
|
||||||
|
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
|
||||||
|
}
|
||||||
|
};
|
@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Angular QuickStart</title>
|
||||||
|
<base href="/">
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<users-page>loading users component</users-page>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -0,0 +1,32 @@
|
|||||||
|
import { TestBed, async } from '@angular/core/testing';
|
||||||
|
|
||||||
|
import { AppComponent } from './app.component';
|
||||||
|
|
||||||
|
describe('AppComponent', () => {
|
||||||
|
beforeEach(async(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
declarations: [
|
||||||
|
AppComponent
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
}));
|
||||||
|
|
||||||
|
it('should create the app', async(() => {
|
||||||
|
const fixture = TestBed.createComponent(AppComponent);
|
||||||
|
const app = fixture.debugElement.componentInstance;
|
||||||
|
expect(app).toBeTruthy();
|
||||||
|
}));
|
||||||
|
|
||||||
|
it(`should have as title 'app'`, async(() => {
|
||||||
|
const fixture = TestBed.createComponent(AppComponent);
|
||||||
|
const app = fixture.debugElement.componentInstance;
|
||||||
|
expect(app.title).toEqual('app');
|
||||||
|
}));
|
||||||
|
|
||||||
|
it('should render title in a h1 tag', async(() => {
|
||||||
|
const fixture = TestBed.createComponent(AppComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const compiled = fixture.debugElement.nativeElement;
|
||||||
|
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!!');
|
||||||
|
}));
|
||||||
|
});
|
@ -0,0 +1,10 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-root',
|
||||||
|
templateUrl: './app.component.html',
|
||||||
|
styleUrls: ['./app.component.css']
|
||||||
|
})
|
||||||
|
export class AppComponent {
|
||||||
|
title = 'app';
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
import { BrowserModule } from '@angular/platform-browser';
|
||||||
|
import { NgModule } from '@angular/core';
|
||||||
|
import { HttpModule } from '@angular/http';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
|
||||||
|
import { AppComponent } from './app.component';
|
||||||
|
import { UsersComponent } from './users.component';
|
||||||
|
import { RouterModule } from '@angular/router';
|
||||||
|
|
||||||
|
@NgModule({
|
||||||
|
declarations: [
|
||||||
|
AppComponent,
|
||||||
|
UsersComponent
|
||||||
|
],
|
||||||
|
imports: [
|
||||||
|
BrowserModule,
|
||||||
|
HttpModule,
|
||||||
|
FormsModule,
|
||||||
|
RouterModule.forRoot([
|
||||||
|
{ path: '', component: AppComponent },
|
||||||
|
{ path: 'users', component: UsersComponent }])],
|
||||||
|
providers: [],
|
||||||
|
bootstrap: [AppComponent]
|
||||||
|
})
|
||||||
|
export class AppModule { }
|
@ -0,0 +1,36 @@
|
|||||||
|
import {Injectable} from '@angular/core';
|
||||||
|
import { Http, Response, Headers, RequestOptions } from '@angular/http';
|
||||||
|
import 'rxjs/add/operator/map';
|
||||||
|
|
||||||
|
export class User {
|
||||||
|
constructor(
|
||||||
|
public email: string,
|
||||||
|
public name: string) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UserService {
|
||||||
|
constructor(
|
||||||
|
private _http: Http){}
|
||||||
|
|
||||||
|
url = 'http://localhost:8080/rest-server/users';
|
||||||
|
|
||||||
|
addUser(user){
|
||||||
|
let headers = new Headers({'Content-Type': 'application/json'});
|
||||||
|
let options = new RequestOptions({ headers: headers});
|
||||||
|
|
||||||
|
return this._http.post(this.url, JSON.stringify(user), options)
|
||||||
|
.map(
|
||||||
|
(_response: Response) => {
|
||||||
|
return _response;
|
||||||
|
},
|
||||||
|
err => alert('Error adding user'));
|
||||||
|
}
|
||||||
|
|
||||||
|
getUsers() {
|
||||||
|
return this._http.get(this.url)
|
||||||
|
.map((_response: Response) => {
|
||||||
|
return _response.json();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
<form>
|
||||||
|
Email: <input type="text" [(ngModel)]="user.email" name="email"/><br />
|
||||||
|
Name: <input type="text" [(ngModel)]="user.name" name="name"/><br />
|
||||||
|
<input type="submit" (click)="addUser()" value="Add User"/>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<table>
|
||||||
|
<tr *ngFor="let user of res" >
|
||||||
|
<td>{{user.email}}
|
||||||
|
</td>
|
||||||
|
<td>{{user.name}}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
@ -0,0 +1,39 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import {UserService, User} from './app.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'users-page',
|
||||||
|
providers: [UserService],
|
||||||
|
templateUrl: './users.component.html',
|
||||||
|
styleUrls: ['./app.component.css']
|
||||||
|
})
|
||||||
|
export class UsersComponent {
|
||||||
|
title = 'Users';
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private _service:UserService){}
|
||||||
|
|
||||||
|
public user = {email: "", name: ""};
|
||||||
|
public res=[];
|
||||||
|
|
||||||
|
addUser() {
|
||||||
|
this._service.addUser(this.user)
|
||||||
|
.subscribe( () => this.getUsers());
|
||||||
|
}
|
||||||
|
|
||||||
|
getUsers() {
|
||||||
|
this._service.getUsers()
|
||||||
|
.subscribe(
|
||||||
|
users => {
|
||||||
|
this.res=[];
|
||||||
|
users.forEach(usr => {
|
||||||
|
this.res.push(
|
||||||
|
new User(
|
||||||
|
usr.email,
|
||||||
|
usr.name
|
||||||
|
)
|
||||||
|
)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user