Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
32d8694a52
1
.gitignore
vendored
1
.gitignore
vendored
@ -43,3 +43,4 @@ spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
||||
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
||||
*.springBeans
|
||||
|
||||
20171220-JMeter.csv
|
||||
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.algorithms.maze.solver;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class BFSMazeSolver {
|
||||
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
|
||||
|
||||
public List<Coordinate> solve(Maze maze) {
|
||||
LinkedList<Coordinate> nextToVisit = new LinkedList<>();
|
||||
Coordinate start = maze.getEntry();
|
||||
nextToVisit.add(start);
|
||||
|
||||
while (!nextToVisit.isEmpty()) {
|
||||
Coordinate cur = nextToVisit.remove();
|
||||
|
||||
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (maze.isWall(cur.getX(), cur.getY())) {
|
||||
maze.setVisited(cur.getX(), cur.getY(), true);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (maze.isExit(cur.getX(), cur.getY())) {
|
||||
return backtrackPath(cur);
|
||||
}
|
||||
|
||||
for (int[] direction : DIRECTIONS) {
|
||||
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
|
||||
nextToVisit.add(coordinate);
|
||||
maze.setVisited(cur.getX(), cur.getY(), true);
|
||||
}
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private List<Coordinate> backtrackPath(Coordinate cur) {
|
||||
List<Coordinate> path = new ArrayList<>();
|
||||
Coordinate iter = cur;
|
||||
|
||||
while (iter != null) {
|
||||
path.add(iter);
|
||||
iter = iter.parent;
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.algorithms.maze.solver;
|
||||
|
||||
public class Coordinate {
|
||||
int x;
|
||||
int y;
|
||||
Coordinate parent;
|
||||
|
||||
public Coordinate(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.parent = null;
|
||||
}
|
||||
|
||||
public Coordinate(int x, int y, Coordinate parent) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
Coordinate getParent() {
|
||||
return parent;
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.algorithms.maze.solver;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class DFSMazeSolver {
|
||||
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
|
||||
|
||||
public List<Coordinate> solve(Maze maze) {
|
||||
List<Coordinate> path = new ArrayList<>();
|
||||
if (explore(maze, maze.getEntry()
|
||||
.getX(),
|
||||
maze.getEntry()
|
||||
.getY(),
|
||||
path)) {
|
||||
return path;
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private boolean explore(Maze maze, int row, int col, List<Coordinate> path) {
|
||||
if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
path.add(new Coordinate(row, col));
|
||||
maze.setVisited(row, col, true);
|
||||
|
||||
if (maze.isExit(row, col)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (int[] direction : DIRECTIONS) {
|
||||
Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]);
|
||||
if (explore(maze, coordinate.getX(), coordinate.getY(), path)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
path.remove(path.size() - 1);
|
||||
return false;
|
||||
}
|
||||
|
||||
private Coordinate getNextCoordinate(int row, int col, int i, int j) {
|
||||
return new Coordinate(row + i, col + j);
|
||||
}
|
||||
}
|
@ -0,0 +1,141 @@
|
||||
package com.baeldung.algorithms.maze.solver;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Maze {
|
||||
private static final int ROAD = 0;
|
||||
private static final int WALL = 1;
|
||||
private static final int START = 2;
|
||||
private static final int EXIT = 3;
|
||||
private static final int PATH = 4;
|
||||
|
||||
private int[][] maze;
|
||||
private boolean[][] visited;
|
||||
private Coordinate start;
|
||||
private Coordinate end;
|
||||
|
||||
public Maze(File maze) throws FileNotFoundException {
|
||||
String fileText = "";
|
||||
try (Scanner input = new Scanner(maze)) {
|
||||
while (input.hasNextLine()) {
|
||||
fileText += input.nextLine() + "\n";
|
||||
}
|
||||
}
|
||||
initializeMaze(fileText);
|
||||
}
|
||||
|
||||
private void initializeMaze(String text) {
|
||||
if (text == null || (text = text.trim()).length() == 0) {
|
||||
throw new IllegalArgumentException("empty lines data");
|
||||
}
|
||||
|
||||
String[] lines = text.split("[\r]?\n");
|
||||
maze = new int[lines.length][lines[0].length()];
|
||||
visited = new boolean[lines.length][lines[0].length()];
|
||||
|
||||
for (int row = 0; row < getHeight(); row++) {
|
||||
if (lines[row].length() != getWidth()) {
|
||||
throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")");
|
||||
}
|
||||
|
||||
for (int col = 0; col < getWidth(); col++) {
|
||||
if (lines[row].charAt(col) == '#')
|
||||
maze[row][col] = WALL;
|
||||
else if (lines[row].charAt(col) == 'S') {
|
||||
maze[row][col] = START;
|
||||
start = new Coordinate(row, col);
|
||||
} else if (lines[row].charAt(col) == 'E') {
|
||||
maze[row][col] = EXIT;
|
||||
end = new Coordinate(row, col);
|
||||
} else
|
||||
maze[row][col] = ROAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return maze.length;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return maze[0].length;
|
||||
}
|
||||
|
||||
public Coordinate getEntry() {
|
||||
return start;
|
||||
}
|
||||
|
||||
public Coordinate getExit() {
|
||||
return end;
|
||||
}
|
||||
|
||||
public boolean isExit(int x, int y) {
|
||||
return x == end.getX() && y == end.getY();
|
||||
}
|
||||
|
||||
public boolean isStart(int x, int y) {
|
||||
return x == start.getX() && y == start.getY();
|
||||
}
|
||||
|
||||
public boolean isExplored(int row, int col) {
|
||||
return visited[row][col];
|
||||
}
|
||||
|
||||
public boolean isWall(int row, int col) {
|
||||
return maze[row][col] == WALL;
|
||||
}
|
||||
|
||||
public void setVisited(int row, int col, boolean value) {
|
||||
visited[row][col] = value;
|
||||
}
|
||||
|
||||
public boolean isValidLocation(int row, int col) {
|
||||
if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void printPath(List<Coordinate> path) {
|
||||
int[][] tempMaze = Arrays.stream(maze)
|
||||
.map(int[]::clone)
|
||||
.toArray(int[][]::new);
|
||||
for (Coordinate coordinate : path) {
|
||||
if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) {
|
||||
continue;
|
||||
}
|
||||
tempMaze[coordinate.getX()][coordinate.getY()] = PATH;
|
||||
}
|
||||
System.out.println(toString(tempMaze));
|
||||
}
|
||||
|
||||
public String toString(int[][] maze) {
|
||||
StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1));
|
||||
for (int row = 0; row < getHeight(); row++) {
|
||||
for (int col = 0; col < getWidth(); col++) {
|
||||
if (maze[row][col] == ROAD) {
|
||||
result.append(' ');
|
||||
} else if (maze[row][col] == WALL) {
|
||||
result.append('#');
|
||||
} else if (maze[row][col] == START) {
|
||||
result.append('S');
|
||||
} else if (maze[row][col] == EXIT) {
|
||||
result.append('E');
|
||||
} else {
|
||||
result.append('.');
|
||||
}
|
||||
}
|
||||
result.append('\n');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
for (int i = 0; i < visited.length; i++)
|
||||
Arrays.fill(visited[i], false);
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.maze.solver;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
public class MazeDriver {
|
||||
public static void main(String[] args) throws Exception {
|
||||
File maze1 = new File("src/main/resources/maze/maze1.txt");
|
||||
File maze2 = new File("src/main/resources/maze/maze2.txt");
|
||||
|
||||
execute(maze1);
|
||||
execute(maze2);
|
||||
}
|
||||
|
||||
private static void execute(File file) throws Exception {
|
||||
Maze maze = new Maze(file);
|
||||
dfs(maze);
|
||||
bfs(maze);
|
||||
}
|
||||
|
||||
private static void bfs(Maze maze) {
|
||||
BFSMazeSolver bfs = new BFSMazeSolver();
|
||||
List<Coordinate> path = bfs.solve(maze);
|
||||
maze.printPath(path);
|
||||
maze.reset();
|
||||
}
|
||||
|
||||
private static void dfs(Maze maze) {
|
||||
DFSMazeSolver dfs = new DFSMazeSolver();
|
||||
List<Coordinate> path = dfs.solve(maze);
|
||||
maze.printPath(path);
|
||||
maze.reset();
|
||||
}
|
||||
}
|
@ -40,15 +40,15 @@ public class BacktrackingAlgorithm {
|
||||
}
|
||||
|
||||
private boolean solve(int[][] board) {
|
||||
for (int r = BOARD_START_INDEX; r < BOARD_SIZE; r++) {
|
||||
for (int c = BOARD_START_INDEX; c < BOARD_SIZE; c++) {
|
||||
if (board[r][c] == NO_VALUE) {
|
||||
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
|
||||
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
|
||||
if (board[row][column] == NO_VALUE) {
|
||||
for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
|
||||
board[r][c] = k;
|
||||
if (isValid(board, r, c) && solve(board)) {
|
||||
board[row][column] = k;
|
||||
if (isValid(board, row, column) && solve(board)) {
|
||||
return true;
|
||||
}
|
||||
board[r][c] = NO_VALUE;
|
||||
board[row][column] = NO_VALUE;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@ -57,44 +57,44 @@ public class BacktrackingAlgorithm {
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isValid(int[][] board, int r, int c) {
|
||||
return rowConstraint(board, r) &&
|
||||
columnConstraint(board, c) &&
|
||||
subsectionConstraint(board, r, c);
|
||||
private boolean isValid(int[][] board, int row, int column) {
|
||||
return rowConstraint(board, row) &&
|
||||
columnConstraint(board, column) &&
|
||||
subsectionConstraint(board, row, column);
|
||||
}
|
||||
|
||||
private boolean subsectionConstraint(int[][] board, int r, int c) {
|
||||
private boolean subsectionConstraint(int[][] board, int row, int column) {
|
||||
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||
int subsectionRowStart = (r / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
|
||||
|
||||
int subsectionColumnStart = (c / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
|
||||
|
||||
for (int i = subsectionRowStart; i < subsectionRowEnd; i++) {
|
||||
for (int j = subsectionColumnStart; j < subsectionColumnEnd; j++) {
|
||||
if (!checkConstraint(board, i, constraint, j)) return false;
|
||||
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
|
||||
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
|
||||
if (!checkConstraint(board, r, constraint, c)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean columnConstraint(int[][] board, int c) {
|
||||
private boolean columnConstraint(int[][] board, int column) {
|
||||
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
|
||||
.allMatch(i -> checkConstraint(board, i, constraint, c));
|
||||
.allMatch(row -> checkConstraint(board, row, constraint, column));
|
||||
}
|
||||
|
||||
private boolean rowConstraint(int[][] board, int r) {
|
||||
private boolean rowConstraint(int[][] board, int row) {
|
||||
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
|
||||
.allMatch(i -> checkConstraint(board, r, constraint, i));
|
||||
.allMatch(column -> checkConstraint(board, row, constraint, column));
|
||||
}
|
||||
|
||||
private boolean checkConstraint(int[][] board, int r, boolean[] constraint, int c) {
|
||||
if (board[r][c] != NO_VALUE) {
|
||||
if (!constraint[board[r][c] - 1]) {
|
||||
constraint[board[r][c] - 1] = true;
|
||||
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
|
||||
if (board[row][column] != NO_VALUE) {
|
||||
if (!constraint[board[row][column] - 1]) {
|
||||
constraint[board[row][column] - 1] = true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
@ -120,10 +120,10 @@ public class DancingLinks {
|
||||
}
|
||||
|
||||
private static void printSolution(int[][] result) {
|
||||
int N = result.length;
|
||||
int size = result.length;
|
||||
for (int[] aResult : result) {
|
||||
StringBuilder ret = new StringBuilder();
|
||||
for (int j = 0; j < N; j++) {
|
||||
for (int j = 0; j < size; j++) {
|
||||
ret.append(aResult[j]).append(" ");
|
||||
}
|
||||
System.out.println(ret);
|
||||
|
@ -34,75 +34,88 @@ public class DancingLinksAlgorithm {
|
||||
dlx.runSolver();
|
||||
}
|
||||
|
||||
private int getIndex(int row, int col, int num) {
|
||||
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (col - 1) * BOARD_SIZE + (num - 1);
|
||||
private int getIndex(int row, int column, int num) {
|
||||
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (column - 1) * BOARD_SIZE + (num - 1);
|
||||
}
|
||||
|
||||
private boolean[][] createExactCoverBoard() {
|
||||
boolean[][] R = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
|
||||
boolean[][] coverBoard = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
|
||||
|
||||
int hBase = 0;
|
||||
hBase = checkCellConstraint(coverBoard, hBase);
|
||||
hBase = checkRowConstraint(coverBoard, hBase);
|
||||
hBase = checkColumnConstraint(coverBoard, hBase);
|
||||
checkSubsectionConstraint(coverBoard, hBase);
|
||||
|
||||
// Cell constraint.
|
||||
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
|
||||
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++, hBase++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
|
||||
int index = getIndex(r, c, n);
|
||||
R[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return coverBoard;
|
||||
}
|
||||
|
||||
// Row constrain.
|
||||
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||
for (int c1 = COVER_START_INDEX; c1 <= BOARD_SIZE; c1++) {
|
||||
int index = getIndex(r, c1, n);
|
||||
R[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Column constraint.
|
||||
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||
for (int r1 = COVER_START_INDEX; r1 <= BOARD_SIZE; r1++) {
|
||||
int index = getIndex(r1, c, n);
|
||||
R[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Subsection constraint
|
||||
for (int br = COVER_START_INDEX; br <= BOARD_SIZE; br += SUBSECTION_SIZE) {
|
||||
for (int bc = COVER_START_INDEX; bc <= BOARD_SIZE; bc += SUBSECTION_SIZE) {
|
||||
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
|
||||
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) {
|
||||
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||
for (int rDelta = 0; rDelta < SUBSECTION_SIZE; rDelta++) {
|
||||
for (int cDelta = 0; cDelta < SUBSECTION_SIZE; cDelta++) {
|
||||
int index = getIndex(br + rDelta, bc + cDelta, n);
|
||||
R[index][hBase] = true;
|
||||
for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) {
|
||||
for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) {
|
||||
int index = getIndex(row + rowDelta, column + columnDelta, n);
|
||||
coverBoard[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return R;
|
||||
return hBase;
|
||||
}
|
||||
|
||||
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
|
||||
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||
int index = getIndex(row, column, n);
|
||||
coverBoard[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return hBase;
|
||||
}
|
||||
|
||||
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
|
||||
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||
int index = getIndex(row, column, n);
|
||||
coverBoard[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return hBase;
|
||||
}
|
||||
|
||||
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
|
||||
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) {
|
||||
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
|
||||
int index = getIndex(row, column, n);
|
||||
coverBoard[index][hBase] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return hBase;
|
||||
}
|
||||
|
||||
private boolean[][] initializeExactCoverBoard(int[][] board) {
|
||||
boolean[][] R = createExactCoverBoard();
|
||||
for (int i = COVER_START_INDEX; i <= BOARD_SIZE; i++) {
|
||||
for (int j = COVER_START_INDEX; j <= BOARD_SIZE; j++) {
|
||||
int n = board[i - 1][j - 1];
|
||||
boolean[][] coverBoard = createExactCoverBoard();
|
||||
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||
int n = board[row - 1][column - 1];
|
||||
if (n != NO_VALUE) {
|
||||
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
|
||||
if (num != n) {
|
||||
Arrays.fill(R[getIndex(i, j, num)], false);
|
||||
Arrays.fill(coverBoard[getIndex(row, column, num)], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return R;
|
||||
return coverBoard;
|
||||
}
|
||||
}
|
@ -4,21 +4,21 @@ class DancingNode {
|
||||
DancingNode L, R, U, D;
|
||||
ColumnNode C;
|
||||
|
||||
DancingNode hookDown(DancingNode n1) {
|
||||
assert (this.C == n1.C);
|
||||
n1.D = this.D;
|
||||
n1.D.U = n1;
|
||||
n1.U = this;
|
||||
this.D = n1;
|
||||
return n1;
|
||||
DancingNode hookDown(DancingNode node) {
|
||||
assert (this.C == node.C);
|
||||
node.D = this.D;
|
||||
node.D.U = node;
|
||||
node.U = this;
|
||||
this.D = node;
|
||||
return node;
|
||||
}
|
||||
|
||||
DancingNode hookRight(DancingNode n1) {
|
||||
n1.R = this.R;
|
||||
n1.R.L = n1;
|
||||
n1.L = this;
|
||||
this.R = n1;
|
||||
return n1;
|
||||
DancingNode hookRight(DancingNode node) {
|
||||
node.R = this.R;
|
||||
node.R.L = node;
|
||||
node.L = this;
|
||||
this.R = node;
|
||||
return node;
|
||||
}
|
||||
|
||||
void unlinkLR() {
|
||||
|
12
algorithms/src/main/resources/maze/maze1.txt
Normal file
12
algorithms/src/main/resources/maze/maze1.txt
Normal file
@ -0,0 +1,12 @@
|
||||
S ########
|
||||
# #
|
||||
# ### ## #
|
||||
# # # #
|
||||
# # # # #
|
||||
# ## #####
|
||||
# # #
|
||||
# # # # #
|
||||
##### ####
|
||||
# # E
|
||||
# # # #
|
||||
##########
|
22
algorithms/src/main/resources/maze/maze2.txt
Normal file
22
algorithms/src/main/resources/maze/maze2.txt
Normal file
@ -0,0 +1,22 @@
|
||||
S ##########################
|
||||
# # # #
|
||||
# # #### ############### #
|
||||
# # # # # #
|
||||
# # #### # # ###############
|
||||
# # # # # # #
|
||||
# # # #### ### ########### #
|
||||
# # # # # #
|
||||
# ################## #
|
||||
######### # # # # #
|
||||
# # #### # ####### # #
|
||||
# # ### ### # # # # #
|
||||
# # ## # ##### # #
|
||||
##### ####### # # # # #
|
||||
# # ## ## #### # #
|
||||
# ##### ####### # #
|
||||
# # ############
|
||||
####### ######### # #
|
||||
# # ######## #
|
||||
# ####### ###### ## # E
|
||||
# # # ## #
|
||||
############################
|
114
checker-plugin/pom.xml
Normal file
114
checker-plugin/pom.xml
Normal file
@ -0,0 +1,114 @@
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>checker-plugin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>checker-plugin</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<!-- https://checkerframework.org/manual/#maven -->
|
||||
|
||||
<properties>
|
||||
<!-- These properties will be set by the Maven Dependency plugin -->
|
||||
<annotatedJdk>${org.checkerframework:jdk8:jar}</annotatedJdk>
|
||||
<!-- Uncomment to use the Type Annotations compiler. -->
|
||||
<!--
|
||||
<typeAnnotationsJavac>${org.checkerframework:compiler:jar}</typeAnnotationsJavac>
|
||||
-->
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<!-- Annotations from the Checker Framework: nullness, interning, locking, ... -->
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>checker-qual</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>checker</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>jdk8</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<!-- The Type Annotations compiler. Uncomment if using annotations in comments. -->
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>compiler</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<!-- This plugin will set properties values using dependency information -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<!--
|
||||
Goal that sets a property pointing to the artifact file for each project dependency.
|
||||
For each dependency (direct and transitive) a project property will be set which
|
||||
follows the:
|
||||
|
||||
groupId:artifactId:type:[classifier]
|
||||
|
||||
form and contains the path to the resolved artifact. -->
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<!-- Uncomment the following line to use the type annotations compiler. -->
|
||||
<!-- <fork>true</fork> -->
|
||||
<compilerArguments>
|
||||
<Xmaxerrs>10000</Xmaxerrs>
|
||||
<Xmaxwarns>10000</Xmaxwarns>
|
||||
</compilerArguments>
|
||||
<annotationProcessors>
|
||||
<!-- Add all the checkers you want to enable here -->
|
||||
<annotationProcessor>org.checkerframework.checker.nullness.NullnessChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.interning.InterningChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.fenum.FenumChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.formatter.FormatterChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.regex.RegexChecker</annotationProcessor>
|
||||
</annotationProcessors>
|
||||
<compilerArgs>
|
||||
<arg>-AprintErrorStack</arg>
|
||||
|
||||
<!-- location of the annotated JDK, which comes from a Maven dependency -->
|
||||
<arg>-Xbootclasspath/p:${annotatedJdk}</arg>
|
||||
<!--
|
||||
-->
|
||||
|
||||
<!-- Uncomment the following line to use the type annotations compiler. -->
|
||||
<!--
|
||||
<arg>-J-Xbootclasspath/p:${typeAnnotationsJavac}</arg>
|
||||
-->
|
||||
<!-- Uncomment the following line to turn type-checking warnings into errors. -->
|
||||
<arg>-Awarns</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.fenum.qual.Fenum;
|
||||
|
||||
//@SuppressWarnings("fenum:assignment.type.incompatible")
|
||||
public class FakeNumExample {
|
||||
|
||||
// Here we use some String constants to represents countries.
|
||||
static final @Fenum("country") String ITALY = "IT";
|
||||
static final @Fenum("country") String US = "US";
|
||||
static final @Fenum("country") String UNITED_KINGDOM = "UK";
|
||||
|
||||
// Here we use other String constants to represent planets instead.
|
||||
static final @Fenum("planet") String MARS = "Mars";
|
||||
static final @Fenum("planet") String EARTH = "Earth";
|
||||
static final @Fenum("planet") String VENUS = "Venus";
|
||||
|
||||
// Now we write this method and we want to be sure that
|
||||
// the String parameter has a value of a country, not that is just a String.
|
||||
void greetCountries(@Fenum("country") String country) {
|
||||
System.out.println("Hello " + country);
|
||||
}
|
||||
|
||||
// Similarly we're enforcing here that the provided
|
||||
// parameter is a String that represent a planet.
|
||||
void greetPlanets(@Fenum("planet") String planet) {
|
||||
System.out.println("Hello " + planet);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
FakeNumExample obj = new FakeNumExample();
|
||||
|
||||
// This will fail because we pass a planet-String to a method that
|
||||
// accept a country-String.
|
||||
obj.greetCountries(MARS);
|
||||
|
||||
// Here the opposite happens.
|
||||
obj.greetPlanets(US);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
public class FormatExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Just enabling org.checkerframework.checker.formatter.FormatterChecker
|
||||
// we can be sure at compile time that the format strings we pass to format()
|
||||
// are correct. Normally we would have those errors raised just at runtime.
|
||||
// All those formats are in fact wrong.
|
||||
|
||||
String.format("%y", 7); // error: invalid format string
|
||||
|
||||
String.format("%d", "a string"); // error: invalid argument type for %d
|
||||
|
||||
String.format("%d %s", 7); // error: missing argument for %s
|
||||
|
||||
String.format("%d", 7, 3); // warning: unused argument 3
|
||||
|
||||
String.format("{0}", 7); // warning: unused argument 7, because {0} is wrong syntax
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.KeyFor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class KeyForExample {
|
||||
|
||||
private final Map<String, String> config = new HashMap<>();
|
||||
|
||||
KeyForExample() {
|
||||
|
||||
// Here we initialize a map to store
|
||||
// some config data.
|
||||
config.put("url", "http://1.2.3.4");
|
||||
config.put("name", "foobaz");
|
||||
}
|
||||
|
||||
public void dumpPort() {
|
||||
|
||||
// Here, we want to dump the port value stored in the
|
||||
// config, so we declare that this key has to be
|
||||
// present in the config map.
|
||||
// Obviously that will fail because such key is not present
|
||||
// in the map.
|
||||
@KeyFor("config") String key = "port";
|
||||
System.out.println( config.get(key) );
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class MonotonicNotNullExample {
|
||||
|
||||
// The idea is we need this field to be to lazily initialized,
|
||||
// so it starts as null but once it becomes not null
|
||||
// it cannot return null.
|
||||
// In these cases, we can use @MonotonicNonNull
|
||||
@MonotonicNonNull private Date firstCall;
|
||||
|
||||
public Date getFirstCall() {
|
||||
if (firstCall == null) {
|
||||
firstCall = new Date();
|
||||
}
|
||||
return firstCall;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
// This is reported as error because
|
||||
// we wrongly set the field back to null.
|
||||
firstCall = null;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
public class NonNullExample {
|
||||
|
||||
// This method's parameter is annotated in order
|
||||
// to tell the pluggable type system that it can never be null.
|
||||
private static int countArgs(@NonNull String[] args) {
|
||||
return args.length;
|
||||
}
|
||||
|
||||
// This method's parameter is annotated in order
|
||||
// to tell the pluggable type system that it may be null.
|
||||
public static void main(@Nullable String[] args) {
|
||||
|
||||
// Here lies a potential error,
|
||||
// because we pass a potential null reference to a method
|
||||
// that does not accept nulls.
|
||||
// The Checker Framework will spot this problem at compile time
|
||||
// instead of runtime.
|
||||
System.out.println(countArgs(args));
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.regex.qual.Regex;
|
||||
|
||||
public class RegexExample {
|
||||
|
||||
// For some reason we want to be sure that this regex
|
||||
// contains at least one capturing group.
|
||||
// However, we do an error and we forgot to define such
|
||||
// capturing group in it.
|
||||
@Regex(1) private static String findNumbers = "\\d*";
|
||||
|
||||
public static void main(String[] args) {
|
||||
String message = "My phone number is +3911223344.";
|
||||
message.matches(findNumbers);
|
||||
}
|
||||
|
||||
}
|
4
core-groovy/README.md
Normal file
4
core-groovy/README.md
Normal file
@ -0,0 +1,4 @@
|
||||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
118
core-groovy/pom.xml
Normal file
118
core-groovy/pom.xml
Normal file
@ -0,0 +1,118 @@
|
||||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>core-groovy</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.4.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.6</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
|
||||
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
|
||||
<kotlinx.version>0.15</kotlinx.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
|
||||
<junit.jupiter.version>5.0.0</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<junit.vintage.version>4.12.0</junit.vintage.version>
|
||||
<junit4.version>4.12</junit4.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,229 @@
|
||||
package com.baeldung.groovy.sql
|
||||
|
||||
import groovy.sql.GroovyResultSet
|
||||
import groovy.sql.GroovyRowResult
|
||||
import groovy.sql.Sql
|
||||
import groovy.transform.CompileStatic
|
||||
import static org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SqlTest {
|
||||
|
||||
final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver']
|
||||
|
||||
@Test
|
||||
void whenNewSqlInstance_thenDbIsAccessed() {
|
||||
def sql = Sql.newInstance(dbConnParams)
|
||||
sql.close()
|
||||
sql.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableDoesNotExist_thenSelectFails() {
|
||||
try {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.eachRow('select * from PROJECT') {}
|
||||
}
|
||||
|
||||
fail("An exception should have been thrown")
|
||||
} catch (ignored) {
|
||||
//Ok
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableCreated_thenSelectIsPossible() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))'
|
||||
|
||||
assertEquals(0, sql.updateCount)
|
||||
assertFalse(result)
|
||||
|
||||
result = sql.execute('select * from PROJECT_1')
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIdentityColumn_thenInsertReturnsNewId() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
|
||||
assertEquals(0, ids[0][0])
|
||||
|
||||
ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
assertEquals(1, ids[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUpdate_thenNumberOfAffectedRows() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL")
|
||||
|
||||
assertEquals(2, count)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEachRow_thenResultSetHasProperties() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_4") { GroovyResultSet rs ->
|
||||
assertNotNull(rs.name)
|
||||
assertNotNull(rs.url)
|
||||
assertNotNull(rs[0])
|
||||
assertNotNull(rs[1])
|
||||
assertNotNull(rs[2])
|
||||
assertEquals(rs.name, rs['name'])
|
||||
assertEquals(rs.url, rs['url'])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPagination_thenSubsetIsReturned() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1)
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
assertEquals('REST with Spring', rows[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParameters_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials')
|
||||
sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring'])
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParametersInGString_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})"
|
||||
def name = 'REST with Spring'
|
||||
def url = 'github.com/eugenp/REST-With-Spring'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${name}, ${url})"
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollback_thenNoDataInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_8")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_9")
|
||||
|
||||
assertEquals(2, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenException_thenTransactionIsRolledBack() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_10")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCachedConnection_whenException_thenDataIsPersisted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.cacheConnection {
|
||||
sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('This does not rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_11")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
/*@Test
|
||||
void whenModifyResultSet_thenDataIsChanged() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5 FOR UPDATE ") { GroovyResultSet rs ->
|
||||
rs['name'] = "The great ${rs.name}!" as String
|
||||
rs.updateRow()
|
||||
}
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5") { GroovyResultSet rs ->
|
||||
assertTrue(rs.name.startsWith('The great '))
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
}
|
@ -40,3 +40,4 @@
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.shufflingcollections;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ShufflingCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenShufflingList_thenListIsShuffled() {
|
||||
List<String> students = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
System.out.println("List before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
Collections.shuffle(students);
|
||||
System.out.println("List after shuffling:");
|
||||
System.out.println(students);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingMapEntries_thenValuesAreShuffled() {
|
||||
Map<Integer, String> studentsById = new HashMap<>();
|
||||
studentsById.put(1, "Foo");
|
||||
studentsById.put(2, "Bar");
|
||||
studentsById.put(3, "Baz");
|
||||
studentsById.put(4, "Qux");
|
||||
|
||||
System.out.println("Students before shuffling:");
|
||||
System.out.println(studentsById.values());
|
||||
|
||||
List<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
|
||||
Collections.shuffle(shuffledStudentEntries);
|
||||
|
||||
List<String> shuffledStudents = shuffledStudentEntries.stream()
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
System.out.println("Students after shuffling");
|
||||
System.out.println(shuffledStudents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingSet_thenElementsAreShuffled() {
|
||||
Set<String> students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux"));
|
||||
|
||||
System.out.println("Set before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
List<String> studentList = new ArrayList<>(students);
|
||||
|
||||
Collections.shuffle(studentList);
|
||||
System.out.println("Shuffled set elements:");
|
||||
System.out.println(studentList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() {
|
||||
List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
List<String> students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
Collections.shuffle(students_1, new Random(5));
|
||||
Collections.shuffle(students_2, new Random(5));
|
||||
|
||||
assertThat(students_1).isEqualTo(students_2);
|
||||
}
|
||||
}
|
@ -1,126 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import static java.net.HttpURLConnection.HTTP_OK;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.CookieManager;
|
||||
import java.net.CookiePolicy;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SimpleHttpRequestsUnitTest {
|
||||
|
||||
private URI httpURI;
|
||||
|
||||
@Before
|
||||
public void init() throws URISyntaxException {
|
||||
httpURI = new URI("http://www.baeldung.com/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
HttpResponse response = request.response();
|
||||
int responseStatusCode = response.statusCode();
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
long before = System.currentTimeMillis();
|
||||
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
||||
futureResponse.thenAccept(response -> {
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
});
|
||||
HttpResponse resp = futureResponse.get();
|
||||
HttpHeaders hs = resp.headers();
|
||||
assertTrue("There should be more then 1 header.", hs.map().size() > 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
||||
requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE);
|
||||
HttpRequest request = requestBuilder.POST();
|
||||
HttpResponse response = request.response();
|
||||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException {
|
||||
CookieManager cManager = new CookieManager();
|
||||
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
|
||||
|
||||
SSLParameters sslParam = new SSLParameters(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||
|
||||
HttpClient.Builder hcBuilder = HttpClient.create();
|
||||
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
||||
HttpClient httpClient = hcBuilder.build();
|
||||
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
||||
|
||||
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
||||
HttpResponse response = request.response();
|
||||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException {
|
||||
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
||||
String[] proto = sslP1.getApplicationProtocols();
|
||||
String[] cifers = sslP1.getCipherSuites();
|
||||
System.out.println(printStringArr(proto));
|
||||
System.out.println(printStringArr(cifers));
|
||||
return sslP1;
|
||||
}
|
||||
|
||||
String printStringArr(String... args) {
|
||||
if (args == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String s : args) {
|
||||
sb.append(s);
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String printHeaders(HttpHeaders h) {
|
||||
if (h == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<String, List<String>> hMap = h.map();
|
||||
for (String k : hMap.keySet()) {
|
||||
sb.append(k).append(":");
|
||||
List<String> l = hMap.get(k);
|
||||
if (l != null) {
|
||||
l.forEach(s -> {
|
||||
sb.append(s).append(",");
|
||||
});
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -16,7 +16,8 @@ public class Job implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
System.out.println("Job:" + jobName + " Priority:" + jobPriority);
|
||||
System.out.println("Job:" + jobName +
|
||||
" Priority:" + jobPriority);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
|
@ -9,21 +9,21 @@ import java.util.concurrent.TimeUnit;
|
||||
public class PriorityJobScheduler {
|
||||
|
||||
private ExecutorService priorityJobPoolExecutor;
|
||||
private ExecutorService priorityJobScheduler;
|
||||
private PriorityBlockingQueue<Runnable> priorityQueue;
|
||||
private ExecutorService priorityJobScheduler =
|
||||
Executors.newSingleThreadExecutor();
|
||||
private PriorityBlockingQueue<Job> priorityQueue;
|
||||
|
||||
public PriorityJobScheduler(Integer poolSize, Integer queueSize) {
|
||||
priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
|
||||
Comparator<? super Job> jobComparator = Comparator.comparing(Job::getJobPriority);
|
||||
priorityQueue = new PriorityBlockingQueue<Runnable>(queueSize,
|
||||
(Comparator<? super Runnable>) jobComparator);
|
||||
priorityQueue = new PriorityBlockingQueue<Job>(queueSize,
|
||||
Comparator.comparing(Job::getJobPriority));
|
||||
|
||||
priorityJobScheduler = Executors.newSingleThreadExecutor();
|
||||
priorityJobScheduler.execute(()->{
|
||||
while (true) {
|
||||
try {
|
||||
priorityJobPoolExecutor.execute(priorityQueue.take());
|
||||
} catch (InterruptedException e) {
|
||||
// exception needs special handling
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class BlockedState {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Thread t1 = new Thread(new DemoThreadB());
|
||||
Thread t2 = new Thread(new DemoThreadB());
|
||||
|
||||
t1.start();
|
||||
t2.start();
|
||||
|
||||
Thread.sleep(1000);
|
||||
|
||||
System.out.println(t2.getState());
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
class DemoThreadB implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
commonResource();
|
||||
}
|
||||
|
||||
public static synchronized void commonResource() {
|
||||
while(true) {
|
||||
// Infinite loop to mimic heavy processing
|
||||
// Thread 't1' won't leave this method
|
||||
// when Thread 't2' enters this
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class NewState implements Runnable {
|
||||
public static void main(String[] args) {
|
||||
Runnable runnable = new NewState();
|
||||
Thread t = new Thread(runnable);
|
||||
System.out.println(t.getState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class RunnableState implements Runnable {
|
||||
public static void main(String[] args) {
|
||||
Runnable runnable = new NewState();
|
||||
Thread t = new Thread(runnable);
|
||||
t.start();
|
||||
System.out.println(t.getState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class TerminatedState implements Runnable {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Thread t1 = new Thread(new TerminatedState());
|
||||
t1.start();
|
||||
Thread.sleep(1000);
|
||||
System.out.println(t1.getState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// No processing in this block
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class TimedWaitingState {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
DemoThread obj1 = new DemoThread();
|
||||
Thread t1 = new Thread(obj1);
|
||||
t1.start();
|
||||
// The following sleep will give enough time for ThreadScheduler
|
||||
// to start processing of thread t1
|
||||
Thread.sleep(1000);
|
||||
System.out.println(t1.getState());
|
||||
}
|
||||
}
|
||||
|
||||
class DemoThread implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.concurrent.threadlifecycle;
|
||||
|
||||
public class WaitingState implements Runnable {
|
||||
public static Thread t1;
|
||||
|
||||
public static void main(String[] args) {
|
||||
t1 = new Thread(new WaitingState());
|
||||
t1.start();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
Thread t2 = new Thread(new DemoThreadWS());
|
||||
t2.start();
|
||||
|
||||
try {
|
||||
t2.join();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DemoThreadWS implements Runnable {
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
System.out.println(WaitingState.t1.getState());
|
||||
}
|
||||
}
|
@ -30,7 +30,9 @@ public class PriorityJobSchedulerUnitTest {
|
||||
// delay to avoid job sleep (added for demo) being interrupted
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ignored) {
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
pjs.closeScheduler();
|
||||
|
@ -78,6 +78,11 @@
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
@ -468,6 +473,7 @@
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
|
13
core-java/src/main/java/com/baeldung/casting/Animal.java
Normal file
13
core-java/src/main/java/com/baeldung/casting/Animal.java
Normal file
@ -0,0 +1,13 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("animal is eating");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeeder {
|
||||
|
||||
public void feed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
if (animal instanceof Cat) {
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void uncheckedFeed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
((Cat) animal).meow();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
16
core-java/src/main/java/com/baeldung/casting/Cat.java
Normal file
16
core-java/src/main/java/com/baeldung/casting/Cat.java
Normal file
@ -0,0 +1,16 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Cat extends Animal implements Mew {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("cat is eating");
|
||||
}
|
||||
|
||||
public void meow() {
|
||||
LOGGER.info("meow");
|
||||
}
|
||||
}
|
12
core-java/src/main/java/com/baeldung/casting/Dog.java
Normal file
12
core-java/src/main/java/com/baeldung/casting/Dog.java
Normal file
@ -0,0 +1,12 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Dog extends Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Dog.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("dog is eating");
|
||||
}
|
||||
}
|
5
core-java/src/main/java/com/baeldung/casting/Mew.java
Normal file
5
core-java/src/main/java/com/baeldung/casting/Mew.java
Normal file
@ -0,0 +1,5 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
public interface Mew {
|
||||
public void meow();
|
||||
}
|
59
core-java/src/main/java/com/baeldung/deepcopy/Address.java
Normal file
59
core-java/src/main/java/com/baeldung/deepcopy/Address.java
Normal file
@ -0,0 +1,59 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Address implements Serializable, Cloneable {
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
try {
|
||||
return (Address) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
return new Address(this.street, this.getCity(), this.getCountry());
|
||||
}
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 1740913841244949416L;
|
||||
private String street;
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
public Address(Address that) {
|
||||
this(that.getStreet(), that.getCity(), that.getCountry());
|
||||
}
|
||||
|
||||
public Address(String street, String city, String country) {
|
||||
this.street = street;
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
48
core-java/src/main/java/com/baeldung/deepcopy/User.java
Normal file
48
core-java/src/main/java/com/baeldung/deepcopy/User.java
Normal file
@ -0,0 +1,48 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
|
||||
private static final long serialVersionUID = -3427002229954777557L;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Address address;
|
||||
|
||||
public User(String firstName, String lastName, Address address) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User(User that) {
|
||||
this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
User user;
|
||||
try {
|
||||
user = (User) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
user = new User(this.getFirstName(), this.getLastName(), this.getAddress());
|
||||
}
|
||||
user.address = (Address) this.address.clone();
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public abstract class AuthenticationProcessor {
|
||||
|
||||
// next element in chain or responsibility
|
||||
public AuthenticationProcessor nextProcessor;
|
||||
|
||||
public AuthenticationProcessor(AuthenticationProcessor nextProcessor) {
|
||||
this.nextProcessor = nextProcessor;
|
||||
}
|
||||
|
||||
public abstract boolean isAuthorized(AuthenticationProvider authProvider);
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public interface AuthenticationProvider {
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public class OAuthAuthenticationProcessor extends AuthenticationProcessor {
|
||||
|
||||
public OAuthAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
|
||||
super(nextProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthorized(AuthenticationProvider authProvider) {
|
||||
|
||||
if (authProvider instanceof OAuthTokenProvider) {
|
||||
return Boolean.TRUE;
|
||||
} else if (nextProcessor != null) {
|
||||
return nextProcessor.isAuthorized(authProvider);
|
||||
} else {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public class OAuthTokenProvider implements AuthenticationProvider {
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public class SamlAuthenticationProvider implements AuthenticationProvider {
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor {
|
||||
|
||||
public UsernamePasswordAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
|
||||
super(nextProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthorized(AuthenticationProvider authProvider) {
|
||||
if (authProvider instanceof UsernamePasswordProvider) {
|
||||
return Boolean.TRUE;
|
||||
} else if (nextProcessor != null) {
|
||||
return nextProcessor.isAuthorized(authProvider);
|
||||
} else {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public class UsernamePasswordProvider implements AuthenticationProvider {
|
||||
|
||||
}
|
229
core-java/src/main/java/com/baeldung/java/list/CustomList.java
Normal file
229
core-java/src/main/java/com/baeldung/java/list/CustomList.java
Normal file
@ -0,0 +1,229 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
public class CustomList<E> implements List<E> {
|
||||
private Object[] internal = {};
|
||||
|
||||
@Override
|
||||
public void add(int index, E element) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends E> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(int index, Collection<? extends E> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E remove(int index) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object object) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return internal.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return internal.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E element) {
|
||||
// the first cycle
|
||||
// internal = new Object[1];
|
||||
// internal[0] = element;
|
||||
// return true;
|
||||
|
||||
Object[] temp = new Object[internal.length + 1];
|
||||
System.arraycopy(internal, 0, temp, 0, internal.length);
|
||||
temp[internal.length] = element;
|
||||
internal = temp;
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E get(int index) {
|
||||
return (E) internal[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object object) {
|
||||
// return false
|
||||
|
||||
for (Object element : internal) {
|
||||
if (object.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> collection) {
|
||||
// the first cycle
|
||||
// for (Object element : collection) {
|
||||
// if (element.equals(internal[0])) {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
// return false;
|
||||
|
||||
for (Object element : collection)
|
||||
if (!contains(element)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E set(int index, E element) {
|
||||
E oldElement = (E) internal[index];
|
||||
internal[index] = element;
|
||||
return oldElement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
internal = new Object[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int indexOf(Object object) {
|
||||
// the first cycle
|
||||
// if (object.equals(internal[0])) {
|
||||
// return 0;
|
||||
// }
|
||||
// return -1;
|
||||
|
||||
for (int i = 0; i < internal.length; i++) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastIndexOf(Object object) {
|
||||
// the first cycle
|
||||
// if (object.equals(internal[0])) {
|
||||
// return 0;
|
||||
// }
|
||||
// return -1;
|
||||
|
||||
for (int i = internal.length - 1; i >= 0; i--) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public List<E> subList(int fromIndex, int toIndex) {
|
||||
// the first cycle
|
||||
// return (List<E>) Arrays.asList(internal);
|
||||
|
||||
Object[] temp = new Object[toIndex - fromIndex];
|
||||
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
|
||||
return (List<E>) Arrays.asList(temp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
return Arrays.copyOf(internal, internal.length);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T[] toArray(T[] array) {
|
||||
// the first cycle
|
||||
// array[0] = (T) internal[0];
|
||||
// return array;
|
||||
|
||||
// the second cycle
|
||||
// if (array.length < internal.length) {
|
||||
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
// }
|
||||
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
|
||||
if (array.length < internal.length) {
|
||||
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
}
|
||||
|
||||
System.arraycopy(internal, 0, array, 0, internal.length);
|
||||
if (array.length > internal.length) {
|
||||
array[internal.length] = null;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new CustomIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<E> listIterator() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<E> listIterator(int index) {
|
||||
// ignored for brevity
|
||||
return null;
|
||||
}
|
||||
|
||||
private class CustomIterator implements Iterator<E> {
|
||||
int index;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
// the first cycle
|
||||
// return true;
|
||||
|
||||
return index != internal.length;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E next() {
|
||||
// the first cycle
|
||||
// return (E) CustomList.this.internal[0];
|
||||
|
||||
E element = (E) CustomList.this.internal[index];
|
||||
index++;
|
||||
return element;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.methodoverloadingoverriding.application;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.model.Car;
|
||||
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
|
||||
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Multiplier multiplier = new Multiplier();
|
||||
System.out.println(multiplier.multiply(10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10.5));
|
||||
System.out.println(multiplier.multiply(10.5, 10.5));
|
||||
|
||||
Vehicle vehicle = new Vehicle();
|
||||
System.out.println(vehicle.accelerate(100));
|
||||
System.out.println(vehicle.run());
|
||||
System.out.println(vehicle.stop());
|
||||
|
||||
Vehicle car = new Car();
|
||||
System.out.println(car.accelerate(80));
|
||||
System.out.println(car.run());
|
||||
System.out.println(car.stop());
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Car extends Vehicle {
|
||||
|
||||
@Override
|
||||
public String accelerate(long mph) {
|
||||
return "The car accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Vehicle {
|
||||
|
||||
public String accelerate(long mph) {
|
||||
return "The vehicle accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
|
||||
public String stop() {
|
||||
return "The vehicle has stopped.";
|
||||
}
|
||||
|
||||
public String run() {
|
||||
return "The vehicle is running.";
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.util;
|
||||
|
||||
public class Multiplier {
|
||||
|
||||
public int multiply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
public int multiply(int a, int b, int c) {
|
||||
return a * b * c;
|
||||
}
|
||||
|
||||
public double multiply(double a, double b) {
|
||||
return a * b;
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class ExampleControl extends ResourceBundle.Control {
|
||||
|
||||
@Override
|
||||
public List<Locale> getCandidateLocales(String s, Locale locale) {
|
||||
return Arrays.asList(new Locale("pl", "PL"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import java.util.ListResourceBundle;
|
||||
|
||||
public class ExampleResource extends ListResourceBundle {
|
||||
|
||||
@Override
|
||||
protected Object[][] getContents() {
|
||||
return new Object[][] {
|
||||
{ "greeting", "hello" }
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import java.util.ListResourceBundle;
|
||||
|
||||
public class ExampleResource_pl extends ListResourceBundle {
|
||||
|
||||
@Override
|
||||
protected Object[][] getContents() {
|
||||
return new Object[][] {
|
||||
{ "greeting", "cześć" },
|
||||
{ "language", "polish" },
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ListResourceBundle;
|
||||
|
||||
public class ExampleResource_pl_PL extends ListResourceBundle {
|
||||
|
||||
@Override
|
||||
protected Object[][] getContents() {
|
||||
return new Object[][] {
|
||||
{ "currency", "polish zloty" },
|
||||
{ "toUsdRate", new BigDecimal("3.401") },
|
||||
{ "cities", new String[] { "Warsaw", "Cracow" } }
|
||||
};
|
||||
}
|
||||
|
||||
}
|
66
core-java/src/main/java/com/baeldung/string/Palindrome.java
Normal file
66
core-java/src/main/java/com/baeldung/string/Palindrome.java
Normal file
@ -0,0 +1,66 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class Palindrome {
|
||||
|
||||
public boolean isPalindrome(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
int length = clean.length();
|
||||
int forward = 0;
|
||||
int backward = length - 1;
|
||||
while (backward > forward) {
|
||||
char forwardChar = clean.charAt(forward++);
|
||||
char backwardChar = clean.charAt(backward--);
|
||||
if (forwardChar != backwardChar)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isPalindromeReverseTheString(String text) {
|
||||
StringBuilder reverse = new StringBuilder();
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
char[] plain = clean.toCharArray();
|
||||
for (int i = plain.length - 1; i >= 0; i--)
|
||||
reverse.append(plain[i]);
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingStringBuilder(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
StringBuilder plain = new StringBuilder(clean);
|
||||
StringBuilder reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingStringBuffer(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
StringBuffer plain = new StringBuffer(clean);
|
||||
StringBuffer reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeRecursive(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
return recursivePalindrome(clean, 0, clean.length() - 1);
|
||||
}
|
||||
|
||||
private boolean recursivePalindrome(String text, int forward, int backward) {
|
||||
if (forward == backward)
|
||||
return true;
|
||||
if ((text.charAt(forward)) != (text.charAt(backward)))
|
||||
return false;
|
||||
if (forward < backward + 1) {
|
||||
return recursivePalindrome(text, forward + 1, backward - 1);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingIntStream(String text) {
|
||||
String temp = text.replaceAll("\\s+", "").toLowerCase();
|
||||
return IntStream.range(0, temp.length() / 2)
|
||||
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
# Buttons
|
||||
cancelButton=cancel
|
||||
continueButton continue
|
||||
|
||||
! Labels
|
||||
helloLabel:hello
|
@ -0,0 +1 @@
|
||||
deleteButton=delete
|
@ -0,0 +1,3 @@
|
||||
backButton=cofnij
|
||||
helloLabel=cze\u015b\u0107
|
||||
helloLabelNoEncoding=cześć
|
@ -0,0 +1,58 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CastingTest {
|
||||
|
||||
@Test
|
||||
public void whenPrimitiveConverted_thenValueChanged() {
|
||||
double myDouble = 1.1;
|
||||
int myInt = (int) myDouble;
|
||||
assertNotEquals(myDouble, myInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcast_thenInstanceUnchanged() {
|
||||
Cat cat = new Cat();
|
||||
Animal animal = cat;
|
||||
animal = (Animal) cat;
|
||||
assertTrue(animal instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToObject_thenInstanceUnchanged() {
|
||||
Object object = new Animal();
|
||||
assertTrue(object instanceof Animal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToInterface_thenInstanceUnchanged() {
|
||||
Mew mew = new Cat();
|
||||
assertTrue(mew instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToAnimal_thenOverridenMethodsCalled() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().feed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCat_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void whenDownCastWithoutCheck_thenExceptionThrown() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().uncheckedFeed(animals);
|
||||
}
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package com.baeldung.decimalformat;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DecimalFormatExamplesTest {
|
||||
|
||||
double d = 1234567.89;
|
||||
|
||||
@Test
|
||||
public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("001234567.890");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() {
|
||||
|
||||
assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The 1234568 number");
|
||||
|
||||
assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The # 1234568 number");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocales_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenE_WhenFormatting_ThenScientificNotation() {
|
||||
|
||||
assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("12.3456789E5");
|
||||
|
||||
assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("123.456789E4");
|
||||
|
||||
assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH));
|
||||
((DecimalFormat) nf).setParseBigDecimal(true);
|
||||
assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.lang.SerializationUtils;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class DeepCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingDeepCopyWithCopyConstructor_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
assertThat(deepCopy).isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenConstructorCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCloneCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) pm.clone();
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCommonsCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) SerializationUtils.clone(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenGsonCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
Gson gson = new Gson();
|
||||
User deepCopy = gson.fromJson(gson.toJson(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenJacksonCopyShouldNotChange() throws IOException {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
User deepCopy = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenMakingCopies_thenShowHowLongEachMethodTakes() throws CloneNotSupportedException, IOException {
|
||||
int times = 1000000;
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) SerializationUtils.clone(pm);
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Apache Commons Lang took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
Gson gson = new Gson();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = gson.fromJson(gson.toJson(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Gson took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = new User(pm);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with the copy constructor took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) pm.clone();
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Cloneable interface took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Jackson took " + (end - start) + " milliseconds.");
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ShallowCopyUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenShallowCopying_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
assertThat(shallowCopy)
|
||||
.isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCopyShouldChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(shallowCopy.getAddress().getCountry())
|
||||
.isEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ChainOfResponsibilityTest {
|
||||
|
||||
private static AuthenticationProcessor getChainOfAuthProcessor() {
|
||||
|
||||
AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null);
|
||||
AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor);
|
||||
return unamePasswordProcessor;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() {
|
||||
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
|
||||
boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider());
|
||||
assertTrue(isAuthorized);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() {
|
||||
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
|
||||
boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider());
|
||||
assertTrue(isAuthorized);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() {
|
||||
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
|
||||
boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider());
|
||||
assertTrue(!isAuthorized);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,282 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CustomListUnitTest {
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddToSpecifiedIndex_thenExceptionIsThrown() {
|
||||
new CustomList<>().add(0, null);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddAllToTheEnd_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
List<Object> list = new CustomList<>();
|
||||
list.addAll(collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddAllToSpecifiedIndex_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
List<Object> list = new CustomList<>();
|
||||
list.addAll(0, collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveAtSpecifiedIndex_thenExceptionIsThrown() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.remove(0);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveSpecifiedElement_thenExceptionIsThrown() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.remove("baeldung");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveAll_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.removeAll(collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRetainAll_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.retainAll(collection);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenSize_thenZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertEquals(0, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded = list.add("baeldung");
|
||||
Object element = list.get(0);
|
||||
|
||||
assertTrue(succeeded);
|
||||
assertEquals("baeldung", element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded1 = list.add("baeldung");
|
||||
boolean succeeded2 = list.add(".com");
|
||||
Object element1 = list.get(0);
|
||||
Object element2 = list.get(1);
|
||||
|
||||
assertTrue(succeeded1);
|
||||
assertTrue(succeeded2);
|
||||
assertEquals("baeldung", element1);
|
||||
assertEquals(".com", element2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenContains_thenFalseIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertFalse(list.contains(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenContains_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertTrue(list.contains("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenContainsAll_thenTrueIsReturned() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertTrue(list.containsAll(collection));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenContainsAll_thenEitherTrueOrFalseIsReturned() {
|
||||
Collection<Object> collection1 = new ArrayList<>();
|
||||
collection1.add("baeldung");
|
||||
collection1.add(".com");
|
||||
Collection<Object> collection2 = new ArrayList<>();
|
||||
collection2.add("baeldung");
|
||||
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertFalse(list.containsAll(collection1));
|
||||
assertTrue(list.containsAll(collection2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenSet_thenOldElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Object element = list.set(0, null);
|
||||
|
||||
assertEquals("baeldung", element);
|
||||
assertNull(list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenClear_thenAllElementsAreRemoved() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.clear();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenIndexOf_thenIndexZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertEquals(0, list.indexOf("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
list.add(".com");
|
||||
|
||||
assertEquals(1, list.indexOf(".com"));
|
||||
assertEquals(-1, list.indexOf("com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLastIndexOf_thenIndexZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertEquals(0, list.lastIndexOf("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLastIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
|
||||
assertEquals(1, list.lastIndexOf("baeldung"));
|
||||
assertEquals(-1, list.indexOf("com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubListZeroToOne_thenListContainingFirstElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
List<Object> subList = list.subList(0, 1);
|
||||
|
||||
assertEquals("baeldung", subList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubListOneToTwo_thenListContainingSecondElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".");
|
||||
list.add("com");
|
||||
List<Object> subList = list.subList(1, 2);
|
||||
|
||||
assertEquals(1, subList.size());
|
||||
assertEquals(".", subList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithElements_whenToArray_thenArrayContainsThose() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
Object[] array = list.toArray();
|
||||
|
||||
assertArrayEquals(new Object[] { "baeldung", ".com" }, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenToArray_thenInputArrayIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = new String[1];
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung" }, input);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToArrayIsCalledWithEmptyInputArray_thenNewArrayIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = {};
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung" }, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToArrayIsCalledWithLargerInput_thenOutputHasTrailingNull() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = new String[2];
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung", null }, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithOneElement_whenIterator_thenThisElementIsNext() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Iterator<Object> iterator = list.iterator();
|
||||
|
||||
assertTrue(iterator.hasNext());
|
||||
assertEquals("baeldung", iterator.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratorNextIsCalledTwice_thenTheSecondReturnsFalse() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Iterator<Object> iterator = list.iterator();
|
||||
|
||||
iterator.next();
|
||||
assertFalse(iterator.hasNext());
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.methodoverloadingoverriding.test;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class MethodOverloadingUnitTest {
|
||||
|
||||
private static Multiplier multiplier;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpMultiplierInstance() {
|
||||
multiplier = new Multiplier();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithTwoIntegers_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithTreeIntegers_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10, 10)).isEqualTo(1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithIntDouble_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10.5)).isEqualTo(105.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithDoubleDouble_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10.5, 10.5)).isEqualTo(110.25);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithIntIntAndMatching_thenNoTypePromotion() {
|
||||
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.baeldung.methodoverloadingoverriding.test;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.model.Car;
|
||||
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class MethodOverridingUnitTest {
|
||||
|
||||
private static Vehicle vehicle;
|
||||
private static Car car;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpVehicleInstance() {
|
||||
vehicle = new Vehicle();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpCarInstance() {
|
||||
car = new Car();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledAccelerate_thenOneAssertion() {
|
||||
assertThat(vehicle.accelerate(100)).isEqualTo("The vehicle accelerates at : 100 MPH.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledRun_thenOneAssertion() {
|
||||
assertThat(vehicle.run()).isEqualTo("The vehicle is running.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledStop_thenOneAssertion() {
|
||||
assertThat(vehicle.stop()).isEqualTo("The vehicle has stopped.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledAccelerate_thenOneAssertion() {
|
||||
assertThat(car.accelerate(80)).isEqualTo("The car accelerates at : 80 MPH.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledRun_thenOneAssertion() {
|
||||
assertThat(car.run()).isEqualTo("The vehicle is running.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledStop_thenOneAssertion() {
|
||||
assertThat(car.stop()).isEqualTo("The vehicle has stopped.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledAccelerateWithSameArgument_thenNotEqual() {
|
||||
assertThat(vehicle.accelerate(100)).isNotEqualTo(car.accelerate(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledRun_thenEqual() {
|
||||
assertThat(vehicle.run()).isEqualTo(car.run());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledStop_thenEqual() {
|
||||
assertThat(vehicle.stop()).isEqualTo(car.stop());
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ExampleResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenGetBundleExampleResourceForLocalePlPl_thenItShouldInheritPropertiesGreetingAndLanguage() {
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
|
||||
ResourceBundle exampleBundle = ResourceBundle.getBundle("com.baeldung.resourcebundle.ExampleResource", plLocale);
|
||||
|
||||
assertTrue(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("toUsdRate", "cities", "greeting", "currency", "language")));
|
||||
assertEquals(exampleBundle.getString("greeting"), "cześć");
|
||||
assertEquals(exampleBundle.getObject("toUsdRate"), new BigDecimal("3.401"));
|
||||
assertArrayEquals(exampleBundle.getStringArray("cities"), new String[] { "Warsaw", "Cracow" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBundleExampleResourceForLocaleUs_thenItShouldContainOnlyGreeting() {
|
||||
Locale usLocale = Locale.US;
|
||||
|
||||
ResourceBundle exampleBundle = ResourceBundle.getBundle("com.baeldung.resourcebundle.ExampleResource", usLocale);
|
||||
|
||||
assertFalse(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("toUsdRate", "cities", "currency", "language")));
|
||||
assertTrue(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("greeting")));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PropertyResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLocaleUsAsDefualt_whenGetBundleForLocalePlPl_thenItShouldContain3ButtonsAnd1Label() {
|
||||
Locale.setDefault(Locale.US);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("pl", "PL"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("backButton", "helloLabel", "cancelButton", "continueButton", "helloLabelNoEncoding")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleUsAsDefualt_whenGetBundleForLocaleFrFr_thenItShouldContainKeys1To3AndKey4() {
|
||||
Locale.setDefault(Locale.US);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("deleteButton", "helloLabel", "cancelButton", "continueButton")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleChinaAsDefualt_whenGetBundleForLocaleFrFr_thenItShouldOnlyContainKeys1To3() {
|
||||
Locale.setDefault(Locale.CHINA);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("continueButton", "helloLabel", "cancelButton")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleChinaAsDefualt_whenGetBundleForLocaleFrFrAndExampleControl_thenItShouldOnlyContainKey5() {
|
||||
Locale.setDefault(Locale.CHINA);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"), new ExampleControl());
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("backButton", "helloLabel")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValuesDifferentlyEncoded_whenGetBundleForLocalePlPl_thenItShouldContain3ButtonsAnd1Label() {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("pl", "PL"));
|
||||
|
||||
assertEquals(bundle.getString("helloLabel"), "cześć");
|
||||
assertEquals(bundle.getString("helloLabelNoEncoding"), "czeÅ\u009BÄ\u0087");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,97 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PalindromeTest {
|
||||
|
||||
private String[] words = {
|
||||
"Anna",
|
||||
"Civic",
|
||||
"Kayak",
|
||||
"Level",
|
||||
"Madam",
|
||||
};
|
||||
|
||||
private String[] sentences = {
|
||||
"Sore was I ere I saw Eros",
|
||||
"Euston saw I was not Sue",
|
||||
"Too hot to hoot",
|
||||
"No mists or frost Simon",
|
||||
"Stella won no wallets"
|
||||
};
|
||||
|
||||
private Palindrome palindrome = new Palindrome();
|
||||
|
||||
@Test
|
||||
public void whenWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindrome(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindrome(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeReverseTheString(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeReverseTheString(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilderWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuilder(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilderSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBufferWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuffer(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBufferSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeRecursive_wordShouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeRecursive(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeRecursive_sentenceShouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeRecursive(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeStreams_wordShouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingIntStream(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeStreams_sentenceShouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingIntStream(sentence));
|
||||
}
|
||||
}
|
@ -0,0 +1,154 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringComparisonTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingComparisonOperator_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using comparison operator";
|
||||
String string2 = "using comparison operator";
|
||||
String string3 = new String("using comparison operator");
|
||||
|
||||
assertThat(string1 == string2).isTrue();
|
||||
assertThat(string1 == string3).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsMethod_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using equals method";
|
||||
String string2 = "using equals method";
|
||||
|
||||
String string3 = "using EQUALS method";
|
||||
String string4 = new String("using equals method");
|
||||
|
||||
assertThat(string1.equals(string2)).isTrue();
|
||||
assertThat(string1.equals(string4)).isTrue();
|
||||
|
||||
assertThat(string1.equals(null)).isFalse();
|
||||
assertThat(string1.equals(string3)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using equals ignore case";
|
||||
String string2 = "USING EQUALS IGNORE CASE";
|
||||
|
||||
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareTo_ThenComparingStrings(){
|
||||
|
||||
String author = "author";
|
||||
String book = "book";
|
||||
String duplicateBook = "book";
|
||||
|
||||
assertThat(author.compareTo(book)).isEqualTo(-1);
|
||||
assertThat(book.compareTo(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareTo(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
String author = "Author";
|
||||
String book = "book";
|
||||
String duplicateBook = "BOOK";
|
||||
|
||||
assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1);
|
||||
assertThat(book.compareToIgnoreCase(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using objects equals";
|
||||
String string2 = "using objects equals";
|
||||
String string3 = new String("using objects equals");
|
||||
|
||||
assertThat(Objects.equals(string1, string2)).isTrue();
|
||||
assertThat(Objects.equals(string1, string3)).isTrue();
|
||||
|
||||
assertThat(Objects.equals(null, null)).isTrue();
|
||||
assertThat(Objects.equals(null, string1)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equals(null, null)).isTrue();
|
||||
assertThat(StringUtils.equals(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equals("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyOf_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsAny(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(
|
||||
"equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompare_thenComparingStringsWithNulls(){
|
||||
|
||||
assertThat(StringUtils.compare(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1);
|
||||
assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1);
|
||||
assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
@ -17,4 +17,4 @@
|
||||
- [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes)
|
||||
- [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
|
||||
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
|
||||
|
||||
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions)
|
||||
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class InfixFunctionsTest {
|
||||
@Test
|
||||
fun testColours() {
|
||||
val color = 0x123456
|
||||
val red = (color and 0xff0000) shr 16
|
||||
val green = (color and 0x00ff00) shr 8
|
||||
val blue = (color and 0x0000ff) shr 0
|
||||
|
||||
Assert.assertEquals(0x12, red)
|
||||
Assert.assertEquals(0x34, green)
|
||||
Assert.assertEquals(0x56, blue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNewAssertions() {
|
||||
class Assertion<T>(private val target: T) {
|
||||
infix fun isEqualTo(other: T) {
|
||||
Assert.assertEquals(other, target)
|
||||
}
|
||||
|
||||
infix fun isDifferentFrom(other: T) {
|
||||
Assert.assertNotEquals(other, target)
|
||||
}
|
||||
}
|
||||
|
||||
val result = Assertion(5)
|
||||
|
||||
result isEqualTo 5
|
||||
|
||||
// The following two lines are expected to fail
|
||||
// result isEqualTo 6
|
||||
// result isDifferentFrom 5
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNewStringMethod() {
|
||||
infix fun String.substringMatches(r: Regex) : List<String> {
|
||||
return r.findAll(this)
|
||||
.map { it.value }
|
||||
.toList()
|
||||
}
|
||||
|
||||
val matches = "a bc def" substringMatches ".*? ".toRegex()
|
||||
Assert.assertEquals(listOf("a ", "bc "), matches)
|
||||
}
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
package com.baeldung.kotlin.stdlib
|
||||
|
||||
import org.junit.Test
|
||||
import java.beans.ExceptionListener
|
||||
import java.beans.XMLEncoder
|
||||
import java.io.*
|
||||
import java.lang.Exception
|
||||
import kotlin.test.*
|
||||
import kotlin.text.RegexOption.*
|
||||
|
||||
class RegexTest {
|
||||
|
||||
@Test
|
||||
fun whenRegexIsInstantiated_thenIsEqualToToRegexMethod() {
|
||||
val pattern = """a([bc]+)d?\\"""
|
||||
|
||||
assertEquals(Regex.fromLiteral(pattern).pattern, pattern)
|
||||
assertEquals(pattern, Regex(pattern).pattern)
|
||||
assertEquals(pattern, pattern.toRegex().pattern)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRegexMatches_thenResultIsTrue() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
|
||||
assertTrue(regex.containsMatchIn("xabcdy"))
|
||||
assertTrue(regex.matches("abcd"))
|
||||
assertFalse(regex matches "xabcdy")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenCompletelyMatchingRegex_whenMatchResult_thenDestructuring() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
|
||||
assertNull(regex.matchEntire("xabcdy"))
|
||||
|
||||
val matchResult = regex.matchEntire("abbccbbd")
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
||||
assertEquals("bbccbb", matchResult.destructured.component1())
|
||||
assertNull(matchResult.next())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenGroups() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
var matchResult = regex.find("abcb abbd")
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
||||
assertEquals("abcb", matchResult.value)
|
||||
assertEquals(IntRange(0, 3), matchResult.range)
|
||||
assertEquals(listOf("abcb", "bcb"), matchResult.groupValues)
|
||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
||||
|
||||
matchResult = matchResult.next()
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals("abbd", matchResult!!.value)
|
||||
assertEquals("bb", matchResult.groupValues[1])
|
||||
|
||||
matchResult = matchResult.next()
|
||||
|
||||
assertNull(matchResult)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenDestructuring() {
|
||||
val regex = """([\w\s]+) is (\d+) years old""".toRegex()
|
||||
val matchResult = regex.find("Mickey Mouse is 95 years old")
|
||||
val (name, age) = matchResult!!.destructured
|
||||
|
||||
assertEquals("Mickey Mouse", name)
|
||||
assertEquals("95", age)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenNonMatchingRegex_whenFindCalled_thenNull() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
val matchResult = regex.find("foo")
|
||||
|
||||
assertNull(matchResult)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenNonMatchingRegex_whenFindAllCalled_thenEmptySet() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
val matchResults = regex.findAll("foo")
|
||||
|
||||
assertNotNull(matchResults)
|
||||
assertTrue(matchResults.none())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReplace_thenReplacement() {
|
||||
val regex = """(red|green|blue)""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
val grim = regex.replace(beautiful, "dark")
|
||||
val shiny = regex.replaceFirst(beautiful, "rainbow")
|
||||
|
||||
assertEquals("Roses are dark, Violets are dark", grim)
|
||||
assertEquals("Roses are rainbow, Violets are blue", shiny)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenComplexReplace_thenReplacement() {
|
||||
val regex = """(red|green|blue)""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
val reallyBeautiful = regex.replace(beautiful) {
|
||||
matchResult -> matchResult.value.toUpperCase() + "!"
|
||||
}
|
||||
|
||||
assertEquals("Roses are RED!, Violets are BLUE!", reallyBeautiful)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSplit_thenList() {
|
||||
val regex = """\W+""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
|
||||
assertEquals(listOf("Roses", "are", "red", "Violets", "are", "blue"), regex.split(beautiful))
|
||||
assertEquals(listOf("Roses", "are", "red", "Violets are blue"), regex.split(beautiful, 4))
|
||||
assertEquals(regex.toPattern().split(beautiful).asList(), regex.split(beautiful))
|
||||
}
|
||||
|
||||
}
|
@ -129,7 +129,7 @@
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.9.2</jackson.version>
|
||||
<jackson.version>2.9.4</jackson.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.controller;
|
||||
|
||||
import com.baeldung.service.StudentService;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(name = "StudentServlet", urlPatterns = "/student-record")
|
||||
public class StudentServlet extends HttpServlet {
|
||||
|
||||
private final StudentService studentService = new StudentService();
|
||||
|
||||
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
String studentID = request.getParameter("id");
|
||||
if (studentID != null) {
|
||||
int id = Integer.parseInt(studentID);
|
||||
studentService.getStudent(id)
|
||||
.ifPresent(s -> request.setAttribute("studentRecord", s));
|
||||
}
|
||||
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/student-record.jsp");
|
||||
dispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
}
|
39
javax-servlets/src/main/java/com/baeldung/model/Student.java
Normal file
39
javax-servlets/src/main/java/com/baeldung/model/Student.java
Normal file
@ -0,0 +1,39 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Student {
|
||||
|
||||
private int id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Student(int id, String firstName, String lastName) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.model.Student;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class StudentService {
|
||||
|
||||
public Optional<Student> getStudent(int id) {
|
||||
switch (id) {
|
||||
case 1:
|
||||
return Optional.of(new Student(1, "John", "Doe"));
|
||||
case 2:
|
||||
return Optional.of(new Student(2, "Jane", "Goodall"));
|
||||
case 3:
|
||||
return Optional.of(new Student(3, "Max", "Born"));
|
||||
default:
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,7 +1,6 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@ -13,7 +12,7 @@ public class FormServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
throws IOException {
|
||||
|
||||
String height = request.getParameter("height");
|
||||
String weight = request.getParameter("weight");
|
||||
@ -25,23 +24,20 @@ public class FormServlet extends HttpServlet {
|
||||
response.setHeader("Test", "Success");
|
||||
response.setHeader("BMI", String.valueOf(bmi));
|
||||
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
|
||||
dispatcher.forward(request, response);
|
||||
} catch (Exception e) {
|
||||
|
||||
response.sendRedirect("index.jsp");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
// do something else here
|
||||
}
|
||||
|
||||
private Double calculateBMI(Double weight, Double height) {
|
||||
|
||||
return weight / (height * height);
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
|
||||
<%@ page import="com.baeldung.model.Student"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Student Record</title>
|
||||
</head>
|
||||
<body>
|
||||
<%
|
||||
if (request.getAttribute("studentRecord") != null) {
|
||||
Student student = (Student) request.getAttribute("studentRecord");
|
||||
%>
|
||||
|
||||
<h1>Student Record</h1>
|
||||
<div>
|
||||
ID:
|
||||
<%=student.getId()%></div>
|
||||
<div>
|
||||
First Name:
|
||||
<%=student.getFirstName()%></div>
|
||||
<div>
|
||||
Last Name:
|
||||
<%=student.getLastName()%></div>
|
||||
|
||||
<%
|
||||
} else {
|
||||
%>
|
||||
<h1>No student record found.</h1>
|
||||
<%
|
||||
}
|
||||
%>
|
||||
</body>
|
||||
</html>
|
@ -6,10 +6,11 @@
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<validation-api.version>2.0.0.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@ -21,12 +22,6 @@
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${validation-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
@ -50,6 +45,16 @@
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
@ -0,0 +1,38 @@
|
||||
package org.baeldung.javaxval.methodvalidation;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.model.Customer;
|
||||
import org.baeldung.javaxval.methodvalidation.model.Reservation;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({ "org.baeldung.javaxval.methodvalidation.model" })
|
||||
public class MethodValidationConfig {
|
||||
|
||||
@Bean
|
||||
public MethodValidationPostProcessor methodValidationPostProcessor() {
|
||||
return new MethodValidationPostProcessor();
|
||||
}
|
||||
|
||||
@Bean("customer")
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public Customer customer(String firstName, String lastName) {
|
||||
|
||||
Customer customer = new Customer(firstName, lastName);
|
||||
return customer;
|
||||
}
|
||||
|
||||
@Bean("reservation")
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public Reservation reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
|
||||
|
||||
Reservation reservation = new Reservation(begin, end, customer, room);
|
||||
return reservation;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package org.baeldung.javaxval.methodvalidation.constraints;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import javax.validation.constraintvalidation.SupportedValidationTarget;
|
||||
import javax.validation.constraintvalidation.ValidationTarget;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
|
||||
public class ConsistentDateParameterValidator implements ConstraintValidator<ConsistentDateParameters, Object[]> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
|
||||
|
||||
if (value[0] == null || value[1] == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(value[0] instanceof LocalDate) || !(value[1] instanceof LocalDate)) {
|
||||
throw new IllegalArgumentException("Illegal method signature, expected two parameters of type LocalDate.");
|
||||
}
|
||||
|
||||
return ((LocalDate) value[0]).isAfter(LocalDate.now()) && ((LocalDate) value[0]).isBefore((LocalDate) value[1]);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package org.baeldung.javaxval.methodvalidation.constraints;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Constraint(validatedBy = ConsistentDateParameterValidator.class)
|
||||
@Target({ METHOD, CONSTRUCTOR })
|
||||
@Retention(RUNTIME)
|
||||
@Documented
|
||||
public @interface ConsistentDateParameters {
|
||||
|
||||
String message() default "End date must be after begin date and both must be in the future";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package org.baeldung.javaxval.methodvalidation.constraints;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.CONSTRUCTOR;
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Constraint(validatedBy = ValidReservationValidator.class)
|
||||
@Target({ METHOD, CONSTRUCTOR })
|
||||
@Retention(RUNTIME)
|
||||
@Documented
|
||||
public @interface ValidReservation {
|
||||
|
||||
String message() default "End date must be after begin date and both must be in the future, room number must be bigger than 0";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package org.baeldung.javaxval.methodvalidation.constraints;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.model.Reservation;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class ValidReservationValidator implements ConstraintValidator<ValidReservation, Reservation> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(Reservation reservation, ConstraintValidatorContext context) {
|
||||
|
||||
if (reservation == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(reservation instanceof Reservation)) {
|
||||
throw new IllegalArgumentException("Illegal method signature, expected parameter of type Reservation.");
|
||||
}
|
||||
|
||||
if (reservation.getBegin() == null || reservation.getEnd() == null || reservation.getCustomer() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (reservation.getBegin()
|
||||
.isAfter(LocalDate.now())
|
||||
&& reservation.getBegin()
|
||||
.isBefore(reservation.getEnd())
|
||||
&& reservation.getRoom() > 0);
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package org.baeldung.javaxval.methodvalidation.model;
|
||||
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Validated
|
||||
public class Customer {
|
||||
|
||||
@Size(min = 5, max = 200)
|
||||
private String firstName;
|
||||
|
||||
@Size(min = 5, max = 200)
|
||||
private String lastName;
|
||||
|
||||
public Customer(@Size(min = 5, max = 200) @NotNull String firstName, @Size(min = 5, max = 200) @NotNull String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Customer() {
|
||||
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package org.baeldung.javaxval.methodvalidation.model;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters;
|
||||
import org.baeldung.javaxval.methodvalidation.constraints.ValidReservation;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Positive;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Validated
|
||||
public class Reservation {
|
||||
|
||||
private LocalDate begin;
|
||||
|
||||
private LocalDate end;
|
||||
|
||||
@Valid
|
||||
private Customer customer;
|
||||
|
||||
@Positive
|
||||
private int room;
|
||||
|
||||
@ConsistentDateParameters
|
||||
@ValidReservation
|
||||
public Reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
|
||||
this.begin = begin;
|
||||
this.end = end;
|
||||
this.customer = customer;
|
||||
this.room = room;
|
||||
}
|
||||
|
||||
public LocalDate getBegin() {
|
||||
return begin;
|
||||
}
|
||||
|
||||
public void setBegin(LocalDate begin) {
|
||||
this.begin = begin;
|
||||
}
|
||||
|
||||
public LocalDate getEnd() {
|
||||
return end;
|
||||
}
|
||||
|
||||
public void setEnd(LocalDate end) {
|
||||
this.end = end;
|
||||
}
|
||||
|
||||
public Customer getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public void setCustomer(Customer customer) {
|
||||
this.customer = customer;
|
||||
}
|
||||
|
||||
public int getRoom() {
|
||||
return room;
|
||||
}
|
||||
|
||||
public void setRoom(int room) {
|
||||
this.room = room;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package org.baeldung.javaxval.methodvalidation.model;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters;
|
||||
import org.baeldung.javaxval.methodvalidation.constraints.ValidReservation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.*;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Controller
|
||||
@Validated
|
||||
public class ReservationManagement {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
@ConsistentDateParameters
|
||||
public void createReservation(LocalDate begin, LocalDate end, @NotNull Customer customer) {
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public void createReservation(@NotNull @Future LocalDate begin, @Min(1) int duration, @NotNull Customer customer) {
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public void createReservation(@Valid Reservation reservation) {
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
public List<@NotNull Customer> getAllCustomers() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Valid
|
||||
public Reservation getReservationById(int id) {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,97 @@
|
||||
package org.baeldung.javaxval.methodvalidation;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.model.Customer;
|
||||
import org.baeldung.javaxval.methodvalidation.model.Reservation;
|
||||
import org.baeldung.javaxval.methodvalidation.model.ReservationManagement;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { MethodValidationConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class ContainerValidationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
ReservationManagement reservationManagement;
|
||||
|
||||
@Rule
|
||||
public final ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidMethodParameters_thenConstraintViolationException() {
|
||||
|
||||
exception.expect(ConstraintViolationException.class);
|
||||
reservationManagement.createReservation(LocalDate.now(), 0, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidMethodParameters_thenNoException() {
|
||||
|
||||
reservationManagement.createReservation(LocalDate.now()
|
||||
.plusDays(1), 1, new Customer("William", "Smith"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithInvalidParameters_thenConstraintViolationException() {
|
||||
|
||||
exception.expect(ConstraintViolationException.class);
|
||||
reservationManagement.createReservation(LocalDate.now(), LocalDate.now(), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithValidParameters_thenNoException() {
|
||||
|
||||
reservationManagement.createReservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
new Customer("William", "Smith"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidReturnValue_thenConstraintViolationException() {
|
||||
|
||||
exception.expect(ConstraintViolationException.class);
|
||||
List<Customer> list = reservationManagement.getAllCustomers();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidCascadedValue_thenConstraintViolationException() {
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setFirstName("John");
|
||||
customer.setLastName("Doe");
|
||||
Reservation reservation = new Reservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
customer, 1);
|
||||
|
||||
exception.expect(ConstraintViolationException.class);
|
||||
reservationManagement.createReservation(reservation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidCascadedValue_thenCNoException() {
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setFirstName("William");
|
||||
customer.setLastName("Smith");
|
||||
Reservation reservation = new Reservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
customer, 1);
|
||||
|
||||
reservationManagement.createReservation(reservation);
|
||||
}
|
||||
}
|
@ -0,0 +1,209 @@
|
||||
package org.baeldung.javaxval.methodvalidation;
|
||||
|
||||
import org.baeldung.javaxval.methodvalidation.model.Customer;
|
||||
import org.baeldung.javaxval.methodvalidation.model.Reservation;
|
||||
import org.baeldung.javaxval.methodvalidation.model.ReservationManagement;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.ValidatorFactory;
|
||||
import javax.validation.executable.ExecutableValidator;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationIntegrationTest {
|
||||
|
||||
private ExecutableValidator executableValidator;
|
||||
|
||||
@Before
|
||||
public void getExecutableValidator() {
|
||||
|
||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
this.executableValidator = factory.getValidator()
|
||||
.forExecutables();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidMethodParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class);
|
||||
Object[] parameterValues = { LocalDate.now(), 0, null };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(3, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidMethodParameters_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class);
|
||||
Object[] parameterValues = { LocalDate.now()
|
||||
.plusDays(1), 1, new Customer("John", "Doe") };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithInvalidParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class);
|
||||
Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("John", "Doe") };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithValidParameters_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class);
|
||||
Object[] parameterValues = { LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
new Customer("John", "Doe") };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Customer> constructor = Customer.class.getConstructor(String.class, String.class);
|
||||
Object[] parameterValues = { "John", "Doe" };
|
||||
Set<ConstraintViolation<Customer>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
|
||||
|
||||
assertEquals(2, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Customer> constructor = Customer.class.getConstructor(String.class, String.class);
|
||||
Object[] parameterValues = { "William", "Smith" };
|
||||
Set<ConstraintViolation<Customer>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
|
||||
Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 1 };
|
||||
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
|
||||
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCrossParameterValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
|
||||
Object[] parameterValues = { LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
new Customer("William", "Smith"), 1 };
|
||||
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("getAllCustomers");
|
||||
Object returnValue = Collections.<Customer> emptyList();
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateReturnValue(object, method, returnValue);
|
||||
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidReturnValue_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("getAllCustomers");
|
||||
Object returnValue = Collections.singletonList(new Customer("William", "Smith"));
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateReturnValue(object, method, returnValue);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidConstructorReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
|
||||
Reservation createdObject = new Reservation(LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 0);
|
||||
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject);
|
||||
|
||||
assertEquals(1, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidConstructorReturnValue_thenZeroVoilations() throws NoSuchMethodException {
|
||||
|
||||
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
|
||||
Reservation createdObject = new Reservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
new Customer("William", "Smith"), 1);
|
||||
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithInvalidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class);
|
||||
Customer customer = new Customer();
|
||||
customer.setFirstName("John");
|
||||
customer.setLastName("Doe");
|
||||
Reservation reservation = new Reservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
customer, 1);
|
||||
Object[] parameterValues = { reservation };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(2, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidationWithValidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
|
||||
|
||||
ReservationManagement object = new ReservationManagement();
|
||||
Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class);
|
||||
Customer customer = new Customer();
|
||||
customer.setFirstName("William");
|
||||
customer.setLastName("Smith");
|
||||
Reservation reservation = new Reservation(LocalDate.now()
|
||||
.plusDays(1),
|
||||
LocalDate.now()
|
||||
.plusDays(2),
|
||||
customer, 1);
|
||||
Object[] parameterValues = { reservation };
|
||||
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
|
||||
|
||||
assertEquals(0, violations.size());
|
||||
}
|
||||
|
||||
}
|
@ -100,21 +100,16 @@ public class JGroupsMessenger extends ReceiverAdapter {
|
||||
System.out.println("Received initial view:");
|
||||
newView.forEach(System.out::println);
|
||||
} else {
|
||||
|
||||
// Compare to last view
|
||||
System.out.println("Received new view.");
|
||||
|
||||
List<Address> newMembers = View.newMembers(lastView, newView);
|
||||
if (newMembers.size() > 0) {
|
||||
System.out.println("New members: ");
|
||||
newMembers.forEach(System.out::println);
|
||||
}
|
||||
System.out.println("New members: ");
|
||||
newMembers.forEach(System.out::println);
|
||||
|
||||
List<Address> exMembers = View.leftMembers(lastView, newView);
|
||||
if (exMembers.size() > 0) {
|
||||
System.out.println("Exited members:");
|
||||
exMembers.forEach(System.out::println);
|
||||
}
|
||||
System.out.println("Exited members:");
|
||||
exMembers.forEach(System.out::println);
|
||||
}
|
||||
lastView = newView;
|
||||
}
|
||||
@ -122,7 +117,7 @@ public class JGroupsMessenger extends ReceiverAdapter {
|
||||
/**
|
||||
* Loop on console input until we see 'x' to exit
|
||||
*/
|
||||
private void processInput() {
|
||||
private void processInput() throws Exception {
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
|
||||
while (running) {
|
||||
@ -138,13 +133,8 @@ public class JGroupsMessenger extends ReceiverAdapter {
|
||||
running = false;
|
||||
continue;
|
||||
} else if (!destinationName.isEmpty()) {
|
||||
Optional<Address> optDestination = getAddress(destinationName);
|
||||
if (optDestination.isPresent()) {
|
||||
destination = optDestination.get();
|
||||
} else {
|
||||
System.out.println("Destination not found, try again.");
|
||||
continue;
|
||||
}
|
||||
destination = getAddress(destinationName)
|
||||
. orElseThrow(() -> new Exception("Destination not found"));
|
||||
}
|
||||
|
||||
// Accept a string to send
|
||||
|
24
jsonld/.gitignore
vendored
Normal file
24
jsonld/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
nbproject/private/
|
||||
build/
|
||||
nbbuild/
|
||||
dist/
|
||||
nbdist/
|
||||
.nb-gradle/
|
BIN
jsonld/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
BIN
jsonld/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
Binary file not shown.
1
jsonld/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
1
jsonld/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@ -0,0 +1 @@
|
||||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
|
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