Merge branch 'master' into feature/ktln-43/working-with-lists-in-kotlin
This commit is contained in:
commit
98194e3faa
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -5,21 +5,21 @@ import static com.baeldung.algorithms.quicksort.SortingUtils.swap;
|
|||
|
||||
public class DutchNationalFlagPartioning {
|
||||
|
||||
public static Partition partition(int[] a, int begin, int end) {
|
||||
public static Partition partition(int[] input, int begin, int end) {
|
||||
int lt = begin, current = begin, gt = end;
|
||||
int partitioningValue = a[begin];
|
||||
int partitioningValue = input[begin];
|
||||
|
||||
while (current <= gt) {
|
||||
int compareCurrent = compare(a[current], partitioningValue);
|
||||
int compareCurrent = compare(input[current], partitioningValue);
|
||||
switch (compareCurrent) {
|
||||
case -1:
|
||||
swap(a, current++, lt++);
|
||||
swap(input, current++, lt++);
|
||||
break;
|
||||
case 0:
|
||||
current++;
|
||||
break;
|
||||
case 1:
|
||||
swap(a, current, gt--);
|
||||
swap(input, current, gt--);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -9,3 +9,4 @@ This module contains articles about Java 14.
|
|||
- [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)
|
||||
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
|
||||
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
|
||||
|
|
|
@ -5,7 +5,7 @@ This module contains articles about the improvements to core Java features intro
|
|||
### Relevant Articles:
|
||||
|
||||
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
||||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaArraysToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfArray_whenTryingToConvertToString_thenNameOfClassIsShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfArray_whenUsingArraysToStringToConvert_thenValueOfObjectsAreShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfDeepArray_whenUsingArraysDeepToStringToConvert_thenValueOfInnerObjectsAreShown() {
|
||||
Object[] innerArray = { "We", "Are", "Inside" };
|
||||
Object[] arrayOfObjects = { "John", 2, innerArray };
|
||||
assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstanceOfDeepArray_whenUsingStreamsToConvert_thenValueOfObjectsAreShown() {
|
||||
Object[] arrayOfObjects = { "John", 2, true };
|
||||
List<String> listOfString = Stream.of(arrayOfObjects)
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(listOfString.toString(), "[John, 2, true]");
|
||||
}
|
||||
}
|
|
@ -13,4 +13,5 @@ This module contains articles about advanced topics about multithreading with co
|
|||
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
|
||||
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
|
||||
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
|
||||
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
|
||||
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
|
||||
|
|
|
@ -13,3 +13,4 @@ This module contains articles about concurrent Java collections
|
|||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
|
||||
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)
|
||||
|
|
|
@ -0,0 +1,82 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
|
||||
|
||||
public class TooManyOpenFilesExceptionLiveTest {
|
||||
|
||||
private File tempFile;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() throws IOException {
|
||||
tempFile = File.createTempFile("testForException", "tmp");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void tearDown() {
|
||||
System.gc();
|
||||
tempFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotClosingResoures_thenIOExceptionShouldBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
FileInputStream leakyHandle = new FileInputStream(tempFile);
|
||||
}
|
||||
Assertions.fail("Method Should Have Failed");
|
||||
} catch (IOException e) {
|
||||
assertTrue(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClosingResoures_thenIOExceptionShouldNotBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
FileInputStream nonLeakyHandle = null;
|
||||
try {
|
||||
nonLeakyHandle = new FileInputStream(tempFile);
|
||||
} finally {
|
||||
if (nonLeakyHandle != null) {
|
||||
nonLeakyHandle.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
Assertions.fail("Method Should Not Have Failed");
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTryWithResoures_thenIOExceptionShouldNotBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
try (FileInputStream nonLeakyHandle = new FileInputStream(tempFile)) {
|
||||
//Do something with the file
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
Assertions.fail("Method Should Not Have Failed");
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -51,14 +51,37 @@
|
|||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>${asm.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm-util</artifactId>
|
||||
<version>${asm.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.bcel</groupId>
|
||||
<artifactId>bcel</artifactId>
|
||||
<version>${bcel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jol</groupId>
|
||||
<artifactId>jol-core</artifactId>
|
||||
<version>${jol-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- instrumentation -->
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
<javaassist.version>3.27.0-GA</javaassist.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<sun.tools.version>1.8.0</sun.tools.version>
|
||||
<jol-core.version>0.10</jol-core.version>
|
||||
<asm.version>8.0.1</asm.version>
|
||||
<bcel.version>6.5.0</bcel.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.boolsize;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jol.info.ClassLayout;
|
||||
import org.openjdk.jol.vm.VM;
|
||||
|
||||
public class BooleanSizeUnitTest {
|
||||
|
||||
@Test
|
||||
public void printingTheVMDetails() {
|
||||
System.out.println(VM.current().details());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void printingTheBoolWrapper() {
|
||||
System.out.println(ClassLayout.parseClass(BooleanWrapper.class).toPrintable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void printingTheBoolArray() {
|
||||
boolean[] value = new boolean[3];
|
||||
|
||||
System.out.println(ClassLayout.parseInstance(value).toPrintable());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.boolsize;
|
||||
|
||||
class BooleanWrapper {
|
||||
private boolean value;
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.bytecode;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.bcel.Repository;
|
||||
import org.apache.bcel.classfile.JavaClass;
|
||||
import org.junit.Test;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.util.TraceClassVisitor;
|
||||
import javassist.ClassPool;
|
||||
import javassist.NotFoundException;
|
||||
import javassist.bytecode.ClassFile;
|
||||
|
||||
public class ViewBytecodeUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingASM_thenReadBytecode() throws IOException {
|
||||
ClassReader reader = new ClassReader("java.lang.Object");
|
||||
StringWriter sw = new StringWriter();
|
||||
TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(sw));
|
||||
reader.accept(tcv, 0);
|
||||
|
||||
assertTrue(sw.toString().contains("public class java/lang/Object"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBCEL_thenReadBytecode() throws ClassNotFoundException {
|
||||
JavaClass objectClazz = Repository.lookupClass("java.lang.Object");
|
||||
|
||||
assertEquals(objectClazz.getClassName(), "java.lang.Object");
|
||||
assertEquals(objectClazz.getMethods().length, 14);
|
||||
assertTrue(objectClazz.toString().contains("public class java.lang.Object"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJavassist_thenReadBytecode() throws NotFoundException {
|
||||
ClassPool cp = ClassPool.getDefault();
|
||||
ClassFile cf = cp.get("java.lang.Object").getClassFile();
|
||||
|
||||
assertEquals(cf.getName(), "java.lang.Object");
|
||||
assertEquals(cf.getMethods().size(), 14);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -6,7 +6,6 @@
|
|||
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
|
||||
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
|
||||
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
|
||||
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
|
||||
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)
|
||||
|
|
|
@ -7,3 +7,6 @@ This module contains articles about types in Java
|
|||
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
|
||||
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
|
||||
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
|
||||
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about Java operators
|
|||
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
|
||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and)
|
||||
- [Finding an Object’s Class in Java](https://www.baeldung.com/java-finding-class)
|
||||
|
|
|
@ -4,7 +4,6 @@ This module contains articles about core features in the Java language
|
|||
|
||||
### Relevant Articles:
|
||||
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
|
||||
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
|
||||
- [Recursion In Java](https://www.baeldung.com/java-recursion)
|
||||
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
|
||||
|
@ -12,8 +11,6 @@ This module contains articles about core features in the Java language
|
|||
- [Using Java Assertions](https://www.baeldung.com/java-assert)
|
||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
|
||||
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
|
||||
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
||||
|
|
|
@ -17,6 +17,15 @@ public class StringToIntOrIntegerUnitTest {
|
|||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
|
||||
String givenString = "101010";
|
||||
|
||||
int result = Integer.parseInt(givenString, 2);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
||||
String givenString = "42";
|
||||
|
@ -26,6 +35,15 @@ public class StringToIntOrIntegerUnitTest {
|
|||
assertThat(result).isEqualTo(new Integer(42));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
||||
String givenString = "101010";
|
||||
|
||||
Integer result = Integer.valueOf(givenString, 2);
|
||||
|
||||
assertThat(result).isEqualTo(new Integer(42));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
|
||||
for (int i = -128; i <= 127; i++) {
|
||||
|
|
|
@ -12,4 +12,5 @@ This module contains articles about core features in the Kotlin language.
|
|||
- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety)
|
||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||
- [If-Else Expression in Kotlin](https://www.baeldung.com/kotlin/if-else-expression)
|
||||
- [Checking Whether a lateinit var Is Initialized in Kotlin](https://www.baeldung.com/kotlin/checking-lateinit)
|
||||
- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang)
|
|
@ -5,5 +5,4 @@ This module contains articles about Drools
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Drools](https://www.baeldung.com/drools)
|
||||
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
|
||||
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)
|
||||
|
|
|
@ -16,12 +16,39 @@
|
|||
|
||||
<build>
|
||||
<finalName>guava-collections-map</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -13,8 +13,32 @@
|
|||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections-set</finalName>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -23,13 +47,10 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections-set</finalName>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -15,6 +15,25 @@
|
|||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
|
@ -27,7 +46,20 @@
|
|||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -44,16 +76,6 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
|
@ -61,6 +83,7 @@
|
|||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -4,6 +4,9 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>guava-io</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
<name>guava-io</name>
|
||||
|
||||
<parent>
|
||||
|
@ -15,12 +18,35 @@
|
|||
|
||||
<build>
|
||||
<finalName>guava-io</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -11,8 +11,11 @@ import java.io.FileOutputStream;
|
|||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
|
@ -31,6 +34,21 @@ import com.google.common.io.Resources;
|
|||
|
||||
public class GuavaIOUnitTest {
|
||||
|
||||
@After
|
||||
public void afterEach() throws Exception {
|
||||
deleteProducedFiles();
|
||||
}
|
||||
|
||||
private void deleteProducedFiles() throws IOException {
|
||||
deleteIfExists("test.out");
|
||||
deleteIfExists("test_copy.in");
|
||||
deleteIfExists("test_le.txt");
|
||||
}
|
||||
|
||||
private void deleteIfExists(String fileName) throws IOException {
|
||||
java.nio.file.Files.deleteIfExists(Paths.get("src", "test", "resources", fileName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteUsingFiles_thenWritten() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
|
@ -206,5 +224,4 @@ public class GuavaIOUnitTest {
|
|||
|
||||
assertEquals(value, result);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Hello world
|
|
@ -0,0 +1 @@
|
|||
Test
|
|
@ -0,0 +1,4 @@
|
|||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
|
@ -8,9 +8,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -8,9 +8,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -8,9 +8,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -4,13 +4,16 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<name>guava-modules</name>
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@ -19,4 +22,28 @@
|
|||
<module>guava-21</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -15,13 +15,45 @@
|
|||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>guava</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -30,18 +62,9 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -23,6 +23,16 @@
|
|||
<module>jackson-exceptions</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
|
@ -35,6 +45,22 @@
|
|||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -13,6 +13,25 @@
|
|||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-simple</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!--jackson for xml -->
|
||||
<dependency>
|
||||
|
@ -20,7 +39,20 @@
|
|||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -29,18 +61,9 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-simple</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -225,6 +225,12 @@
|
|||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- jhipster-needle-maven-add-dependency -->
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -16,5 +16,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
|
|||
- [Introduction to Takes](https://www.baeldung.com/java-takes)
|
||||
- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway)
|
||||
- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro)
|
||||
- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker)
|
||||
- More articles [[<-- prev]](/libraries-2) [[next -->]](/libraries-4)
|
||||
|
|
|
@ -1,84 +0,0 @@
|
|||
<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>coroutines-with-quasar</artifactId>
|
||||
<name>coroutines-with-quasar</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>libraries-concurrency</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-core</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-actors</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-reactive-streams</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>getClasspathFilenames</id>
|
||||
<goals>
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.quasar.App</mainClass>
|
||||
<workingDirectory>target/classes</workingDirectory>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<!-- Turn off before production -->
|
||||
<argument>-Dco.paralleluniverse.fibers.verifyInstrumentation=true</argument>
|
||||
|
||||
<!-- Quasar Agent -->
|
||||
<argument>-javaagent:${co.paralleluniverse:quasar-core:jar}</argument>
|
||||
|
||||
<!-- Classpath -->
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
|
||||
<!-- Main class -->
|
||||
<argument>com.baeldung.quasar.App</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>12</source>
|
||||
<target>12</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -5,7 +5,6 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>libraries-concurrency</artifactId>
|
||||
<name>libraries-concurrency</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -13,8 +12,70 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<!-- <module>coroutines-with-quasar</module> --><!-- we haven't upgraded to Java 12 -->
|
||||
</modules>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-core</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-actors</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-reactive-streams</artifactId>
|
||||
<version>0.8.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>getClasspathFilenames</id>
|
||||
<goals>
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.quasar.App</mainClass>
|
||||
<workingDirectory>target/classes</workingDirectory>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<!-- Turn off before production -->
|
||||
<argument>-Dco.paralleluniverse.fibers.verifyInstrumentation=true</argument>
|
||||
|
||||
<!-- Quasar Agent -->
|
||||
<argument>-javaagent:${co.paralleluniverse:quasar-core:jar}</argument>
|
||||
|
||||
<!-- Classpath -->
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
|
||||
<!-- Main class -->
|
||||
<argument>com.baeldung.quasar.App</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -12,6 +12,7 @@ This module contains articles about libraries for data processing in Java.
|
|||
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
|
||||
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
|
||||
- [Java-R Integration](https://www.baeldung.com/java-r-integration)
|
||||
- [Univocity Parsers](https://www.baeldung.com/java-univocity-parsers)
|
||||
- More articles: [[<-- prev]](/../libraries-data)
|
||||
|
||||
##### Building the project
|
||||
|
|
|
@ -153,7 +153,13 @@
|
|||
<artifactId>renjin-script-engine</artifactId>
|
||||
<version>${renjin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.kafka</groupId>
|
||||
<artifactId>kafka-clients</artifactId>
|
||||
<version>${kafka.version}</version>
|
||||
|
|
|
@ -151,6 +151,13 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender)
|
||||
- [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output)
|
||||
- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers)
|
||||
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Netflix Genie](https://www.baeldung.com/netflix-genie-intro)
|
|
@ -5,8 +5,6 @@ import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
|
|||
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
|
||||
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
|
@ -20,9 +18,6 @@ import io.netty.handler.codec.http.HttpObject;
|
|||
import io.netty.handler.codec.http.HttpRequest;
|
||||
import io.netty.handler.codec.http.HttpUtil;
|
||||
import io.netty.handler.codec.http.LastHttpContent;
|
||||
import io.netty.handler.codec.http.cookie.Cookie;
|
||||
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
|
||||
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
|
||||
import io.netty.util.CharsetUtil;
|
||||
|
||||
public class CustomHttpServerHandler extends SimpleChannelInboundHandler<Object> {
|
||||
|
@ -45,22 +40,20 @@ public class CustomHttpServerHandler extends SimpleChannelInboundHandler<Object>
|
|||
}
|
||||
|
||||
responseData.setLength(0);
|
||||
responseData.append(ResponseBuilder.addRequestAttributes(request));
|
||||
responseData.append(ResponseBuilder.addHeaders(request));
|
||||
responseData.append(ResponseBuilder.addParams(request));
|
||||
responseData.append(RequestUtils.formatParams(request));
|
||||
}
|
||||
|
||||
responseData.append(ResponseBuilder.addDecoderResult(request));
|
||||
responseData.append(RequestUtils.evaluateDecoderResult(request));
|
||||
|
||||
if (msg instanceof HttpContent) {
|
||||
HttpContent httpContent = (HttpContent) msg;
|
||||
|
||||
responseData.append(ResponseBuilder.addBody(httpContent));
|
||||
responseData.append(ResponseBuilder.addDecoderResult(request));
|
||||
responseData.append(RequestUtils.formatBody(httpContent));
|
||||
responseData.append(RequestUtils.evaluateDecoderResult(request));
|
||||
|
||||
if (msg instanceof LastHttpContent) {
|
||||
LastHttpContent trailer = (LastHttpContent) msg;
|
||||
responseData.append(ResponseBuilder.addLastResponse(request, trailer));
|
||||
responseData.append(RequestUtils.prepareLastResponse(request, trailer));
|
||||
writeResponse(ctx, trailer, responseData);
|
||||
}
|
||||
}
|
||||
|
@ -88,18 +81,6 @@ public class CustomHttpServerHandler extends SimpleChannelInboundHandler<Object>
|
|||
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
|
||||
}
|
||||
|
||||
String cookieString = request.headers()
|
||||
.get(HttpHeaderNames.COOKIE);
|
||||
if (cookieString != null) {
|
||||
Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
|
||||
if (!cookies.isEmpty()) {
|
||||
for (Cookie cookie : cookies) {
|
||||
httpResponse.headers()
|
||||
.add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.write(httpResponse);
|
||||
|
||||
if (!keepAlive) {
|
||||
|
|
|
@ -7,32 +7,15 @@ import java.util.Map.Entry;
|
|||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.handler.codec.DecoderResult;
|
||||
import io.netty.handler.codec.http.HttpContent;
|
||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||
import io.netty.handler.codec.http.HttpHeaders;
|
||||
import io.netty.handler.codec.http.HttpObject;
|
||||
import io.netty.handler.codec.http.HttpRequest;
|
||||
import io.netty.handler.codec.http.LastHttpContent;
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import io.netty.util.CharsetUtil;
|
||||
|
||||
class ResponseBuilder {
|
||||
class RequestUtils {
|
||||
|
||||
static StringBuilder addRequestAttributes(HttpRequest request) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
responseData.append("Version: ")
|
||||
.append(request.protocolVersion())
|
||||
.append("\r\n");
|
||||
responseData.append("Host: ")
|
||||
.append(request.headers()
|
||||
.get(HttpHeaderNames.HOST, "unknown"))
|
||||
.append("\r\n");
|
||||
responseData.append("URI: ")
|
||||
.append(request.uri())
|
||||
.append("\r\n\r\n");
|
||||
return responseData;
|
||||
}
|
||||
|
||||
static StringBuilder addParams(HttpRequest request) {
|
||||
static StringBuilder formatParams(HttpRequest request) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
|
||||
Map<String, List<String>> params = queryStringDecoder.parameters();
|
||||
|
@ -42,9 +25,9 @@ class ResponseBuilder {
|
|||
List<String> vals = p.getValue();
|
||||
for (String val : vals) {
|
||||
responseData.append("Parameter: ")
|
||||
.append(key)
|
||||
.append(key.toUpperCase())
|
||||
.append(" = ")
|
||||
.append(val)
|
||||
.append(val.toUpperCase())
|
||||
.append("\r\n");
|
||||
}
|
||||
}
|
||||
|
@ -53,24 +36,7 @@ class ResponseBuilder {
|
|||
return responseData;
|
||||
}
|
||||
|
||||
static StringBuilder addHeaders(HttpRequest request) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
HttpHeaders headers = request.headers();
|
||||
if (!headers.isEmpty()) {
|
||||
for (Map.Entry<String, String> header : headers) {
|
||||
CharSequence key = header.getKey();
|
||||
CharSequence value = header.getValue();
|
||||
responseData.append(key)
|
||||
.append(" = ")
|
||||
.append(value)
|
||||
.append("\r\n");
|
||||
}
|
||||
responseData.append("\r\n");
|
||||
}
|
||||
return responseData;
|
||||
}
|
||||
|
||||
static StringBuilder addBody(HttpContent httpContent) {
|
||||
static StringBuilder formatBody(HttpContent httpContent) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
ByteBuf content = httpContent.content();
|
||||
if (content.isReadable()) {
|
||||
|
@ -81,7 +47,7 @@ class ResponseBuilder {
|
|||
return responseData;
|
||||
}
|
||||
|
||||
static StringBuilder addDecoderResult(HttpObject o) {
|
||||
static StringBuilder evaluateDecoderResult(HttpObject o) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
DecoderResult result = o.decoderResult();
|
||||
|
||||
|
@ -94,7 +60,7 @@ class ResponseBuilder {
|
|||
return responseData;
|
||||
}
|
||||
|
||||
static StringBuilder addLastResponse(HttpRequest request, LastHttpContent trailer) {
|
||||
static StringBuilder prepareLastResponse(HttpRequest request, LastHttpContent trailer) {
|
||||
StringBuilder responseData = new StringBuilder();
|
||||
responseData.append("Good Bye!\r\n");
|
||||
|
|
@ -89,7 +89,7 @@ public class HttpServerLiveTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenGetSent_thenCookieReceivedInResponse() throws Exception {
|
||||
public void whenGetSent_thenResponseOK() throws Exception {
|
||||
DefaultFullHttpRequest request = createRequest(null);
|
||||
|
||||
channel.writeAndFlush(request);
|
||||
|
@ -98,9 +98,6 @@ public class HttpServerLiveTest {
|
|||
assertEquals(200, response.getStatus());
|
||||
assertEquals("HTTP/1.1", response.getVersion());
|
||||
|
||||
Map<String, String> headers = response.getHeaders();
|
||||
String cookies = headers.get("set-cookie");
|
||||
assertTrue(cookies.contains("my-cookie"));
|
||||
}
|
||||
|
||||
@After
|
||||
|
|
|
@ -32,11 +32,6 @@
|
|||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
|
|
@ -2,4 +2,4 @@
|
|||
|
||||
- [A Solid Guide to Solid Principles](https://www.baeldung.com/solid-principles)
|
||||
- [Single Responsibility Principle in Java](https://www.baeldung.com/java-single-responsibility-principle)
|
||||
|
||||
- [Open/Closed Principle in Java](https://www.baeldung.com/java-open-closed-principle)
|
||||
|
|
|
@ -5,3 +5,4 @@ This module contains articles about PDF files.
|
|||
### Relevant Articles:
|
||||
- [PDF Conversions in Java](https://www.baeldung.com/pdf-conversions-java)
|
||||
- [Creating PDF Files in Java](https://www.baeldung.com/java-pdf-creation)
|
||||
- [Generating PDF Files Using Thymeleaf](https://www.baeldung.com/thymeleaf-generate-pdf)
|
||||
|
|
|
@ -60,6 +60,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<h2.version>1.4.200</h2.version>
|
||||
<postgresql.version>42.2.5.jre7</postgresql.version>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
||||
|
|
|
@ -0,0 +1,93 @@
|
|||
package com.baeldung.genkeys;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JdbcInsertIdIntegrationTest {
|
||||
|
||||
private static final String QUERY = "insert into persons (name) values (?)";
|
||||
|
||||
private static Connection connection;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws Exception {
|
||||
connection = DriverManager.getConnection("jdbc:h2:mem:generated-keys", "sa", "");
|
||||
connection
|
||||
.createStatement()
|
||||
.execute("create table persons(id bigint auto_increment, name varchar(255))");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() throws SQLException {
|
||||
connection
|
||||
.createStatement()
|
||||
.execute("drop table persons");
|
||||
connection.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInsert_whenUsingAutoGenFlag_thenBeAbleToFetchTheIdAfterward() throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(QUERY, Statement.RETURN_GENERATED_KEYS)) {
|
||||
statement.setString(1, "Foo");
|
||||
int affectedRows = statement.executeUpdate();
|
||||
assertThat(affectedRows).isPositive();
|
||||
|
||||
try (ResultSet keys = statement.getGeneratedKeys()) {
|
||||
assertThat(keys.next()).isTrue();
|
||||
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInsert_whenUsingAutoGenFlagViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
String query = "insert into persons (name) values ('Foo')";
|
||||
int affectedRows = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
|
||||
assertThat(affectedRows).isPositive();
|
||||
|
||||
try (ResultSet keys = statement.getGeneratedKeys()) {
|
||||
assertThat(keys.next()).isTrue();
|
||||
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInsert_whenUsingReturningCols_thenBeAbleToFetchTheIdAfterward() throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(QUERY, new String[] { "id" })) {
|
||||
statement.setString(1, "Foo");
|
||||
int affectedRows = statement.executeUpdate();
|
||||
assertThat(affectedRows).isPositive();
|
||||
|
||||
try (ResultSet keys = statement.getGeneratedKeys()) {
|
||||
assertThat(keys.next()).isTrue();
|
||||
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInsert_whenUsingReturningColsViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
String query = "insert into persons (name) values ('Foo')";
|
||||
int affectedRows = statement.executeUpdate(query, new String[] { "id" });
|
||||
assertThat(affectedRows).isPositive();
|
||||
|
||||
try (ResultSet keys = statement.getGeneratedKeys()) {
|
||||
assertThat(keys.next()).isTrue();
|
||||
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -55,6 +55,12 @@
|
|||
<artifactId>hibernate-testing</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
|
|
@ -13,4 +13,5 @@ This module contains articles about the Java Persistence API (JPA) in Java.
|
|||
- [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type)
|
||||
- [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables)
|
||||
- [Constructing a JPA Query Between Unrelated Entities](https://www.baeldung.com/jpa-query-unrelated-entities)
|
||||
- [When Does JPA Set the Primary Key](https://www.baeldung.com/jpa-strategies-when-set-primary-key)
|
||||
- More articles: [[<-- prev]](/java-jpa)
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "app_admin")
|
||||
public class Admin {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
@Column(name = "admin_name")
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.SequenceGenerator;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "article")
|
||||
public class Article {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "article_gen")
|
||||
@SequenceGenerator(name = "article_gen", sequenceName = "article_seq")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "article_name")
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Table(name = "id_gen")
|
||||
@Entity
|
||||
public class IdGenerator {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "gen_name")
|
||||
private String gen_name;
|
||||
|
||||
@Column(name = "gen_value")
|
||||
private Long gen_value;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getGen_name() {
|
||||
return gen_name;
|
||||
}
|
||||
|
||||
public void setGen_name(String gen_name) {
|
||||
this.gen_name = gen_name;
|
||||
}
|
||||
|
||||
public Long getGen_value() {
|
||||
return gen_value;
|
||||
}
|
||||
|
||||
public void setGen_value(Long gen_value) {
|
||||
this.gen_value = gen_value;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.TableGenerator;
|
||||
|
||||
@Entity
|
||||
@Table(name = "task")
|
||||
public class Task {
|
||||
|
||||
@Id
|
||||
@TableGenerator(name = "id_generator", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_value", pkColumnValue = "task_gen", initialValue = 10000, allocationSize = 10)
|
||||
@GeneratedValue(strategy = GenerationType.TABLE, generator = "id_generator")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "app_user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_name")
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
|
@ -184,4 +184,29 @@
|
|||
value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2-primarykey">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.generateidvalue.Admin</class>
|
||||
<class>com.baeldung.jpa.generateidvalue.Article</class>
|
||||
<class>com.baeldung.jpa.generateidvalue.IdGenerator</class>
|
||||
<class>com.baeldung.jpa.generateidvalue.Task</class>
|
||||
<class>com.baeldung.jpa.generateidvalue.User</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="javax.persistence.sql-load-script-source"
|
||||
value="primary_key_generator.sql" />
|
||||
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
|
||||
<property name="eclipselink.ddl-generation.output-mode" value="database" />
|
||||
<property name="eclipselink.weaving" value="static" />
|
||||
<property name="eclipselink.logging.level" value="FINE" />
|
||||
<property name="eclipselink.jdbc.allow-native-sql-queries" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
CREATE SEQUENCE article_seq MINVALUE 1 START WITH 50 INCREMENT BY 50;
|
||||
|
||||
INSERT INTO id_gen (gen_name, gen_val) VALUES ('id_generator', 0);
|
||||
INSERT INTO id_gen (gen_name, gen_val) VALUES ('task_gen', 10000);
|
|
@ -0,0 +1,81 @@
|
|||
package com.baeldung.jpa.generateidvalue;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* PrimaryKeyGeneratorTest class
|
||||
*
|
||||
* @author shiwangzhihe@gmail.com
|
||||
*/
|
||||
public class PrimaryKeyUnitTest {
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-primarykey");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdentityStrategy_whenCommitTransction_thenReturnPrimaryKey() {
|
||||
User user = new User();
|
||||
user.setName("TestName");
|
||||
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
entityManager.persist(user);
|
||||
Assert.assertNull(user.getId());
|
||||
entityManager.getTransaction()
|
||||
.commit();
|
||||
|
||||
Long expectPrimaryKey = 1L;
|
||||
Assert.assertEquals(expectPrimaryKey, user.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTableStrategy_whenPersist_thenReturnPrimaryKey() {
|
||||
Task task = new Task();
|
||||
task.setName("Test Task");
|
||||
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
entityManager.persist(task);
|
||||
Long expectPrimaryKey = 10000L;
|
||||
Assert.assertEquals(expectPrimaryKey, task.getId());
|
||||
|
||||
entityManager.getTransaction()
|
||||
.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceStrategy_whenPersist_thenReturnPrimaryKey() {
|
||||
Article article = new Article();
|
||||
article.setName("Test Name");
|
||||
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
entityManager.persist(article);
|
||||
Long expectPrimaryKey = 51L;
|
||||
Assert.assertEquals(expectPrimaryKey, article.getId());
|
||||
|
||||
entityManager.getTransaction()
|
||||
.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAutoStrategy_whenPersist_thenReturnPrimaryKey() {
|
||||
Admin admin = new Admin();
|
||||
admin.setName("Test Name");
|
||||
|
||||
entityManager.persist(admin);
|
||||
|
||||
Long expectPrimaryKey = 1L;
|
||||
Assert.assertEquals(expectPrimaryKey, admin.getId());
|
||||
}
|
||||
}
|
|
@ -6,6 +6,7 @@
|
|||
- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java)
|
||||
- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial)
|
||||
- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging)
|
||||
- [Introduction to Spring Data Elasticsearch – test 2](https://www.baeldung.com/spring-data-elasticsearch-test-2)
|
||||
|
||||
### Build the Project with Tests Running
|
||||
```
|
||||
|
|
|
@ -10,9 +10,9 @@
|
|||
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
|
||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
|
||||
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
||||
- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource-2)
|
||||
|
||||
|
||||
### Eclipse Config
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
|
||||
- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing)
|
||||
- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list)
|
||||
- [Transactional Annotations: Spring vs. JTA](https://www.baeldung.com/spring-vs-jta-transactional)
|
||||
|
|
8
pom.xml
8
pom.xml
|
@ -69,12 +69,6 @@
|
|||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
|
@ -1280,7 +1274,7 @@
|
|||
<module>wildfly</module>
|
||||
<module>xml</module>
|
||||
<module>xstream</module>
|
||||
<module>libraries-concurrency</module>
|
||||
<!-- <module>libraries-concurrency</module>--> <!-- we haven't upgraded to Java 11 -->
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
|
|
|
@ -4,4 +4,4 @@ This module contains articles about CI/CD with Spring Boot
|
|||
|
||||
## Relevant Articles
|
||||
|
||||
- [CI/CD for a Spring Boot Project](https://www.baeldung.com/spring-boot-ci-cd)
|
||||
- [Applying CI/CD With Spring Boot](https://www.baeldung.com/spring-boot-ci-cd)
|
||||
|
|
|
@ -36,7 +36,7 @@ public class UserController {
|
|||
|
||||
userRepository.save(user);
|
||||
model.addAttribute("users", userRepository.findAll());
|
||||
return "index";
|
||||
return "redirect:/index";
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
|
@ -55,7 +55,7 @@ public class UserController {
|
|||
|
||||
userRepository.save(user);
|
||||
model.addAttribute("users", userRepository.findAll());
|
||||
return "index";
|
||||
return "redirect:/index";
|
||||
}
|
||||
|
||||
@GetMapping("/delete/{id}")
|
||||
|
|
|
@ -41,7 +41,7 @@ public class UserControllerUnitTest {
|
|||
|
||||
when(mockedBindingResult.hasErrors()).thenReturn(false);
|
||||
|
||||
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("index");
|
||||
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("redirect:/index");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -64,7 +64,7 @@ public class UserControllerUnitTest {
|
|||
|
||||
when(mockedBindingResult.hasErrors()).thenReturn(false);
|
||||
|
||||
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("index");
|
||||
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("redirect:/index");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
## Spring Boot MVC
|
||||
|
||||
This module contains articles about Spring Web MVC in Spring Boot projects.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2)
|
|
@ -0,0 +1,29 @@
|
|||
<?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>spring-boot-mvc-3</artifactId>
|
||||
<name>spring-boot-mvc-3</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>Module For Spring Boot MVC Web</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.circularviewpath;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Spring Boot launcher for an application
|
||||
*
|
||||
*/
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.controller.circularviewpath")
|
||||
public class CircularViewPathApplication {
|
||||
|
||||
/**
|
||||
* Launches a Spring Boot application
|
||||
*
|
||||
* @param args null
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CircularViewPathApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.controller.circularviewpath;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class CircularViewPathController {
|
||||
|
||||
/**
|
||||
* A request mapping which may cause circular view path exception
|
||||
*/
|
||||
@GetMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
|
||||
<title>path.html</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<p>path.html</p>
|
||||
</body>
|
||||
</html>
|
|
@ -7,4 +7,5 @@ This module contains articles about Properties in Spring Boot.
|
|||
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
|
||||
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
|
||||
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)
|
||||
- [@PropertySource with YAML Files in Spring Boot](https://www.baeldung.com/spring-yaml-propertysource)
|
||||
- More articles: [[<-- prev]](../spring-boot-properties)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue