commit
fc2536b6ed
@ -0,0 +1,208 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class Board {
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(Board.class);
|
||||||
|
|
||||||
|
private final int[][] board;
|
||||||
|
|
||||||
|
private final int score;
|
||||||
|
|
||||||
|
public Board(int size) {
|
||||||
|
assert(size > 0);
|
||||||
|
|
||||||
|
this.board = new int[size][];
|
||||||
|
this.score = 0;
|
||||||
|
|
||||||
|
for (int x = 0; x < size; ++x) {
|
||||||
|
this.board[x] = new int[size];
|
||||||
|
for (int y = 0; y < size; ++y) {
|
||||||
|
board[x][y] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Board(int[][] board, int score) {
|
||||||
|
this.score = score;
|
||||||
|
this.board = new int[board.length][];
|
||||||
|
|
||||||
|
for (int x = 0; x < board.length; ++x) {
|
||||||
|
this.board[x] = Arrays.copyOf(board[x], board[x].length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSize() {
|
||||||
|
return board.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getScore() {
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCell(Cell cell) {
|
||||||
|
int x = cell.getX();
|
||||||
|
int y = cell.getY();
|
||||||
|
assert(x >= 0 && x < board.length);
|
||||||
|
assert(y >= 0 && y < board.length);
|
||||||
|
|
||||||
|
return board[x][y];
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty(Cell cell) {
|
||||||
|
return getCell(cell) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Cell> emptyCells() {
|
||||||
|
List<Cell> result = new ArrayList<>();
|
||||||
|
for (int x = 0; x < board.length; ++x) {
|
||||||
|
for (int y = 0; y < board[x].length; ++y) {
|
||||||
|
Cell cell = new Cell(x, y);
|
||||||
|
if (isEmpty(cell)) {
|
||||||
|
result.add(cell);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board placeTile(Cell cell, int number) {
|
||||||
|
if (!isEmpty(cell)) {
|
||||||
|
throw new IllegalArgumentException("That cell is not empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
Board result = new Board(this.board, this.score);
|
||||||
|
result.board[cell.getX()][cell.getY()] = number;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board move(Move move) {
|
||||||
|
// Clone the board
|
||||||
|
int[][] tiles = new int[this.board.length][];
|
||||||
|
for (int x = 0; x < this.board.length; ++x) {
|
||||||
|
tiles[x] = Arrays.copyOf(this.board[x], this.board[x].length);
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG.debug("Before move: {}", Arrays.deepToString(tiles));
|
||||||
|
// If we're doing an Left/Right move then transpose the board to make it a Up/Down move
|
||||||
|
if (move == Move.LEFT || move == Move.RIGHT) {
|
||||||
|
tiles = transpose(tiles);
|
||||||
|
LOG.debug("After transpose: {}", Arrays.deepToString(tiles));
|
||||||
|
}
|
||||||
|
// If we're doing a Right/Down move then reverse the board.
|
||||||
|
// With the above we're now always doing an Up move
|
||||||
|
if (move == Move.DOWN || move == Move.RIGHT) {
|
||||||
|
tiles = reverse(tiles);
|
||||||
|
LOG.debug("After reverse: {}", Arrays.deepToString(tiles));
|
||||||
|
}
|
||||||
|
LOG.debug("Ready to move: {}", Arrays.deepToString(tiles));
|
||||||
|
|
||||||
|
// Shift everything up
|
||||||
|
int[][] result = new int[tiles.length][];
|
||||||
|
int newScore = 0;
|
||||||
|
for (int x = 0; x < tiles.length; ++x) {
|
||||||
|
LinkedList<Integer> thisRow = new LinkedList<>();
|
||||||
|
for (int y = 0; y < tiles[0].length; ++y) {
|
||||||
|
if (tiles[x][y] > 0) {
|
||||||
|
thisRow.add(tiles[x][y]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG.debug("Unmerged row: {}", thisRow);
|
||||||
|
LinkedList<Integer> newRow = new LinkedList<>();
|
||||||
|
while (thisRow.size() >= 2) {
|
||||||
|
int first = thisRow.pop();
|
||||||
|
int second = thisRow.peek();
|
||||||
|
LOG.debug("Looking at numbers {} and {}", first, second);
|
||||||
|
if (second == first) {
|
||||||
|
LOG.debug("Numbers match, combining");
|
||||||
|
int newNumber = first * 2;
|
||||||
|
newRow.add(newNumber);
|
||||||
|
newScore += newNumber;
|
||||||
|
thisRow.pop();
|
||||||
|
} else {
|
||||||
|
LOG.debug("Numbers don't match");
|
||||||
|
newRow.add(first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newRow.addAll(thisRow);
|
||||||
|
LOG.debug("Merged row: {}", newRow);
|
||||||
|
|
||||||
|
result[x] = new int[tiles[0].length];
|
||||||
|
for (int y = 0; y < tiles[0].length; ++y) {
|
||||||
|
if (newRow.isEmpty()) {
|
||||||
|
result[x][y] = 0;
|
||||||
|
} else {
|
||||||
|
result[x][y] = newRow.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LOG.debug("After moves: {}", Arrays.deepToString(result));
|
||||||
|
|
||||||
|
// Un-reverse the board
|
||||||
|
if (move == Move.DOWN || move == Move.RIGHT) {
|
||||||
|
result = reverse(result);
|
||||||
|
LOG.debug("After reverse: {}", Arrays.deepToString(result));
|
||||||
|
}
|
||||||
|
// Un-transpose the board
|
||||||
|
if (move == Move.LEFT || move == Move.RIGHT) {
|
||||||
|
result = transpose(result);
|
||||||
|
LOG.debug("After transpose: {}", Arrays.deepToString(result));
|
||||||
|
}
|
||||||
|
return new Board(result, this.score + newScore);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[][] transpose(int[][] input) {
|
||||||
|
int[][] result = new int[input.length][];
|
||||||
|
|
||||||
|
for (int x = 0; x < input.length; ++x) {
|
||||||
|
result[x] = new int[input[0].length];
|
||||||
|
for (int y = 0; y < input[0].length; ++y) {
|
||||||
|
result[x][y] = input[y][x];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[][] reverse(int[][] input) {
|
||||||
|
int[][] result = new int[input.length][];
|
||||||
|
|
||||||
|
for (int x = 0; x < input.length; ++x) {
|
||||||
|
result[x] = new int[input[0].length];
|
||||||
|
for (int y = 0; y < input[0].length; ++y) {
|
||||||
|
result[x][y] = input[x][input.length - y - 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return Arrays.deepToString(board);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Board board1 = (Board) o;
|
||||||
|
return Arrays.deepEquals(board, board1.board);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Arrays.deepHashCode(board);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
public class Cell {
|
||||||
|
private int x;
|
||||||
|
private int y;
|
||||||
|
|
||||||
|
public Cell(int x, int y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getX() {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getY() {
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", Cell.class.getSimpleName() + "[", "]").add("x=" + x).add("y=" + y).toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class Computer {
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(Computer.class);
|
||||||
|
|
||||||
|
private final SecureRandom rng = new SecureRandom();
|
||||||
|
|
||||||
|
public Board makeMove(Board input) {
|
||||||
|
List<Cell> emptyCells = input.emptyCells();
|
||||||
|
LOG.info("Number of empty cells: {}", emptyCells.size());
|
||||||
|
|
||||||
|
double numberToPlace = rng.nextDouble();
|
||||||
|
LOG.info("New number probability: {}", numberToPlace);
|
||||||
|
|
||||||
|
int indexToPlace = rng.nextInt(emptyCells.size());
|
||||||
|
Cell cellToPlace = emptyCells.get(indexToPlace);
|
||||||
|
LOG.info("Placing number into empty cell: {}", cellToPlace);
|
||||||
|
|
||||||
|
return input.placeTile(cellToPlace, numberToPlace >= 0.9 ? 4 : 2);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,126 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.math3.util.Pair;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class Human {
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(Human.class);
|
||||||
|
|
||||||
|
public Board makeMove(Board input) {
|
||||||
|
// For each move in MOVE
|
||||||
|
// Generate board from move
|
||||||
|
// Generate Score for Board
|
||||||
|
// Return board with the best score
|
||||||
|
//
|
||||||
|
// Generate Score
|
||||||
|
// If Depth Limit
|
||||||
|
// Return Final Score
|
||||||
|
// Total Score = 0
|
||||||
|
// For every empty square in new board
|
||||||
|
// Generate board with "2" in square
|
||||||
|
// Calculate Score
|
||||||
|
// Total Score += (Score * 0.9)
|
||||||
|
// Generate board with "4" in square
|
||||||
|
// Calculate Score
|
||||||
|
// Total Score += (Score * 0.1)
|
||||||
|
//
|
||||||
|
// Calculate Score
|
||||||
|
// For each move in MOVE
|
||||||
|
// Generate board from move
|
||||||
|
// Generate score for board
|
||||||
|
// Return the best generated score
|
||||||
|
|
||||||
|
return Arrays.stream(Move.values())
|
||||||
|
.parallel()
|
||||||
|
.map(input::move)
|
||||||
|
.filter(board -> !board.equals(input))
|
||||||
|
.max(Comparator.comparingInt(board -> generateScore(board, 0)))
|
||||||
|
.orElse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int generateScore(Board board, int depth) {
|
||||||
|
if (depth >= 3) {
|
||||||
|
int finalScore = calculateFinalScore(board);
|
||||||
|
LOG.debug("Final score for board {}: {}", board,finalScore);
|
||||||
|
return finalScore;
|
||||||
|
}
|
||||||
|
|
||||||
|
return board.emptyCells().stream()
|
||||||
|
.parallel()
|
||||||
|
.flatMap(cell -> Stream.of(new Pair<>(cell, 2), new Pair<>(cell, 4)))
|
||||||
|
.mapToInt(move -> {
|
||||||
|
LOG.debug("Simulating move {} at depth {}", move, depth);
|
||||||
|
Board newBoard = board.placeTile(move.getFirst(), move.getSecond());
|
||||||
|
int boardScore = calculateScore(newBoard, depth + 1);
|
||||||
|
int calculatedScore = (int) (boardScore * (move.getSecond() == 2 ? 0.9 : 0.1));
|
||||||
|
LOG.debug("Calculated score for board {} and move {} at depth {}: {}", newBoard, move, depth, calculatedScore);
|
||||||
|
return calculatedScore;
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int calculateScore(Board board, int depth) {
|
||||||
|
return Arrays.stream(Move.values())
|
||||||
|
.parallel()
|
||||||
|
.map(board::move)
|
||||||
|
.filter(moved -> !moved.equals(board))
|
||||||
|
.mapToInt(newBoard -> generateScore(newBoard, depth))
|
||||||
|
.max()
|
||||||
|
.orElse(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int calculateFinalScore(Board board) {
|
||||||
|
List<List<Integer>> rowsToScore = new ArrayList<>();
|
||||||
|
for (int i = 0; i < board.getSize(); ++i) {
|
||||||
|
List<Integer> row = new ArrayList<>();
|
||||||
|
List<Integer> col = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int j = 0; j < board.getSize(); ++j) {
|
||||||
|
row.add(board.getCell(new Cell(i, j)));
|
||||||
|
col.add(board.getCell(new Cell(j, i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsToScore.add(row);
|
||||||
|
rowsToScore.add(col);
|
||||||
|
}
|
||||||
|
|
||||||
|
return rowsToScore.stream()
|
||||||
|
.parallel()
|
||||||
|
.mapToInt(row -> {
|
||||||
|
List<Integer> preMerged = row.stream()
|
||||||
|
.filter(value -> value != 0)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
int numMerges = 0;
|
||||||
|
int monotonicityLeft = 0;
|
||||||
|
int monotonicityRight = 0;
|
||||||
|
for (int i = 0; i < preMerged.size() - 1; ++i) {
|
||||||
|
Integer first = preMerged.get(i);
|
||||||
|
Integer second = preMerged.get(i + 1);
|
||||||
|
if (first.equals(second)) {
|
||||||
|
++numMerges;
|
||||||
|
} else if (first > second) {
|
||||||
|
monotonicityLeft += first - second;
|
||||||
|
} else {
|
||||||
|
monotonicityRight += second - first;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int score = 1000;
|
||||||
|
score += 250 * row.stream().filter(value -> value == 0).count();
|
||||||
|
score += 750 * numMerges;
|
||||||
|
score -= 10 * row.stream().mapToInt(value -> value).sum();
|
||||||
|
score -= 50 * Math.min(monotonicityLeft, monotonicityRight);
|
||||||
|
return score;
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
public enum Move {
|
||||||
|
UP,
|
||||||
|
DOWN,
|
||||||
|
LEFT,
|
||||||
|
RIGHT
|
||||||
|
}
|
@ -0,0 +1,73 @@
|
|||||||
|
package com.baeldung.algorithms.play2048;
|
||||||
|
|
||||||
|
public class Play2048 {
|
||||||
|
private static final int SIZE = 3;
|
||||||
|
private static final int INITIAL_NUMBERS = 2;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// The board and players
|
||||||
|
Board board = new Board(SIZE);
|
||||||
|
Computer computer = new Computer();
|
||||||
|
Human human = new Human();
|
||||||
|
|
||||||
|
// The computer has two moves first
|
||||||
|
System.out.println("Setup");
|
||||||
|
System.out.println("=====");
|
||||||
|
for (int i = 0; i < INITIAL_NUMBERS; ++i) {
|
||||||
|
board = computer.makeMove(board);
|
||||||
|
}
|
||||||
|
|
||||||
|
printBoard(board);
|
||||||
|
do {
|
||||||
|
board = human.makeMove(board);
|
||||||
|
System.out.println("Human move");
|
||||||
|
System.out.println("==========");
|
||||||
|
printBoard(board);
|
||||||
|
|
||||||
|
board = computer.makeMove(board);
|
||||||
|
System.out.println("Computer move");
|
||||||
|
System.out.println("=============");
|
||||||
|
printBoard(board);
|
||||||
|
} while (!board.emptyCells().isEmpty());
|
||||||
|
|
||||||
|
System.out.println("Final Score: " + board.getScore());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printBoard(Board board) {
|
||||||
|
StringBuilder topLines = new StringBuilder();
|
||||||
|
StringBuilder midLines = new StringBuilder();
|
||||||
|
for (int x = 0; x < board.getSize(); ++x) {
|
||||||
|
topLines.append("+--------");
|
||||||
|
midLines.append("| ");
|
||||||
|
}
|
||||||
|
topLines.append("+");
|
||||||
|
midLines.append("|");
|
||||||
|
|
||||||
|
|
||||||
|
for (int y = 0; y < board.getSize(); ++y) {
|
||||||
|
System.out.println(topLines);
|
||||||
|
System.out.println(midLines);
|
||||||
|
for (int x = 0; x < board.getSize(); ++x) {
|
||||||
|
Cell cell = new Cell(x, y);
|
||||||
|
System.out.print("|");
|
||||||
|
if (board.isEmpty(cell)) {
|
||||||
|
System.out.print(" ");
|
||||||
|
} else {
|
||||||
|
StringBuilder output = new StringBuilder(Integer.toString(board.getCell(cell)));
|
||||||
|
while (output.length() < 8) {
|
||||||
|
output.append(" ");
|
||||||
|
if (output.length() < 8) {
|
||||||
|
output.insert(0, " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.print(output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println("|");
|
||||||
|
System.out.println(midLines);
|
||||||
|
}
|
||||||
|
System.out.println(topLines);
|
||||||
|
System.out.println("Score: " + board.getScore());
|
||||||
|
}
|
||||||
|
}
|
@ -15,9 +15,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||||||
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
|
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
|
||||||
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
|
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
|
||||||
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
||||||
- [Kruskal’s Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
|
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)
|
||||||
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
|
|
||||||
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
|
|
||||||
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
|
|
||||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
|
||||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
|
||||||
|
@ -25,12 +25,6 @@
|
|||||||
<artifactId>commons-math3</artifactId>
|
<artifactId>commons-math3</artifactId>
|
||||||
<version>${commons-math3.version}</version>
|
<version>${commons-math3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.projectlombok</groupId>
|
|
||||||
<artifactId>lombok</artifactId>
|
|
||||||
<version>${lombok.version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>pl.allegro.finance</groupId>
|
<groupId>pl.allegro.finance</groupId>
|
||||||
<artifactId>tradukisto</artifactId>
|
<artifactId>tradukisto</artifactId>
|
||||||
|
@ -2,3 +2,9 @@
|
|||||||
|
|
||||||
- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
|
- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
|
||||||
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
|
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
|
||||||
|
- [Kruskal’s Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
|
||||||
|
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
|
||||||
|
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
|
||||||
|
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
|
||||||
|
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||||
|
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
|
||||||
|
@ -18,10 +18,35 @@
|
|||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>${guava.version}</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-commons</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${org.assertj.core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-math3</artifactId>
|
||||||
|
<version>${commons-math3.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<guava.version>28.1-jre</guava.version>
|
<guava.version>28.1-jre</guava.version>
|
||||||
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
|
<junit.platform.version>1.6.0</junit.platform.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package com.baeldung.algorithms.minheapmerge;
|
package com.baeldung.algorithms.minheapmerge;
|
||||||
|
|
||||||
public class HeapNode {
|
public class HeapNode {
|
||||||
|
|
||||||
int element;
|
int element;
|
||||||
int arrayIndex;
|
int arrayIndex;
|
||||||
int nextElementIndex = 1;
|
int nextElementIndex = 1;
|
||||||
|
|
||||||
public HeapNode(int element, int arrayIndex) {
|
public HeapNode(int element, int arrayIndex) {
|
||||||
this.element = element;
|
this.element = element;
|
||||||
this.arrayIndex = arrayIndex;
|
this.arrayIndex = arrayIndex;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,88 +1,88 @@
|
|||||||
package com.baeldung.algorithms.minheapmerge;
|
package com.baeldung.algorithms.minheapmerge;
|
||||||
|
|
||||||
public class MinHeap {
|
public class MinHeap {
|
||||||
|
|
||||||
HeapNode[] heapNodes;
|
HeapNode[] heapNodes;
|
||||||
|
|
||||||
public MinHeap(HeapNode heapNodes[]) {
|
public MinHeap(HeapNode heapNodes[]) {
|
||||||
this.heapNodes = heapNodes;
|
this.heapNodes = heapNodes;
|
||||||
heapifyFromLastLeafsParent();
|
heapifyFromLastLeafsParent();
|
||||||
}
|
}
|
||||||
|
|
||||||
void heapifyFromLastLeafsParent() {
|
void heapifyFromLastLeafsParent() {
|
||||||
int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length);
|
int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length);
|
||||||
while (lastLeafsParentIndex >= 0) {
|
while (lastLeafsParentIndex >= 0) {
|
||||||
heapify(lastLeafsParentIndex);
|
heapify(lastLeafsParentIndex);
|
||||||
lastLeafsParentIndex--;
|
lastLeafsParentIndex--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void heapify(int index) {
|
void heapify(int index) {
|
||||||
int leftNodeIndex = getLeftNodeIndex(index);
|
int leftNodeIndex = getLeftNodeIndex(index);
|
||||||
int rightNodeIndex = getRightNodeIndex(index);
|
int rightNodeIndex = getRightNodeIndex(index);
|
||||||
int smallestElementIndex = index;
|
int smallestElementIndex = index;
|
||||||
if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) {
|
if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) {
|
||||||
smallestElementIndex = leftNodeIndex;
|
smallestElementIndex = leftNodeIndex;
|
||||||
}
|
}
|
||||||
if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) {
|
if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) {
|
||||||
smallestElementIndex = rightNodeIndex;
|
smallestElementIndex = rightNodeIndex;
|
||||||
}
|
}
|
||||||
if (smallestElementIndex != index) {
|
if (smallestElementIndex != index) {
|
||||||
swap(index, smallestElementIndex);
|
swap(index, smallestElementIndex);
|
||||||
heapify(smallestElementIndex);
|
heapify(smallestElementIndex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int getParentNodeIndex(int index) {
|
int getParentNodeIndex(int index) {
|
||||||
return (index - 1) / 2;
|
return (index - 1) / 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
int getLeftNodeIndex(int index) {
|
int getLeftNodeIndex(int index) {
|
||||||
return (2 * index + 1);
|
return (2 * index + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
int getRightNodeIndex(int index) {
|
int getRightNodeIndex(int index) {
|
||||||
return (2 * index + 2);
|
return (2 * index + 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
HeapNode getRootNode() {
|
HeapNode getRootNode() {
|
||||||
return heapNodes[0];
|
return heapNodes[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
void heapifyFromRoot() {
|
void heapifyFromRoot() {
|
||||||
heapify(0);
|
heapify(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void swap(int i, int j) {
|
void swap(int i, int j) {
|
||||||
HeapNode temp = heapNodes[i];
|
HeapNode temp = heapNodes[i];
|
||||||
heapNodes[i] = heapNodes[j];
|
heapNodes[i] = heapNodes[j];
|
||||||
heapNodes[j] = temp;
|
heapNodes[j] = temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
static int[] merge(int[][] array) {
|
static int[] merge(int[][] array) {
|
||||||
HeapNode[] heapNodes = new HeapNode[array.length];
|
HeapNode[] heapNodes = new HeapNode[array.length];
|
||||||
int resultingArraySize = 0;
|
int resultingArraySize = 0;
|
||||||
|
|
||||||
for (int i = 0; i < array.length; i++) {
|
for (int i = 0; i < array.length; i++) {
|
||||||
HeapNode node = new HeapNode(array[i][0], i);
|
HeapNode node = new HeapNode(array[i][0], i);
|
||||||
heapNodes[i] = node;
|
heapNodes[i] = node;
|
||||||
resultingArraySize += array[i].length;
|
resultingArraySize += array[i].length;
|
||||||
}
|
}
|
||||||
|
|
||||||
MinHeap minHeap = new MinHeap(heapNodes);
|
MinHeap minHeap = new MinHeap(heapNodes);
|
||||||
int[] resultingArray = new int[resultingArraySize];
|
int[] resultingArray = new int[resultingArraySize];
|
||||||
|
|
||||||
for (int i = 0; i < resultingArraySize; i++) {
|
for (int i = 0; i < resultingArraySize; i++) {
|
||||||
HeapNode root = minHeap.getRootNode();
|
HeapNode root = minHeap.getRootNode();
|
||||||
resultingArray[i] = root.element;
|
resultingArray[i] = root.element;
|
||||||
|
|
||||||
if (root.nextElementIndex < array[root.arrayIndex].length) {
|
if (root.nextElementIndex < array[root.arrayIndex].length) {
|
||||||
root.element = array[root.arrayIndex][root.nextElementIndex++];
|
root.element = array[root.arrayIndex][root.nextElementIndex++];
|
||||||
} else {
|
} else {
|
||||||
root.element = Integer.MAX_VALUE;
|
root.element = Integer.MAX_VALUE;
|
||||||
}
|
}
|
||||||
minHeap.heapifyFromRoot();
|
minHeap.heapifyFromRoot();
|
||||||
}
|
}
|
||||||
return resultingArray;
|
return resultingArray;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,22 +1,22 @@
|
|||||||
package com.baeldung.algorithms.minheapmerge;
|
package com.baeldung.algorithms.minheapmerge;
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import static org.hamcrest.CoreMatchers.is;
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class MinHeapUnitTest {
|
public class MinHeapUnitTest {
|
||||||
|
|
||||||
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
|
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
|
||||||
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
|
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
|
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
|
||||||
int[] resultArray = MinHeap.merge(inputArray);
|
int[] resultArray = MinHeap.merge(inputArray);
|
||||||
|
|
||||||
assertThat(resultArray.length, is(equalTo(10)));
|
assertThat(resultArray.length, is(equalTo(10)));
|
||||||
assertThat(resultArray, is(equalTo(expectedArray)));
|
assertThat(resultArray, is(equalTo(expectedArray)));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -3,7 +3,7 @@
|
|||||||
This module contains articles about Apache CXF
|
This module contains articles about Apache CXF
|
||||||
|
|
||||||
## Relevant Articles:
|
## Relevant Articles:
|
||||||
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
|
||||||
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
|
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
|
||||||
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
|
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
|
||||||
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
|
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
|
||||||
|
3
apache-cxf/cxf-aegis/README.md
Normal file
3
apache-cxf/cxf-aegis/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
@ -10,9 +10,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>parent-boot-2</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-boot-1</relativePath>
|
<relativePath>../parent-boot-2</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -1,11 +1,14 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.apache.shiro.SecurityUtils;
|
import org.apache.shiro.SecurityUtils;
|
||||||
import org.apache.shiro.authc.*;
|
import org.apache.shiro.authc.AuthenticationException;
|
||||||
|
import org.apache.shiro.authc.IncorrectCredentialsException;
|
||||||
|
import org.apache.shiro.authc.LockedAccountException;
|
||||||
|
import org.apache.shiro.authc.UnknownAccountException;
|
||||||
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
import org.apache.shiro.mgt.DefaultSecurityManager;
|
import org.apache.shiro.mgt.DefaultSecurityManager;
|
||||||
import org.apache.shiro.mgt.SecurityManager;
|
import org.apache.shiro.mgt.SecurityManager;
|
||||||
import org.apache.shiro.realm.Realm;
|
import org.apache.shiro.realm.Realm;
|
||||||
import org.apache.shiro.realm.text.IniRealm;
|
|
||||||
import org.apache.shiro.session.Session;
|
import org.apache.shiro.session.Session;
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
@ -1,16 +1,24 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.apache.shiro.authc.*;
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.apache.shiro.authc.AuthenticationException;
|
||||||
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
|
import org.apache.shiro.authc.AuthenticationToken;
|
||||||
|
import org.apache.shiro.authc.SimpleAuthenticationInfo;
|
||||||
|
import org.apache.shiro.authc.UnknownAccountException;
|
||||||
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
import org.apache.shiro.authz.AuthorizationInfo;
|
import org.apache.shiro.authz.AuthorizationInfo;
|
||||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||||
import org.apache.shiro.realm.jdbc.JdbcRealm;
|
import org.apache.shiro.realm.jdbc.JdbcRealm;
|
||||||
import org.apache.shiro.subject.PrincipalCollection;
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class MyCustomRealm extends JdbcRealm {
|
public class MyCustomRealm extends JdbcRealm {
|
||||||
|
|
||||||
|
@ -1,14 +1,15 @@
|
|||||||
package com.baeldung.shiro.permissions.custom;
|
package com.baeldung.shiro.permissions.custom;
|
||||||
|
|
||||||
import com.baeldung.MyCustomRealm;
|
|
||||||
import org.apache.shiro.SecurityUtils;
|
import org.apache.shiro.SecurityUtils;
|
||||||
import org.apache.shiro.authc.*;
|
import org.apache.shiro.authc.AuthenticationException;
|
||||||
|
import org.apache.shiro.authc.IncorrectCredentialsException;
|
||||||
|
import org.apache.shiro.authc.LockedAccountException;
|
||||||
|
import org.apache.shiro.authc.UnknownAccountException;
|
||||||
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
import org.apache.shiro.config.Ini;
|
import org.apache.shiro.config.Ini;
|
||||||
import org.apache.shiro.mgt.DefaultSecurityManager;
|
import org.apache.shiro.mgt.DefaultSecurityManager;
|
||||||
import org.apache.shiro.mgt.SecurityManager;
|
import org.apache.shiro.mgt.SecurityManager;
|
||||||
import org.apache.shiro.realm.Realm;
|
|
||||||
import org.apache.shiro.realm.text.IniRealm;
|
import org.apache.shiro.realm.text.IniRealm;
|
||||||
import org.apache.shiro.session.Session;
|
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
## Atomikos
|
## Atomikos
|
||||||
|
|
||||||
This module contains articles about Atomikos
|
This module contains articles about Atomikos
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Guide Transactions Using Atomikos]()
|
- [A Guide to Atomikos](https://www.baeldung.com/java-atomikos)
|
||||||
|
3
aws-app-sync/README.md
Normal file
3
aws-app-sync/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [AWS AppSync With Spring Boot](https://www.baeldung.com/aws-appsync-spring)
|
56
aws-app-sync/pom.xml
Normal file
56
aws-app-sync/pom.xml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>2.2.6.RELEASE</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>aws-app-sync</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>aws-app-sync</name>
|
||||||
|
|
||||||
|
<description>Spring Boot using AWS App Sync</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.awsappsync;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.BodyInserters;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class AppSyncClientHelper {
|
||||||
|
|
||||||
|
static String apiUrl = "<INSERT API URL HERE>";
|
||||||
|
static String apiKey = "<INSERT API KEY HERE>";
|
||||||
|
static String API_KEY_HEADER = "x-api-key";
|
||||||
|
|
||||||
|
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) {
|
||||||
|
return WebClient
|
||||||
|
.builder()
|
||||||
|
.baseUrl(apiUrl)
|
||||||
|
.defaultHeader(API_KEY_HEADER, apiKey)
|
||||||
|
.defaultHeader("Content-Type", "application/json")
|
||||||
|
.build()
|
||||||
|
.method(HttpMethod.POST)
|
||||||
|
.uri("/graphql")
|
||||||
|
.body(BodyInserters.fromValue(requestBody))
|
||||||
|
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
||||||
|
.acceptCharset(StandardCharsets.UTF_8)
|
||||||
|
.retrieve();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.awsappsync;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class AwsAppSyncApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(AwsAppSyncApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,74 @@
|
|||||||
|
package com.baeldung.awsappsync;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@Disabled
|
||||||
|
class AwsAppSyncApplicationTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenGraphQuery_whenListEvents_thenReturnAllEvents() {
|
||||||
|
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("query", "query ListEvents {"
|
||||||
|
+ " listEvents {"
|
||||||
|
+ " items {"
|
||||||
|
+ " id"
|
||||||
|
+ " name"
|
||||||
|
+ " where"
|
||||||
|
+ " when"
|
||||||
|
+ " description"
|
||||||
|
+ " }"
|
||||||
|
+ " }"
|
||||||
|
+ "}");
|
||||||
|
requestBody.put("variables", "");
|
||||||
|
requestBody.put("operationName", "ListEvents");
|
||||||
|
|
||||||
|
String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody)
|
||||||
|
.bodyToMono(String.class).block();
|
||||||
|
|
||||||
|
assertNotNull(bodyString);
|
||||||
|
assertTrue(bodyString.contains("My First Event"));
|
||||||
|
assertTrue(bodyString.contains("where"));
|
||||||
|
assertTrue(bodyString.contains("when"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenGraphAdd_whenMutation_thenReturnIdNameDesc() {
|
||||||
|
|
||||||
|
String queryString = "mutation add {"
|
||||||
|
+ " createEvent("
|
||||||
|
+ " name:\"My added GraphQL event\""
|
||||||
|
+ " where:\"Day 2\""
|
||||||
|
+ " when:\"Saturday night\""
|
||||||
|
+ " description:\"Studying GraphQL\""
|
||||||
|
+ " ){"
|
||||||
|
+ " id"
|
||||||
|
+ " name"
|
||||||
|
+ " description"
|
||||||
|
+ " }"
|
||||||
|
+ "}";
|
||||||
|
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("query", queryString);
|
||||||
|
requestBody.put("variables", "");
|
||||||
|
requestBody.put("operationName", "add");
|
||||||
|
|
||||||
|
WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody);
|
||||||
|
|
||||||
|
String bodyString = response.bodyToMono(String.class).block();
|
||||||
|
|
||||||
|
assertNotNull(bodyString);
|
||||||
|
assertTrue(bodyString.contains("My added GraphQL event"));
|
||||||
|
assertFalse(bodyString.contains("where"));
|
||||||
|
assertFalse(bodyString.contains("when"));
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +0,0 @@
|
|||||||
### Relevant Articles:
|
|
||||||
|
|
||||||
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)
|
|
@ -16,10 +16,6 @@
|
|||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts
|
|||||||
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
|
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
|
||||||
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
|
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
|
||||||
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
|
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
|
||||||
|
- [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type)
|
||||||
- [[<-- Prev]](/core-groovy)
|
- [[<-- Prev]](/core-groovy)
|
||||||
|
40
core-groovy-2/determine-datatype/pom.xml
Normal file
40
core-groovy-2/determine-datatype/pom.xml
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung.groovy</groupId>
|
||||||
|
<artifactId>determine-datatype</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<build>
|
||||||
|
<sourceDirectory>src</sourceDirectory>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.8.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmaven</groupId>
|
||||||
|
<artifactId>groovy-maven-plugin</artifactId>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<version>2.0.6</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<dependencies>
|
||||||
|
<!-- https://mvnrepository.com/artifact/org.junit/junit5-engine -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit</groupId>
|
||||||
|
<artifactId>junit5-engine</artifactId>
|
||||||
|
<version>5.0.0-ALPHA</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.groovy.determine.datatype
|
||||||
|
|
||||||
|
class Person {
|
||||||
|
|
||||||
|
private int ageAsInt
|
||||||
|
private Double ageAsDouble
|
||||||
|
private String ageAsString
|
||||||
|
|
||||||
|
Person() {}
|
||||||
|
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
|
||||||
|
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
|
||||||
|
Person(String ageAsString) { this.ageAsString = ageAsString}
|
||||||
|
}
|
||||||
|
class Student extends Person {}
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.groovy.determine.datatype;
|
||||||
|
|
||||||
|
import org.junit.Assert
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PersonTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
|
||||||
|
Person personObj = new Person(10)
|
||||||
|
Assert.assertTrue(personObj.ageAsInt instanceof Integer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
|
||||||
|
Person personObj = new Person(10.0)
|
||||||
|
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsString_thenReturnTrue() {
|
||||||
|
Person personObj = new Person("10 years")
|
||||||
|
Assert.assertTrue(personObj.ageAsString.class == String)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
|
||||||
|
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||||
|
Person personObj = new Person()
|
||||||
|
Assert.assertTrue(personObj instanceof Person)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||||
|
Student studentObj = new Student()
|
||||||
|
Assert.assertTrue(studentObj in Person)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
|
||||||
|
def ageList = ['ageAsString','ageAsDouble', 10]
|
||||||
|
Assert.assertTrue(ageList.class == ArrayList)
|
||||||
|
Assert.assertTrue(ageList.getClass() == ArrayList)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
|
||||||
|
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
|
||||||
|
Assert.assertFalse(ageMap.class == LinkedHashMap)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.determinedatatype
|
||||||
|
|
||||||
|
class Person {
|
||||||
|
|
||||||
|
private int ageAsInt
|
||||||
|
private Double ageAsDouble
|
||||||
|
private String ageAsString
|
||||||
|
|
||||||
|
Person() {}
|
||||||
|
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
|
||||||
|
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
|
||||||
|
Person(String ageAsString) { this.ageAsString = ageAsString}
|
||||||
|
}
|
||||||
|
class Student extends Person {}
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.determinedatatype
|
||||||
|
|
||||||
|
import org.junit.Assert
|
||||||
|
import org.junit.Test
|
||||||
|
import com.baeldung.determinedatatype.Person
|
||||||
|
|
||||||
|
public class PersonTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
|
||||||
|
Person personObj = new Person(10)
|
||||||
|
Assert.assertTrue(personObj.ageAsInt instanceof Integer)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
|
||||||
|
Person personObj = new Person(10.0)
|
||||||
|
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenParameterTypeIsString_thenReturnTrue() {
|
||||||
|
Person personObj = new Person("10 years")
|
||||||
|
Assert.assertTrue(personObj.ageAsString.class == String)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
|
||||||
|
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||||
|
Person personObj = new Person()
|
||||||
|
Assert.assertTrue(personObj instanceof Person)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||||
|
Student studentObj = new Student()
|
||||||
|
Assert.assertTrue(studentObj in Person)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
|
||||||
|
def ageList = ['ageAsString','ageAsDouble', 10]
|
||||||
|
Assert.assertTrue(ageList.class == ArrayList)
|
||||||
|
Assert.assertTrue(ageList.getClass() == ArrayList)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
|
||||||
|
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
|
||||||
|
Assert.assertFalse(ageMap.class == LinkedHashMap)
|
||||||
|
}
|
||||||
|
}
|
@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts
|
|||||||
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
|
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
|
||||||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
||||||
- [[More -->]](/core-groovy-2)
|
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
|
||||||
|
- [[More -->]](/core-groovy-2)
|
||||||
|
@ -8,3 +8,4 @@ This module contains articles about Java 14.
|
|||||||
- [Java Text Blocks](https://www.baeldung.com/java-text-blocks)
|
- [Java Text Blocks](https://www.baeldung.com/java-text-blocks)
|
||||||
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
|
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
|
||||||
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
|
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
|
||||||
|
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java14.helpfulnullpointerexceptions;
|
package com.baeldung.java14.npe;
|
||||||
|
|
||||||
public class HelpfulNullPointerException {
|
public class HelpfulNullPointerException {
|
||||||
|
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.java14.record;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record Person (String name, String address) {
|
||||||
|
|
||||||
|
public static String UNKNOWN_ADDRESS = "Unknown";
|
||||||
|
public static String UNNAMED = "Unnamed";
|
||||||
|
|
||||||
|
public Person {
|
||||||
|
Objects.requireNonNull(name);
|
||||||
|
Objects.requireNonNull(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Person(String name) {
|
||||||
|
this(name, UNKNOWN_ADDRESS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Person unnamed(String address) {
|
||||||
|
return new Person(UNNAMED, address);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,84 @@
|
|||||||
|
package com.baeldung.java14.foreign.api;
|
||||||
|
|
||||||
|
import jdk.incubator.foreign.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.hamcrest.core.Is.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.lang.invoke.VarHandle;
|
||||||
|
import java.nio.ByteOrder;
|
||||||
|
|
||||||
|
public class ForeignMemoryUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAValueIsSet_thenAccessTheValue() {
|
||||||
|
long value = 10;
|
||||||
|
MemoryAddress memoryAddress =
|
||||||
|
MemorySegment.allocateNative(8).baseAddress();
|
||||||
|
VarHandle varHandle = MemoryHandles.varHandle(long.class,
|
||||||
|
ByteOrder.nativeOrder());
|
||||||
|
varHandle.set(memoryAddress, value);
|
||||||
|
assertThat(varHandle.get(memoryAddress), is(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMultipleValuesAreSet_thenAccessAll() {
|
||||||
|
VarHandle varHandle = MemoryHandles.varHandle(int.class,
|
||||||
|
ByteOrder.nativeOrder());
|
||||||
|
|
||||||
|
try(MemorySegment memorySegment =
|
||||||
|
MemorySegment.allocateNative(100)) {
|
||||||
|
MemoryAddress base = memorySegment.baseAddress();
|
||||||
|
for(int i=0; i<25; i++) {
|
||||||
|
varHandle.set(base.addOffset((i*4)), i);
|
||||||
|
}
|
||||||
|
for(int i=0; i<25; i++) {
|
||||||
|
assertThat(varHandle.get(base.addOffset((i*4))), is(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() {
|
||||||
|
SequenceLayout sequenceLayout =
|
||||||
|
MemoryLayout.ofSequence(25,
|
||||||
|
MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder()));
|
||||||
|
VarHandle varHandle =
|
||||||
|
sequenceLayout.varHandle(long.class,
|
||||||
|
MemoryLayout.PathElement.sequenceElement());
|
||||||
|
|
||||||
|
try(MemorySegment memorySegment =
|
||||||
|
MemorySegment.allocateNative(sequenceLayout)) {
|
||||||
|
MemoryAddress base = memorySegment.baseAddress();
|
||||||
|
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
|
||||||
|
varHandle.set(base, i, i);
|
||||||
|
}
|
||||||
|
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
|
||||||
|
assertThat(varHandle.get(base, i), is(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSlicingMemorySegment_thenTheyCanBeAccessedIndividually() {
|
||||||
|
MemoryAddress memoryAddress =
|
||||||
|
MemorySegment.allocateNative(12).baseAddress();
|
||||||
|
MemoryAddress memoryAddress1 =
|
||||||
|
memoryAddress.segment().asSlice(0,4).baseAddress();
|
||||||
|
MemoryAddress memoryAddress2 =
|
||||||
|
memoryAddress.segment().asSlice(4,4).baseAddress();
|
||||||
|
MemoryAddress memoryAddress3 =
|
||||||
|
memoryAddress.segment().asSlice(8,4).baseAddress();
|
||||||
|
|
||||||
|
VarHandle intHandle =
|
||||||
|
MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
|
||||||
|
intHandle.set(memoryAddress1, Integer.MIN_VALUE);
|
||||||
|
intHandle.set(memoryAddress2, 0);
|
||||||
|
intHandle.set(memoryAddress3, Integer.MAX_VALUE);
|
||||||
|
|
||||||
|
assertThat(intHandle.get(memoryAddress1), is(Integer.MIN_VALUE));
|
||||||
|
assertThat(intHandle.get(memoryAddress2), is(0));
|
||||||
|
assertThat(intHandle.get(memoryAddress3), is(Integer.MAX_VALUE));
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java14.helpfulnullpointerexceptions;
|
package com.baeldung.java14.npe;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
@ -0,0 +1,150 @@
|
|||||||
|
package com.baeldung.java14.record;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PersonTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person1 = new Person(name, address);
|
||||||
|
Person person2 = new Person(name, address);
|
||||||
|
|
||||||
|
assertTrue(person1.equals(person2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentObject_whenEquals_thenNotEqual() {
|
||||||
|
|
||||||
|
Person person = new Person("John Doe", "100 Linda Ln.");
|
||||||
|
|
||||||
|
assertFalse(person.equals(new Object()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentName_whenEquals_thenPersonsNotEqual() {
|
||||||
|
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person1 = new Person("Jane Doe", address);
|
||||||
|
Person person2 = new Person("John Doe", address);
|
||||||
|
|
||||||
|
assertFalse(person1.equals(person2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentAddress_whenEquals_thenPersonsNotEqual() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
|
||||||
|
Person person1 = new Person(name, "100 Linda Ln.");
|
||||||
|
Person person2 = new Person(name, "200 London Ave.");
|
||||||
|
|
||||||
|
assertFalse(person1.equals(person2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSameNameAndAddress_whenHashCode_thenPersonsEqual() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person1 = new Person(name, address);
|
||||||
|
Person person2 = new Person(name, address);
|
||||||
|
|
||||||
|
assertEquals(person1.hashCode(), person2.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentObject_whenHashCode_thenNotEqual() {
|
||||||
|
|
||||||
|
Person person = new Person("John Doe", "100 Linda Ln.");
|
||||||
|
|
||||||
|
assertNotEquals(person.hashCode(), new Object().hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentName_whenHashCode_thenPersonsNotEqual() {
|
||||||
|
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person1 = new Person("Jane Doe", address);
|
||||||
|
Person person2 = new Person("John Doe", address);
|
||||||
|
|
||||||
|
assertNotEquals(person1.hashCode(), person2.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDifferentAddress_whenHashCode_thenPersonsNotEqual() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
|
||||||
|
Person person1 = new Person(name, "100 Linda Ln.");
|
||||||
|
Person person2 = new Person(name, "200 London Ave.");
|
||||||
|
|
||||||
|
assertNotEquals(person1.hashCode(), person2.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidNameAndAddress_whenGetNameAndAddress_thenExpectedValuesReturned() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person = new Person(name, address);
|
||||||
|
|
||||||
|
assertEquals(name, person.name());
|
||||||
|
assertEquals(address, person.address());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidNameAndAddress_whenToString_thenCorrectStringReturned() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person = new Person(name, address);
|
||||||
|
|
||||||
|
assertEquals("Person[name=" + name + ", address=" + address + "]", person.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNullName_whenConstruct_thenErrorThrown() {
|
||||||
|
new Person(null, "100 Linda Ln.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNullAddress_whenConstruct_thenErrorThrown() {
|
||||||
|
new Person("John Doe", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnknownAddress_whenConstructing_thenAddressPopulated() {
|
||||||
|
|
||||||
|
String name = "John Doe";
|
||||||
|
|
||||||
|
Person person = new Person(name);
|
||||||
|
|
||||||
|
assertEquals(name, person.name());
|
||||||
|
assertEquals(Person.UNKNOWN_ADDRESS, person.address());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnnamed_whenConstructingThroughFactory_thenNamePopulated() {
|
||||||
|
|
||||||
|
String address = "100 Linda Ln.";
|
||||||
|
|
||||||
|
Person person = Person.unnamed(address);
|
||||||
|
|
||||||
|
assertEquals(Person.UNNAMED, person.name());
|
||||||
|
assertEquals(address, person.address());
|
||||||
|
}
|
||||||
|
}
|
@ -8,12 +8,11 @@
|
|||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
<name>core-java-8-2</name>
|
<name>core-java-8-2</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-java</relativePath>
|
<relativePath>../</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
5
core-java-modules/core-java-8-datetime-2/README.md
Normal file
5
core-java-modules/core-java-8-datetime-2/README.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
|
||||||
|
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
|
||||||
|
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
@ -4,16 +4,15 @@
|
|||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-datetime-java8</artifactId>
|
<artifactId>core-java-8-datetime-2</artifactId>
|
||||||
<version>${project.parent.version}</version>
|
<version>${project.parent.version}</version>
|
||||||
<name>core-java-datetime-java8</name>
|
<name>core-java-8-datetime</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-java</relativePath>
|
<relativePath>../</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -42,7 +41,6 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<finalName>core-java-datetime-java8</finalName>
|
|
||||||
<resources>
|
<resources>
|
||||||
<resource>
|
<resource>
|
||||||
<directory>src/main/resources</directory>
|
<directory>src/main/resources</directory>
|
||||||
@ -64,8 +62,8 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>1.9</maven.compiler.source>
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
<joda-time.version>2.10</joda-time.version>
|
<joda-time.version>2.10</joda-time.version>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
@ -11,31 +11,31 @@ public class LocalDateExampleUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingOfMethod_thenLocalDate() {
|
public void givenValues_whenUsingOfMethod_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8));
|
assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() {
|
public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8));
|
assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingEpochDay_thenLocalDate() {
|
public void givenValues_whenUsingEpochDay_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getDateFromEpochDay(18269));
|
assertEquals("2020-01-08", date.getDateFromEpochDay(18269).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingYearDay_thenLocalDate() {
|
public void givenValues_whenUsingYearDay_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8));
|
assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingParse_thenLocalDate() {
|
public void givenValues_whenUsingParse_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getDateFromString("2020-01-08"));
|
assertEquals("2020-01-08", date.getDateFromString("2020-01-08").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() {
|
public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() {
|
||||||
assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy"));
|
assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy").toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -13,4 +13,4 @@ This module contains articles about the Date and Time API introduced with Java 8
|
|||||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||||
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
||||||
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
|
- [[Next -->]](/core-java-modules/core-java-datetime-java8-2)
|
@ -4,16 +4,15 @@
|
|||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-datetime-java8</artifactId>
|
<artifactId>core-java-8-datetime</artifactId>
|
||||||
<version>${project.parent.version}</version>
|
<version>${project.parent.version}</version>
|
||||||
<name>core-java-datetime-java8</name>
|
<name>core-java-8-datetime</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-java</relativePath>
|
<relativePath>../</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -64,8 +63,8 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>1.9</maven.compiler.source>
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
<joda-time.version>2.10</joda-time.version>
|
<joda-time.version>2.10</joda-time.version>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
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