updated local repo with upstream
This commit is contained in:
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
/**
|
||||
* Finite state machine.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
/**
|
||||
* Default implementation of a finite state machine.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
|
||||
/**
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
/**
|
||||
* State. Part of a finite state machine.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.automata;
|
||||
package com.baeldung.algorithms.automata;
|
||||
|
||||
/**
|
||||
* Transition in a finite State machine.
|
||||
+109
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package algorithms;
|
||||
|
||||
import com.baeldung.automata.*;
|
||||
import com.baeldung.algorithms.automata.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,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
|
||||
@@ -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,3 @@
|
||||
### Relevant Articles:
|
||||
[Introduction to Drools](http://www.baeldung.com/drools)
|
||||
[Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
|
||||
<properties>
|
||||
<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>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
package com.baeldung.drools.config;
|
||||
|
||||
import org.drools.decisiontable.DecisionTableProviderImpl;
|
||||
import org.kie.api.KieServices;
|
||||
import org.kie.api.builder.*;
|
||||
import org.kie.api.io.KieResources;
|
||||
import org.kie.api.io.Resource;
|
||||
import org.kie.api.runtime.KieContainer;
|
||||
import org.kie.api.runtime.KieSession;
|
||||
import org.kie.internal.builder.DecisionTableConfiguration;
|
||||
import org.kie.internal.builder.DecisionTableInputType;
|
||||
import org.kie.internal.builder.KnowledgeBuilderFactory;
|
||||
import org.kie.internal.io.ResourceFactory;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
@@ -64,4 +69,39 @@ public class DroolsBeanFactory {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
+18
-16
@@ -17,37 +17,39 @@ public class ApplicantServiceIntegrationTest {
|
||||
private ApplicantService applicantService;
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
public void setup() {
|
||||
applicantService = new ApplicantService();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCriteriaMatching_ThenSuggestManagerRole() throws IOException {
|
||||
Applicant applicant=new Applicant("Davis",37,1600000.0,11);
|
||||
SuggestedRole suggestedRole=new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
||||
assertEquals("Manager",suggestedRole.getRole());
|
||||
Applicant applicant = new Applicant("Davis", 37, 1600000.0, 11);
|
||||
SuggestedRole suggestedRole = new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||
assertEquals("Manager", suggestedRole.getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole() throws IOException {
|
||||
Applicant applicant=new Applicant("John",37,1200000.0,8);
|
||||
SuggestedRole suggestedRole=new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
||||
assertEquals("Senior developer",suggestedRole.getRole());
|
||||
Applicant applicant = new Applicant("John", 37, 1200000.0, 8);
|
||||
SuggestedRole suggestedRole = new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||
assertEquals("Senior developer", suggestedRole.getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCriteriaMatching_ThenSuggestDeveloperRole() throws IOException {
|
||||
Applicant applicant=new Applicant("Davis",37,800000.0,3);
|
||||
SuggestedRole suggestedRole=new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
||||
assertEquals("Developer",suggestedRole.getRole());
|
||||
Applicant applicant = new Applicant("Davis", 37, 800000.0, 3);
|
||||
SuggestedRole suggestedRole = new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||
assertEquals("Developer", suggestedRole.getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCriteriaNotMatching_ThenNoRole() throws IOException {
|
||||
Applicant applicant=new Applicant("John",37,1200000.0,5);
|
||||
SuggestedRole suggestedRole=new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant,suggestedRole);
|
||||
Applicant applicant = new Applicant("John", 37, 1200000.0, 5);
|
||||
SuggestedRole suggestedRole = new SuggestedRole();
|
||||
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
|
||||
assertNull(suggestedRole.getRole());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+11
-10
@@ -3,6 +3,7 @@ package com.baeldung.drools.service;
|
||||
import com.baeldung.drools.model.Product;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
|
||||
@@ -11,22 +12,22 @@ public class ProductServiceIntegrationTest {
|
||||
private ProductService productService;
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
productService=new ProductService();
|
||||
public void setup() {
|
||||
productService = new ProductService();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenProductTypeElectronic_ThenLabelBarcode(){
|
||||
Product product=new Product("Microwave","Electronic");
|
||||
product=productService.applyLabelToProduct(product);
|
||||
assertEquals("BarCode",product.getLabel());
|
||||
public void whenProductTypeElectronic_ThenLabelBarcode() {
|
||||
Product product = new Product("Microwave", "Electronic");
|
||||
product = productService.applyLabelToProduct(product);
|
||||
assertEquals("BarCode", product.getLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProductTypeBook_ThenLabelIsbn(){
|
||||
Product product=new Product("AutoBiography","Book");
|
||||
product=productService.applyLabelToProduct(product);
|
||||
assertEquals("ISBN",product.getLabel());
|
||||
public void whenProductTypeBook_ThenLabelIsbn() {
|
||||
Product product = new Product("AutoBiography", "Book");
|
||||
product = productService.applyLabelToProduct(product);
|
||||
assertEquals("ISBN", product.getLabel());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
||||
@@ -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>
|
||||
@@ -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": {}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user