fix conflicts

This commit is contained in:
Loredana Crusoveanu
2018-02-11 22:01:46 +02:00
113 changed files with 3512 additions and 197 deletions
+1
View File
@@ -43,3 +43,4 @@ spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
*.springBeans
20171220-JMeter.csv
@@ -0,0 +1,52 @@
package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class BFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) {
LinkedList<Coordinate> nextToVisit = new LinkedList<>();
Coordinate start = maze.getEntry();
nextToVisit.add(start);
while (!nextToVisit.isEmpty()) {
Coordinate cur = nextToVisit.remove();
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
continue;
}
if (maze.isWall(cur.getX(), cur.getY())) {
maze.setVisited(cur.getX(), cur.getY(), true);
continue;
}
if (maze.isExit(cur.getX(), cur.getY())) {
return backtrackPath(cur);
}
for (int[] direction : DIRECTIONS) {
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
nextToVisit.add(coordinate);
maze.setVisited(cur.getX(), cur.getY(), true);
}
}
return Collections.emptyList();
}
private List<Coordinate> backtrackPath(Coordinate cur) {
List<Coordinate> path = new ArrayList<>();
Coordinate iter = cur;
while (iter != null) {
path.add(iter);
iter = iter.parent;
}
return path;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.algorithms.maze.solver;
public class Coordinate {
int x;
int y;
Coordinate parent;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
this.parent = null;
}
public Coordinate(int x, int y, Coordinate parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
int getX() {
return x;
}
int getY() {
return y;
}
Coordinate getParent() {
return parent;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) {
List<Coordinate> path = new ArrayList<>();
if (explore(maze, maze.getEntry()
.getX(),
maze.getEntry()
.getY(),
path)) {
return path;
}
return Collections.emptyList();
}
private boolean explore(Maze maze, int row, int col, List<Coordinate> path) {
if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) {
return false;
}
path.add(new Coordinate(row, col));
maze.setVisited(row, col, true);
if (maze.isExit(row, col)) {
return true;
}
for (int[] direction : DIRECTIONS) {
Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]);
if (explore(maze, coordinate.getX(), coordinate.getY(), path)) {
return true;
}
}
path.remove(path.size() - 1);
return false;
}
private Coordinate getNextCoordinate(int row, int col, int i, int j) {
return new Coordinate(row + i, col + j);
}
}
@@ -0,0 +1,141 @@
package com.baeldung.algorithms.maze.solver;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Maze {
private static final int ROAD = 0;
private static final int WALL = 1;
private static final int START = 2;
private static final int EXIT = 3;
private static final int PATH = 4;
private int[][] maze;
private boolean[][] visited;
private Coordinate start;
private Coordinate end;
public Maze(File maze) throws FileNotFoundException {
String fileText = "";
try (Scanner input = new Scanner(maze)) {
while (input.hasNextLine()) {
fileText += input.nextLine() + "\n";
}
}
initializeMaze(fileText);
}
private void initializeMaze(String text) {
if (text == null || (text = text.trim()).length() == 0) {
throw new IllegalArgumentException("empty lines data");
}
String[] lines = text.split("[\r]?\n");
maze = new int[lines.length][lines[0].length()];
visited = new boolean[lines.length][lines[0].length()];
for (int row = 0; row < getHeight(); row++) {
if (lines[row].length() != getWidth()) {
throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")");
}
for (int col = 0; col < getWidth(); col++) {
if (lines[row].charAt(col) == '#')
maze[row][col] = WALL;
else if (lines[row].charAt(col) == 'S') {
maze[row][col] = START;
start = new Coordinate(row, col);
} else if (lines[row].charAt(col) == 'E') {
maze[row][col] = EXIT;
end = new Coordinate(row, col);
} else
maze[row][col] = ROAD;
}
}
}
public int getHeight() {
return maze.length;
}
public int getWidth() {
return maze[0].length;
}
public Coordinate getEntry() {
return start;
}
public Coordinate getExit() {
return end;
}
public boolean isExit(int x, int y) {
return x == end.getX() && y == end.getY();
}
public boolean isStart(int x, int y) {
return x == start.getX() && y == start.getY();
}
public boolean isExplored(int row, int col) {
return visited[row][col];
}
public boolean isWall(int row, int col) {
return maze[row][col] == WALL;
}
public void setVisited(int row, int col, boolean value) {
visited[row][col] = value;
}
public boolean isValidLocation(int row, int col) {
if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) {
return false;
}
return true;
}
public void printPath(List<Coordinate> path) {
int[][] tempMaze = Arrays.stream(maze)
.map(int[]::clone)
.toArray(int[][]::new);
for (Coordinate coordinate : path) {
if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) {
continue;
}
tempMaze[coordinate.getX()][coordinate.getY()] = PATH;
}
System.out.println(toString(tempMaze));
}
public String toString(int[][] maze) {
StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1));
for (int row = 0; row < getHeight(); row++) {
for (int col = 0; col < getWidth(); col++) {
if (maze[row][col] == ROAD) {
result.append(' ');
} else if (maze[row][col] == WALL) {
result.append('#');
} else if (maze[row][col] == START) {
result.append('S');
} else if (maze[row][col] == EXIT) {
result.append('E');
} else {
result.append('.');
}
}
result.append('\n');
}
return result.toString();
}
public void reset() {
for (int i = 0; i < visited.length; i++)
Arrays.fill(visited[i], false);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.algorithms.maze.solver;
import java.io.File;
import java.util.List;
public class MazeDriver {
public static void main(String[] args) throws Exception {
File maze1 = new File("src/main/resources/maze/maze1.txt");
File maze2 = new File("src/main/resources/maze/maze2.txt");
execute(maze1);
execute(maze2);
}
private static void execute(File file) throws Exception {
Maze maze = new Maze(file);
dfs(maze);
bfs(maze);
}
private static void bfs(Maze maze) {
BFSMazeSolver bfs = new BFSMazeSolver();
List<Coordinate> path = bfs.solve(maze);
maze.printPath(path);
maze.reset();
}
private static void dfs(Maze maze) {
DFSMazeSolver dfs = new DFSMazeSolver();
List<Coordinate> path = dfs.solve(maze);
maze.printPath(path);
maze.reset();
}
}
@@ -101,4 +101,4 @@ public class BacktrackingAlgorithm {
}
return true;
}
}
}
@@ -120,10 +120,10 @@ public class DancingLinks {
}
private static void printSolution(int[][] result) {
int N = result.length;
int size = result.length;
for (int[] aResult : result) {
StringBuilder ret = new StringBuilder();
for (int j = 0; j < N; j++) {
for (int j = 0; j < size; j++) {
ret.append(aResult[j]).append(" ");
}
System.out.println(ret);
@@ -39,70 +39,83 @@ public class DancingLinksAlgorithm {
}
private boolean[][] createExactCoverBoard() {
boolean[][] R = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
boolean[][] coverBoard = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
int hBase = 0;
hBase = checkCellConstraint(coverBoard, hBase);
hBase = checkRowConstraint(coverBoard, hBase);
hBase = checkColumnConstraint(coverBoard, hBase);
checkSubsectionConstraint(coverBoard, hBase);
return coverBoard;
}
// Cell constraint.
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++, hBase++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
int index = getIndex(r, c, n);
R[index][hBase] = true;
}
}
}
// Row constrain.
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int c1 = COVER_START_INDEX; c1 <= BOARD_SIZE; c1++) {
int index = getIndex(r, c1, n);
R[index][hBase] = true;
}
}
}
// Column constraint.
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int r1 = COVER_START_INDEX; r1 <= BOARD_SIZE; r1++) {
int index = getIndex(r1, c, n);
R[index][hBase] = true;
}
}
}
// Subsection constraint
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
for (int br = COVER_START_INDEX; br <= BOARD_SIZE; br += SUBSECTION_SIZE) {
for (int bc = COVER_START_INDEX; bc <= BOARD_SIZE; bc += SUBSECTION_SIZE) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int rDelta = 0; rDelta < SUBSECTION_SIZE; rDelta++) {
for (int cDelta = 0; cDelta < SUBSECTION_SIZE; cDelta++) {
int index = getIndex(br + rDelta, bc + cDelta, n);
R[index][hBase] = true;
coverBoard[index][hBase] = true;
}
}
}
}
}
return R;
return hBase;
}
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int r1 = COVER_START_INDEX; r1 <= BOARD_SIZE; r1++) {
int index = getIndex(r1, c, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int c1 = COVER_START_INDEX; c1 <= BOARD_SIZE; c1++) {
int index = getIndex(r, c1, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++, hBase++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
int index = getIndex(r, c, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private boolean[][] initializeExactCoverBoard(int[][] board) {
boolean[][] R = createExactCoverBoard();
boolean[][] coverBoard = createExactCoverBoard();
for (int i = COVER_START_INDEX; i <= BOARD_SIZE; i++) {
for (int j = COVER_START_INDEX; j <= BOARD_SIZE; j++) {
int n = board[i - 1][j - 1];
if (n != NO_VALUE) {
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
if (num != n) {
Arrays.fill(R[getIndex(i, j, num)], false);
Arrays.fill(coverBoard[getIndex(i, j, num)], false);
}
}
}
}
}
return R;
return coverBoard;
}
}
@@ -0,0 +1,12 @@
S ########
# #
# ### ## #
# # # #
# # # # #
# ## #####
# # #
# # # # #
##### ####
# # E
# # # #
##########
@@ -0,0 +1,22 @@
S ##########################
# # # #
# # #### ############### #
# # # # # #
# # #### # # ###############
# # # # # # #
# # # #### ### ########### #
# # # # # #
# ################## #
######### # # # # #
# # #### # ####### # #
# # ### ### # # # # #
# # ## # ##### # #
##### ####### # # # # #
# # ## ## #### # #
# ##### ####### # #
# # ############
####### ######### # #
# # ######## #
# ####### ###### ## # E
# # # ## #
############################
@@ -11,6 +11,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
@@ -116,18 +117,20 @@ public class HttpClientTest {
.GET()
.build();
ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
.executor(Executors.newFixedThreadPool(2))
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
.executor(Executors.newFixedThreadPool(2))
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
.executor(Executors.newFixedThreadPool(2))
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
@@ -16,7 +16,8 @@ public class Job implements Runnable {
@Override
public void run() {
try {
System.out.println("Job:" + jobName + " Priority:" + jobPriority);
System.out.println("Job:" + jobName +
" Priority:" + jobPriority);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
@@ -9,21 +9,21 @@ import java.util.concurrent.TimeUnit;
public class PriorityJobScheduler {
private ExecutorService priorityJobPoolExecutor;
private ExecutorService priorityJobScheduler;
private PriorityBlockingQueue<Runnable> priorityQueue;
private ExecutorService priorityJobScheduler =
Executors.newSingleThreadExecutor();
private PriorityBlockingQueue<Job> priorityQueue;
public PriorityJobScheduler(Integer poolSize, Integer queueSize) {
priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
Comparator<? super Job> jobComparator = Comparator.comparing(Job::getJobPriority);
priorityQueue = new PriorityBlockingQueue<Runnable>(queueSize,
(Comparator<? super Runnable>) jobComparator);
priorityQueue = new PriorityBlockingQueue<Job>(queueSize,
Comparator.comparing(Job::getJobPriority));
priorityJobScheduler = Executors.newSingleThreadExecutor();
priorityJobScheduler.execute(()->{
while (true) {
try {
priorityJobPoolExecutor.execute(priorityQueue.take());
} catch (InterruptedException e) {
// exception needs special handling
break;
}
}
@@ -30,7 +30,9 @@ public class PriorityJobSchedulerUnitTest {
// delay to avoid job sleep (added for demo) being interrupted
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
pjs.closeScheduler();
@@ -1,28 +1,16 @@
package com.baeldung.javac;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Data implements Serializable {
static List<String> textList = new ArrayList();
public class Data {
List<String> textList = new ArrayList();
private static void addText() {
textList.add("baeldung");
textList.add(".");
textList.add("com");
public void addText(String text) {
textList.add(text);
}
public List getTextList() {
this.addText();
List<String> result = new ArrayList<String>();
String firstElement = (String) textList.get(0);
switch (firstElement) {
case "baeldung":
result.add("baeldung");
case "com":
result.add("com");
}
return result;
return this.textList;
}
}
}
@@ -0,0 +1,62 @@
package com.baeldung.string;
import java.util.stream.IntStream;
public class Palindrome {
public boolean isPalindrome(String text) {
text = text.replaceAll("\\s+", "")
.toLowerCase();
int length = text.length();
int forward = 0;
int backward = length - 1;
boolean palindrome = true;
while (backward > forward) {
char forwardChar = text.charAt(forward++);
char backwardChar = text.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return palindrome;
}
public boolean isPalindromeReverseTheString(String text) {
String reverse = "";
text = text.replaceAll("\\s+", "").toLowerCase();
char[] plain = text.toCharArray();
for (int i = plain.length - 1; i >= 0; i--)
reverse += plain[i];
return reverse.equals(text);
}
public boolean isPalindromeUsingStringBuilder(String text) {
StringBuilder plain = new StringBuilder(text);
StringBuilder reverse = plain.reverse();
return reverse.equals(plain);
}
public boolean isPalindromeUsingStringBuffer(String text) {
StringBuffer plain = new StringBuffer(text);
StringBuffer reverse = plain.reverse();
return reverse.equals(plain);
}
public boolean isPalindromeRecursive(String text, int forward, int backward) {
if (forward == backward)
return true;
if ((text.charAt(forward)) != (text.charAt(backward)))
return false;
if (forward < backward + 1) {
return isPalindromeRecursive(text, forward + 1, backward - 1);
}
return true;
}
public boolean isPalindromeUsingIntStream(String text) {
String temp = text.replaceAll("\\s+", "").toLowerCase();
return IntStream.range(0, temp.length() / 2)
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}
}
@@ -0,0 +1,108 @@
package com.baeldung.string;
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
private String[] words = {
"Anna",
"Civic",
"Kayak",
"Level",
"Madam",
};
private String[] sentences = {
"Sore was I ere I saw Eros",
"Euston saw I was not Sue",
"Too hot to hoot",
"No mists or frost Simon",
"Stella won no wallets"
};
private Palindrome palindrome = new Palindrome();
@Test
public void whenWord_shouldBePalindrome() {
for(String word:words)
assertTrue(palindrome.isPalindrome(word));
}
@Test
public void whenSentence_shouldBePalindrome() {
for(String sentence:sentences)
assertTrue(palindrome.isPalindrome(sentence));
}
@Test
public void whenReverseWord_shouldBePalindrome() {
for(String word:words)
assertTrue(palindrome.isPalindromeReverseTheString(word));
}
@Test
public void whenReverseSentence_shouldBePalindrome() {
for(String sentence:sentences)
assertTrue(palindrome.isPalindromeReverseTheString(sentence));
}
@Test
public void whenStringBuilderWord_shouldBePalindrome() {
for(String word:words)
assertTrue(palindrome.isPalindromeUsingStringBuilder(word));
}
@Test
public void whenStringBuilderSentence_shouldBePalindrome() {
for(String sentence:sentences)
assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence));
}
@Test
public void whenStringBufferWord_shouldBePalindrome() {
for(String word:words)
assertTrue(palindrome.isPalindromeUsingStringBuffer(word));
}
@Test
public void whenStringBufferSentence_shouldBePalindrome() {
for(String sentence:sentences)
assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence));
}
@Test
public void whenPalindromeRecursive_wordShouldBePalindrome() {
for(String word:words) {
word = word.replaceAll("\\s+", "").toLowerCase();
int backward = word.length()-1;
assertTrue(palindrome.isPalindromeRecursive(word,0,backward));
}
}
@Test
public void whenPalindromeRecursive_sentenceShouldBePalindrome() {
for(String sentence:sentences) {
sentence = sentence.replaceAll("\\s+", "").toLowerCase();
int backward = sentence.length()-1;
assertTrue(palindrome.isPalindromeRecursive(sentence,0,backward));
}
}
@Test
public void whenPalindromeStreams_wordShouldBePalindrome() {
for(String word:words) {
assertTrue(palindrome.isPalindromeUsingIntStream(word));
}
}
@Test
public void whenPalindromeStreams_sentenceShouldBePalindrome() {
for(String sentence:sentences) {
assertTrue(palindrome.isPalindromeUsingIntStream(sentence));
}
}
}
@@ -0,0 +1,51 @@
package com.baeldung.kotlin
import org.junit.Assert
import org.junit.Test
class InfixFunctionsTest {
@Test
fun testColours() {
val color = 0x123456
val red = (color and 0xff0000) shr 16
val green = (color and 0x00ff00) shr 8
val blue = (color and 0x0000ff) shr 0
Assert.assertEquals(0x12, red)
Assert.assertEquals(0x34, green)
Assert.assertEquals(0x56, blue)
}
@Test
fun testNewAssertions() {
class Assertion<T>(private val target: T) {
infix fun isEqualTo(other: T) {
Assert.assertEquals(other, target)
}
infix fun isDifferentFrom(other: T) {
Assert.assertNotEquals(other, target)
}
}
val result = Assertion(5)
result isEqualTo 5
// The following two lines are expected to fail
// result isEqualTo 6
// result isDifferentFrom 5
}
@Test
fun testNewStringMethod() {
infix fun String.substringMatches(r: Regex) : List<String> {
return r.findAll(this)
.map { it.value }
.toList()
}
val matches = "a bc def" substringMatches ".*? ".toRegex()
Assert.assertEquals(listOf("a ", "bc "), matches)
}
}
@@ -0,0 +1,128 @@
package com.baeldung.kotlin.stdlib
import org.junit.Test
import java.beans.ExceptionListener
import java.beans.XMLEncoder
import java.io.*
import java.lang.Exception
import kotlin.test.*
import kotlin.text.RegexOption.*
class RegexTest {
@Test
fun whenRegexIsInstantiated_thenIsEqualToToRegexMethod() {
val pattern = """a([bc]+)d?\\"""
assertEquals(Regex.fromLiteral(pattern).pattern, pattern)
assertEquals(pattern, Regex(pattern).pattern)
assertEquals(pattern, pattern.toRegex().pattern)
}
@Test
fun whenRegexMatches_thenResultIsTrue() {
val regex = """a([bc]+)d?""".toRegex()
assertTrue(regex.containsMatchIn("xabcdy"))
assertTrue(regex.matches("abcd"))
assertFalse(regex matches "xabcdy")
}
@Test
fun givenCompletelyMatchingRegex_whenMatchResult_thenDestructuring() {
val regex = """a([bc]+)d?""".toRegex()
assertNull(regex.matchEntire("xabcdy"))
val matchResult = regex.matchEntire("abbccbbd")
assertNotNull(matchResult)
assertEquals(matchResult!!.value, matchResult.groupValues[0])
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
assertEquals("bbccbb", matchResult.destructured.component1())
assertNull(matchResult.next())
}
@Test
fun givenPartiallyMatchingRegex_whenMatchResult_thenGroups() {
val regex = """a([bc]+)d?""".toRegex()
var matchResult = regex.find("abcb abbd")
assertNotNull(matchResult)
assertEquals(matchResult!!.value, matchResult.groupValues[0])
assertEquals("abcb", matchResult.value)
assertEquals(IntRange(0, 3), matchResult.range)
assertEquals(listOf("abcb", "bcb"), matchResult.groupValues)
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
matchResult = matchResult.next()
assertNotNull(matchResult)
assertEquals("abbd", matchResult!!.value)
assertEquals("bb", matchResult.groupValues[1])
matchResult = matchResult.next()
assertNull(matchResult)
}
@Test
fun givenPartiallyMatchingRegex_whenMatchResult_thenDestructuring() {
val regex = """([\w\s]+) is (\d+) years old""".toRegex()
val matchResult = regex.find("Mickey Mouse is 95 years old")
val (name, age) = matchResult!!.destructured
assertEquals("Mickey Mouse", name)
assertEquals("95", age)
}
@Test
fun givenNonMatchingRegex_whenFindCalled_thenNull() {
val regex = """a([bc]+)d?""".toRegex()
val matchResult = regex.find("foo")
assertNull(matchResult)
}
@Test
fun givenNonMatchingRegex_whenFindAllCalled_thenEmptySet() {
val regex = """a([bc]+)d?""".toRegex()
val matchResults = regex.findAll("foo")
assertNotNull(matchResults)
assertTrue(matchResults.none())
}
@Test
fun whenReplace_thenReplacement() {
val regex = """(red|green|blue)""".toRegex()
val beautiful = "Roses are red, Violets are blue"
val grim = regex.replace(beautiful, "dark")
val shiny = regex.replaceFirst(beautiful, "rainbow")
assertEquals("Roses are dark, Violets are dark", grim)
assertEquals("Roses are rainbow, Violets are blue", shiny)
}
@Test
fun whenComplexReplace_thenReplacement() {
val regex = """(red|green|blue)""".toRegex()
val beautiful = "Roses are red, Violets are blue"
val reallyBeautiful = regex.replace(beautiful) {
matchResult -> matchResult.value.toUpperCase() + "!"
}
assertEquals("Roses are RED!, Violets are BLUE!", reallyBeautiful)
}
@Test
fun whenSplit_thenList() {
val regex = """\W+""".toRegex()
val beautiful = "Roses are red, Violets are blue"
assertEquals(listOf("Roses", "are", "red", "Violets", "are", "blue"), regex.split(beautiful))
assertEquals(listOf("Roses", "are", "red", "Violets are blue"), regex.split(beautiful, 4))
assertEquals(regex.toPattern().split(beautiful).asList(), regex.split(beautiful))
}
}
@@ -81,6 +81,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
@@ -0,0 +1,43 @@
package com.baeldung.hibernate.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import com.baeldung.hibernate.pojo.PersonName;
@Converter
public class PersonNameConverter implements AttributeConverter<PersonName, String> {
private static final String SEPARATOR = ", ";
@Override
public String convertToDatabaseColumn(PersonName person) {
StringBuilder sb = new StringBuilder();
if (person.getSurname() != null) {
sb.append(person.getSurname());
sb.append(SEPARATOR);
}
if (person.getName() != null) {
sb.append(person.getName());
}
return sb.toString();
}
@Override
public PersonName convertToEntityAttribute(String dbPerson) {
String[] pieces = dbPerson.split(SEPARATOR);
if (pieces == null || pieces.length != 2) {
return null;
}
PersonName personName = new PersonName();
personName.setSurname(pieces[0]);
personName.setName(pieces[1]);
return personName;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.baeldung.hibernate.converters.PersonNameConverter;
@Entity(name = "PersonTable")
public class Person {
@Id
@GeneratedValue
private Long id;
@Convert(converter = PersonNameConverter.class)
private PersonName personName;
public PersonName getPersonName() {
return personName;
}
public void setPersonName(PersonName personName) {
this.personName = personName;
}
public Long getId() {
return id;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.hibernate.pojo;
import java.io.Serializable;
public class PersonName implements Serializable {
private static final long serialVersionUID = 7883094644631050150L;
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
@@ -0,0 +1,74 @@
package com.baeldung.hibernate.converter;
import java.io.IOException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.PersonName;
import static org.junit.Assert.assertEquals;
public class PersonNameConverterTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from personTable")
.executeUpdate();
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() {
final String name = "name";
final String surname = "surname";
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals(surname + ", " + name, dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName()
.getName(), name);
assertEquals(dbPerson.getPersonName()
.getSurname(), surname);
}
}
-1
View File
@@ -2,7 +2,6 @@
### Relevant Article:
- [Introduction to using InfluxDB with Java](http://www.baeldung.com/using-influxdb-with-java/)
- [Using InfluxDB with Java](http://www.baeldung.com/java-influxdb)
### Overview
This Maven project contains the Java code for the article linked above.
@@ -8,7 +8,6 @@ import org.influxdb.dto.*;
import org.influxdb.impl.InfluxDBResultMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -103,7 +102,7 @@ public class InfluxDBConnectionLiveTest {
// another brief pause.
Thread.sleep(10);
List<MemoryPoint> memoryPointList = getPoints(connection, "Select * from memory", "baeldung");
List<com.baeldung.influxdb.MemoryPoint> memoryPointList = getPoints(connection, "Select * from memory", "baeldung");
assertEquals(10, memoryPointList.size());
+1 -1
View File
@@ -129,7 +129,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.9.2</jackson.version>
<jackson.version>2.9.4</jackson.version>
<!-- util -->
<guava.version>19.0</guava.version>
+13 -8
View File
@@ -6,10 +6,11 @@
<version>0.1-SNAPSHOT</version>
<properties>
<validation-api.version>2.0.0.Final</validation-api.version>
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
<validation-api.version>2.0.1.Final</validation-api.version>
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
</properties>
@@ -21,12 +22,6 @@
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
@@ -50,6 +45,16 @@
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
</dependencies>
@@ -0,0 +1,38 @@
package org.baeldung.javaxval.methodvalidation;
import org.baeldung.javaxval.methodvalidation.model.Customer;
import org.baeldung.javaxval.methodvalidation.model.Reservation;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import java.time.LocalDate;
@Configuration
@ComponentScan({ "org.baeldung.javaxval.methodvalidation.model" })
public class MethodValidationConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Bean("customer")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Customer customer(String firstName, String lastName) {
Customer customer = new Customer(firstName, lastName);
return customer;
}
@Bean("reservation")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Reservation reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
Reservation reservation = new Reservation(begin, end, customer, room);
return reservation;
}
}

Some files were not shown because too many files have changed in this diff Show More