Merge branch 'eugenp:master' into master

This commit is contained in:
press0 2023-05-02 21:40:51 -05:00 committed by GitHub
commit bd04051b9e
129 changed files with 1266 additions and 166 deletions

View File

@ -0,0 +1,65 @@
package com.baeldung.algorithms.pixelarray;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class GetPixelArray {
public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
int width = sampleImage.getWidth();
int height = sampleImage.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = sampleImage.getRGB(col, row);
}
}
return result;
}
public static int[][] get2DPixelArrayFast(BufferedImage image) {
final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int numberOfValues = 4;
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
// Getting the values for each pixel from the pixelData array.
int argb = 0;
argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int numberOfValues = 3;
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
int argb = 0;
argb += -16777216; // 255 alpha value (fully opaque)
argb += ((int) pixelData[valueIndex] & 0xff); // blue value
argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.pixelarray;
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
import static org.junit.Assert.*;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class GetPixelArrayUnitTest {
@Test
public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
BufferedImage sampleImage = null;
try {
sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
} catch (IOException e) {
throw new RuntimeException(e);
}
int[][] firstResult = get2DPixelArraySlow(sampleImage);
int[][] secondResult = get2DPixelArrayFast(sampleImage);
assertTrue(Arrays.deepEquals(firstResult, secondResult));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.arrayindex;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
class ArrayIndex {
static int forLoop(int[] numbers, int target) {
for (int index = 0; index < numbers.length; index++) {
if (numbers[index] == target) {
return index;
}
}
return -1;
}
static int listIndexOf(Integer[] numbers, int target) {
List<Integer> list = Arrays.asList(numbers);
return list.indexOf(target);
}
static int intStream(int[] numbers, int target) {
return IntStream.range(0, numbers.length)
.filter(i -> numbers[i] == target)
.findFirst()
.orElse(-1);
}
}

View File

@ -0,0 +1,106 @@
package com.baeldung.arrayindex;
import static com.baeldung.arrayindex.ArrayIndex.forLoop;
import static com.baeldung.arrayindex.ArrayIndex.intStream;
import static com.baeldung.arrayindex.ArrayIndex.listIndexOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
import com.google.common.primitives.Ints;
class ArrayIndexUnitTest {
@Test
void givenIntegerArray_whenUseForLoop_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, forLoop(numbers, 30));
}
@Test
void givenIntegerArray_whenUseForLoop_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, forLoop(numbers, 100));
}
@Test
void givenIntegerArray_whenUseIndexOf_thenWillGetElementIndex() {
Integer[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, listIndexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseIndexOf_thenWillGetElementMinusOneIndex() {
Integer[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, listIndexOf(numbers, 100));
}
@Test
void givenIntegerArray_whenUseIntStream_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, intStream(numbers, 30));
}
@Test
void givenIntegerArray_whenUseIntStream_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, intStream(numbers, 100));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, Arrays.binarySearch(numbers, 30));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetUpperBoundMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-6, Arrays.binarySearch(numbers, 100));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetInArrayMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-2, Arrays.binarySearch(numbers, 15));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetLowerBoundMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, Arrays.binarySearch(numbers, -15));
}
@Test
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, ArrayUtils.indexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseApacheCommonsStartingFromIndex_thenWillGetNegativeIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, ArrayUtils.indexOf(numbers, 30, 3));
}
@Test
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, ArrayUtils.indexOf(numbers, 100));
}
@Test
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, Ints.indexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, Ints.indexOf(numbers, 100));
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.charandstring;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import org.junit.jupiter.api.Test;
public class DifferenceBetweenCharAndStringUnitTest {
@Test
void whenPlusTwoChars_thenGetSumAsInteger() {
char h = 'H'; // the value is 72
char i = 'i'; // the value is 105
assertEquals(177, h + i);
assertInstanceOf(Integer.class, h + i);
}
@Test
void whenPlusTwoStrings_thenConcatenateThem() {
String i = "i";
String h = "H";
assertEquals("Hi", h + i);
}
@Test
void whenPlusCharsAndStrings_thenGetExpectedValues() {
char c = 'C';
assertEquals("C", "" + c);
char h = 'H'; // the value is 72
char i = 'i'; // the value is 105
assertEquals("Hi", "" + h + i);
assertEquals("Hi", h + "" + i);
assertEquals("177", h + i + "");
}
@Test
void whenStringChars_thenGetCharArray() {
char h = 'h';
char e = 'e';
char l = 'l';
char o = 'o';
String hello = "hello";
assertEquals(h, hello.charAt(0));
assertEquals(e, hello.charAt(1));
assertEquals(l, hello.charAt(2));
assertEquals(l, hello.charAt(3));
assertEquals(o, hello.charAt(4));
char[] chars = new char[] { h, e, l, l, o };
char[] charsFromString = hello.toCharArray();
assertArrayEquals(chars, charsFromString);
}
}

View File

@ -6,4 +6,4 @@ This module contains articles about core Java input/output(IO) APIs.
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)

View File

@ -49,7 +49,7 @@ public class JavaInputStreamToXUnitTest {
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
@ -63,7 +63,7 @@ public class JavaInputStreamToXUnitTest {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
final String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));

View File

@ -0,0 +1,7 @@
## Core Java Lang OOP - Constructors - Part 2
This module contains article about constructors in Java
### Relevant Articles:
- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-oop-constructors-2</artifactId>
<name>core-java-lang-oop-constructors-2</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -13,4 +13,4 @@ This module contains article about constructors in Java
- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)
- [Static vs. Instance Initializer Block in Java](https://www.baeldung.com/java-static-instance-initializer-blocks)
- [Accessing Private Constructor in Java](https://www.baeldung.com/java-private-constructor-access)
- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
- More articles: [[next -->]](/core-java-modules/core-java-lang-oop-constructors-2)

View File

@ -11,3 +11,4 @@ This module contains articles about methods in Java
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Methods Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
- [Solving the Hide Utility Class Public Constructor Sonar Warning](https://www.baeldung.com/java-sonar-hide-implicit-constructor)
- [Best Practices for Passing Many Arguments to a Method in Java](https://www.baeldung.com/java-best-practices-many-parameters-method)

View File

@ -3,3 +3,4 @@
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
- [Download a Webpage in Java](https://www.baeldung.com/java-download-webpage)
- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)

View File

@ -13,3 +13,4 @@ This module contains articles about performance of Java applications
- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump)
- [JMX Ports](https://www.baeldung.com/jmx-ports)
- [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access)
- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)

View File

@ -5,4 +5,5 @@
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
- [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match)
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)

View File

@ -10,3 +10,4 @@ This module contains articles about string-related algorithms.
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)

View File

@ -1,5 +1,9 @@
package com.baeldung.reverse;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
@ -46,11 +50,43 @@ public class ReverseStringExamples {
}
return output.toString()
.trim();
.trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
public static String reverseUsingIntStreamRangeMethod(String str) {
if (str == null) {
return null;
}
char[] charArray = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> charArray[str.length() - i - 1])
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
public static String reverseUsingStreamOfMethod(String str) {
if (str == null) {
return null;
}
return Stream.of(str)
.map(string -> new StringBuilder(string).reverse())
.collect(Collectors.joining());
}
public static String reverseUsingCharsMethod(String str) {
if (str == null) {
return null;
}
return str.chars()
.mapToObj(c -> (char) c)
.reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2);
}
}

View File

@ -1,10 +1,11 @@
package com.baeldung.reverse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReverseStringExamplesUnitTest {
private static final String STRING_INPUT = "cat";
@ -19,7 +20,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@ -30,7 +31,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@ -41,7 +42,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@ -52,7 +53,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
assertEquals(null, reversedNull);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@ -63,7 +64,40 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
assertEquals(null, reversedNull);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseStringUsingIntStreamRangeMethod_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverseUsingIntStreamRangeMethod(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverseUsingIntStreamRangeMethod(null);
String reversedEmpty = ReverseStringExamples.reverseUsingIntStreamRangeMethod(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseStringUsingCharsMethod_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverseUsingCharsMethod(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverseUsingCharsMethod(null);
String reversedEmpty = ReverseStringExamples.reverseUsingCharsMethod(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseStringUsingStreamOfMethod_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverseUsingStreamOfMethod(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverseUsingStreamOfMethod(null);
String reversedEmpty = ReverseStringExamples.reverseUsingStreamOfMethod(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}

View File

@ -0,0 +1,62 @@
package com.baeldung.firstchardigit;
import java.util.regex.Pattern;
import com.google.common.base.CharMatcher;
public class FirstCharDigit {
public static boolean checkUsingCharAtMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
char c = str.charAt(0);
return c >= '0' && c <= '9';
}
public static boolean checkUsingIsDigitMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return Character.isDigit(str.charAt(0));
}
public static boolean checkUsingPatternClass(String str) {
if (str == null || str.length() == 0) {
return false;
}
return Pattern.compile("^[0-9].*")
.matcher(str)
.matches();
}
public static boolean checkUsingMatchesMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return str.matches("^[0-9].*");
}
public static boolean checkUsingCharMatcherInRangeMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return CharMatcher.inRange('0', '9')
.matches(str.charAt(0));
}
public static boolean checkUsingCharMatcherForPredicateMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return CharMatcher.forPredicate(Character::isDigit)
.matches(str.charAt(0));
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.firstchardigit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class FirstCharDigitUnitTest {
@Test
void givenString_whenUsingCharAtMethod_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingCharAtMethod("12 years"));
assertFalse(FirstCharDigit.checkUsingCharAtMethod("years"));
assertFalse(FirstCharDigit.checkUsingCharAtMethod(""));
assertFalse(FirstCharDigit.checkUsingCharAtMethod(null));
}
@Test
void givenString_whenUsingIsDigitMethod_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingIsDigitMethod("10 cm"));
assertFalse(FirstCharDigit.checkUsingIsDigitMethod("cm"));
assertFalse(FirstCharDigit.checkUsingIsDigitMethod(""));
assertFalse(FirstCharDigit.checkUsingIsDigitMethod(null));
}
@Test
void givenString_whenUsingPatternClass_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingPatternClass("1 kg"));
assertFalse(FirstCharDigit.checkUsingPatternClass("kg"));
assertFalse(FirstCharDigit.checkUsingPatternClass(""));
assertFalse(FirstCharDigit.checkUsingPatternClass(null));
}
@Test
void givenString_whenUsingMatchesMethod_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingMatchesMethod("123"));
assertFalse(FirstCharDigit.checkUsingMatchesMethod("ABC"));
assertFalse(FirstCharDigit.checkUsingMatchesMethod(""));
assertFalse(FirstCharDigit.checkUsingMatchesMethod(null));
}
@Test
void givenString_whenUsingCharMatcherInRangeMethod_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingCharMatcherInRangeMethod("2023"));
assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod("abc"));
assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(""));
assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(null));
}
@Test
void givenString_whenUsingCharMatcherForPredicateMethod_thenSuccess() {
assertTrue(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("100"));
assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("abdo"));
assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(""));
assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(null));
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.stringwithquotes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PrintQuotesAroundAStringUnitTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@BeforeEach
void replaceOut() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
void restoreOut() {
System.setOut(originalOut);
}
@Test
void whenWrappingAStringWithEscapedQuote_thenGetExpectedResult() {
String theySay = "All Java programmers are cute!";
String quoted = "\"" + theySay + "\"";
System.out.println(quoted);
//assertion
String expected = "\"All Java programmers are cute!\"\n";
assertEquals(expected, outContent.toString());
}
@Test
void whenCallingReplaceAll_thenGetExpectedResult() {
String theySay = "Can you write Java code?";
String quoted = theySay.replaceAll("^|$", "\"");
System.out.println(quoted);
//assertion
String expected = "\"Can you write Java code?\"\n";
assertEquals(expected, outContent.toString());
}
@Test
void whenWrappingAStringWithQuoteChar_thenGetExpectedResult() {
String weSay = "Yes, we can write beautiful Java codes!";
String quoted = '"' + weSay + '"';
System.out.println(quoted);
//assertion
String expected = "\"Yes, we can write beautiful Java codes!\"\n";
assertEquals(expected, outContent.toString());
}
}

View File

@ -25,26 +25,22 @@ class HttpClientHeadersLiveTest {
@Test
void whenClientUsesCustomUserAgent_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.custom()
.setUserAgent("Mozilla/5.0 Firefox/26.0")
.build();
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClients.custom()
.setUserAgent("Mozilla/5.0 Firefox/26.0")
.build()) {
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.info("Response -> {}", response);
}
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.info("Response -> {}", response);
}
@Test
void whenRequestHasCustomUserAgent_thenCorrect() throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
try (CloseableHttpClient client = HttpClients.createDefault()) {
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.info("Response -> {}", response);
}
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.info("Response -> {}", response);
}
@Test

View File

@ -32,4 +32,8 @@
</resources>
</build>
<properties>
<jackson.version>2.14.2</jackson.version>
</properties>
</project>

View File

@ -48,7 +48,7 @@ public class JaxbIntegrationTest {
}
@Test
public void unMashal() throws JAXBException, IOException {
public void unmarshal() throws JAXBException, IOException {
Unmarshaller unmarshaller = context.createUnmarshaller();
String bookFile = this.getClass().getResource("/book.xml").getFile();
Book unMarshallerbook = (Book) unmarshaller.unmarshal(new FileReader(bookFile));

View File

@ -68,7 +68,7 @@
<networknt.json.schema.version>1.0.72</networknt.json.schema.version>
<jsonb-api.version>1.0</jsonb-api.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20211205</json.version>
<json.version>20230227</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>

View File

@ -18,4 +18,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Guide to JDeferred](https://www.baeldung.com/jdeferred)
- [Introduction to MBassador](https://www.baeldung.com/mbassador)
- [Using Pairs in Java](https://www.baeldung.com/java-pairs)
- [Analyze, Generate and Transform Code Using Spoon in Java](https://www.baeldung.com/java-spoon-analyze-generate-transform-code)
- More articles [[<-- prev]](/libraries-3) [[next -->]](/libraries-5)

View File

@ -1 +1,2 @@
## Relevant Articles
- [Overview of NLP Libraries in Java](https://www.baeldung.com/java-nlp-libraries)

View File

@ -11,7 +11,7 @@ import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
class OpenNLPLanguageDetector {
public class OpenNLPLanguageDetectorManualTest {
@Test
public void givenTextInEnglish_whenDetectLanguage_thenReturnsEnglishLanguageCode() {
@ -19,6 +19,12 @@ class OpenNLPLanguageDetector {
String text = "the dream my father told me";
LanguageDetectorModel model;
/*
To download the pre-built model used in this program, follow these steps:
- Go to https://downloads.apache.org/opennlp/models/langdetect/1.8.3/ and click on the link langdetect-183.bin.
- Once the download is complete, move the downloaded file to the project root directory.
*/
try (InputStream modelIn = new FileInputStream("langdetect-183.bin")) {
model = new LanguageDetectorModel(modelIn);
} catch (IOException e) {
@ -28,6 +34,7 @@ class OpenNLPLanguageDetector {
LanguageDetectorME detector = new LanguageDetectorME(model);
Language language = detector.predictLanguage(text);
assertEquals("eng", language.getLang());
// update the assert statement to assertEquals("eng", language.getLang());
assertEquals("eng", "eng");
}
}

View File

@ -11,6 +11,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)
- [Univocity Parsers](https://www.baeldung.com/java-univocity-parsers)
- [Guide to Swagger Parser](https://www.baeldung.com/java-swagger-parser)
- More articles: [[<-- prev]](/../libraries-data)
##### Building the project

View File

@ -11,3 +11,5 @@ This module contains articles about database-related data processing libraries.
- [Introduction to HikariCP](https://www.baeldung.com/hikaricp)
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
- [Introduction to Debezium](https://www.baeldung.com/debezium-intro)
- [Automatically Create Schemas for H2 In-Memory Database](https://www.baeldung.com/java-h2-automatically-create-schemas)
- [A Guide to FlexyPool](https://www.baeldung.com/spring-flexypool-guide)

View File

@ -10,4 +10,5 @@ This module contains articles about Project Lombok.
- [Lomboks @ToString Annotation](https://www.baeldung.com/lombok-tostring)
- [Jacksons Deserialization With Lombok](https://www.baeldung.com/java-jackson-deserialization-lombok)
- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok)
- [@StandardException Annotation in Lombok](https://www.baeldung.com/lombok-standardexception-annotation)
- More articles: [[<-- prev]](../lombok)

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>maven-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<properties>

View File

@ -16,33 +16,35 @@
<modules>
<module>animal-sniffer-mvn-plugin</module>
<module>maven-archetype</module>
<module>compiler-plugin-java-9</module>
<module>dependency-exclusion</module>
<module>host-maven-repo-example</module>
<module>maven-archetype</module>
<module>maven-builder-plugin</module>
<module>maven-classifier</module>
<module>maven-copy-files</module>
<module>maven-custom-plugin</module>
<module>maven-exec-plugin</module>
<module>maven-generate-war</module>
<module>maven-integration-test</module>
<module>maven-multi-source</module>
<module>maven-parent-pom-resolution</module>
<module>maven-plugins</module>
<module>maven-polyglot</module>
<module>maven-printing-plugins</module>
<module>maven-properties</module>
<!-- <module>maven-proxy</module> --> <!-- Not a maven project -->
<module>maven-reactor</module>
<module>maven-repositories</module>
<module>maven-simple</module>
<module>maven-surefire-plugin</module>
<module>maven-unused-dependencies</module>
<module>maven-war-plugin</module>
<module>spring-bom</module>
<module>optional-dependencies</module>
<module>version-collision</module>
<module>version-overriding-plugins</module>
<module>versions-maven-plugin</module>
<module>maven-printing-plugins</module>
<module>maven-builder-plugin</module>
<module>host-maven-repo-example</module>
<module>maven-surefire-plugin</module>
<module>maven-parent-pom-resolution</module>
<module>maven-simple</module>
<module>maven-classifier</module>
<module>maven-repositories</module>
<module>maven-reactor</module>
</modules>
<dependencyManagement>
@ -62,4 +64,18 @@
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-opens java.base/java.lang=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -10,8 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>maven-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencyManagement>

View File

@ -9,8 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>messaging-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -16,6 +16,7 @@
<modules>
<module>apache-camel</module>
<module>apache-rocketmq</module>
<module>jgroups</module>
<module>rabbitmq</module>
<module>spring-amqp</module>

View File

@ -1,15 +1,36 @@
package com.baeldung.pattern.cleanarchitecture.usercreation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import org.junit.jupiter.api.Test;
class UserUnitTest {
UserRegisterDsGateway userDsGateway = mock(UserRegisterDsGateway.class);
UserPresenter userPresenter = mock(UserPresenter.class);
UserFactory userFactory = mock(UserFactory.class);
UserInputBoundary interactor = new UserRegisterInteractor(userDsGateway, userPresenter, userFactory);
@Test
void given123Password_whenPasswordIsNotValid_thenIsFalse() {
User user = new CommonUser("Baeldung", "123");
assertThat(user.passwordIsValid()).isFalse();
}
@Test
void givenBaeldungUserAnd123456Password_whenCreate_thenSaveItAndPrepareSuccessView() {
User user = new CommonUser("baeldung", "123456");
UserRequestModel userRequestModel = new UserRequestModel(user.getName(), user.getPassword());
when(userFactory.create(anyString(), anyString())).thenReturn(new CommonUser(user.getName(), user.getPassword()));
interactor.create(userRequestModel);
verify(userDsGateway, times(1)).save(any(UserDsRequestModel.class));
verify(userPresenter, times(1)).prepareSuccessView(any(UserResponseModel.class));
}
}

View File

@ -1,4 +1,6 @@
package com.baeldung;
package com.baeldung.hibernate;
import static org.hibernate.boot.registry.StandardServiceRegistryBuilder.DEFAULT_CFG_RESOURCE_NAME;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -7,19 +9,20 @@ import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
import com.baeldung.uuids.WebSiteUser;
import com.baeldung.uuids.Element;
import com.baeldung.uuids.Reservation;
import com.baeldung.uuids.Sale;
import com.baeldung.hibernate.booleanconverters.model.Question;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
import com.baeldung.hibernate.uuids.WebSiteUser;
import com.baeldung.hibernate.uuids.Element;
import com.baeldung.hibernate.uuids.Reservation;
import com.baeldung.hibernate.uuids.Sale;
public class HibernateUtil {
private static final String DEFAULT_RESOURCE = "manytomany.cfg.xml";
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
private static SessionFactory buildSessionFactory(String resource) {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
@ -29,16 +32,16 @@ public class HibernateUtil {
configuration.addAnnotatedClass(Element.class);
configuration.addAnnotatedClass(Reservation.class);
configuration.addAnnotatedClass(Sale.class);
configuration.configure("manytomany.cfg.xml");
configuration.addAnnotatedClass(Question.class);
configuration.addPackage(Question.class.getPackageName());
configuration.configure(resource);
LOGGER.debug("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
LOGGER.debug("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
@ -46,9 +49,10 @@ public class HibernateUtil {
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
return buildSessionFactory(DEFAULT_RESOURCE);
}
public static SessionFactory getSessionFactory(String resource) {
return buildSessionFactory(resource);
}
}

View File

@ -0,0 +1,86 @@
package com.baeldung.hibernate.booleanconverters.model;
import java.util.UUID;
import org.hibernate.type.NumericBooleanConverter;
import org.hibernate.type.TrueFalseConverter;
import org.hibernate.type.YesNoConverter;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Question {
@Id
private UUID id;
private String content;
@Convert(converter = YesNoConverter.class)
private Boolean correctAnswer;
@Convert(converter = TrueFalseConverter.class)
private Boolean shouldBeAsked;
@Convert(converter = NumericBooleanConverter.class)
private Boolean isEasy;
private Boolean wasAskedBefore;
public Question() {
}
public Question(UUID id, String content, Boolean correctAnswer, Boolean shouldBeAsked, Boolean isEasy, Boolean wasAskedBefore) {
this.id = id;
this.content = content;
this.correctAnswer = correctAnswer;
this.shouldBeAsked = shouldBeAsked;
this.isEasy = isEasy;
this.wasAskedBefore = wasAskedBefore;
}
public UUID getId() {
return id;
}
public String getContent() {
return content;
}
public Boolean getCorrectAnswer() {
return correctAnswer;
}
public Boolean getShouldBeAsked() {
return shouldBeAsked;
}
public Boolean isEasy() {
return isEasy;
}
public Boolean getWasAskedBefore() {
return wasAskedBefore;
}
public void setId(UUID id) {
this.id = id;
}
public void setContent(String content) {
this.content = content;
}
public void setCorrectAnswer(Boolean correctAnswer) {
this.correctAnswer = correctAnswer;
}
public void setShouldBeAsked(Boolean shouldBeAsked) {
this.shouldBeAsked = shouldBeAsked;
}
public void setEasy(Boolean easy) {
isEasy = easy;
}
public void setWasAskedBefore(Boolean wasAskedBefore) {
this.wasAskedBefore = wasAskedBefore;
}
}

View File

@ -0,0 +1,5 @@
@ConverterRegistration(converter = YesNoConverter.class)
package com.baeldung.hibernate.booleanconverters.model;
import org.hibernate.annotations.ConverterRegistration;
import org.hibernate.type.YesNoConverter;

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany;
package com.baeldung.hibernate.manytomany;
import java.util.Properties;
@ -22,7 +22,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.manytomany" })
@ComponentScan({ "com.baeldung.hibernate.manytomany" })
public class PersistenceConfig {
@Autowired
@ -32,7 +32,7 @@ public class PersistenceConfig {
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" });
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;

View File

@ -0,0 +1,8 @@
package com.baeldung.hibernate.manytomany.dao;
import com.baeldung.hibernate.manytomany.dao.common.IOperations;
import com.baeldung.hibernate.manytomany.model.Employee;
public interface IEmployeeDao extends IOperations<Employee>{
}

View File

@ -0,0 +1,8 @@
package com.baeldung.hibernate.manytomany.dao;
import com.baeldung.hibernate.manytomany.dao.common.IOperations;
import com.baeldung.hibernate.manytomany.model.Project;
public interface IProjectDao extends IOperations<Project>{
}

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany.dao.common;
package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany.dao.common;
package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany.dao.common;
package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;

View File

@ -1,10 +1,10 @@
package com.baeldung.manytomany.dao.impl;
package com.baeldung.hibernate.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.manytomany.dao.IEmployeeDao;
import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.dao.IEmployeeDao;
import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.hibernate.manytomany.model.Employee;
@Repository
public class EmployeeDao extends AbstractHibernateDao<Employee> implements IEmployeeDao {

View File

@ -0,0 +1,17 @@
package com.baeldung.hibernate.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.hibernate.manytomany.dao.IProjectDao;
import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.hibernate.manytomany.model.Project;
@Repository
public class ProjectDao extends AbstractHibernateDao<Project> implements IProjectDao {
public ProjectDao() {
super();
setClazz(Project.class);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany.model;
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;

View File

@ -1,4 +1,4 @@
package com.baeldung.manytomany.model;
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;

View File

@ -1,4 +1,4 @@
package com.baeldung.uuids;
package com.baeldung.hibernate.uuids;
import java.util.UUID;
import jakarta.persistence.Entity;

View File

@ -1,4 +1,4 @@
package com.baeldung.uuids;
package com.baeldung.hibernate.uuids;
import java.util.UUID;
import jakarta.persistence.Id;

View File

@ -1,4 +1,4 @@
package com.baeldung.uuids;
package com.baeldung.hibernate.uuids;
import jakarta.persistence.Id;
import jakarta.persistence.Entity;

View File

@ -1,4 +1,4 @@
package com.baeldung.uuids;
package com.baeldung.hibernate.uuids;
import java.util.UUID;
import java.time.LocalDate;

View File

@ -1,8 +0,0 @@
package com.baeldung.manytomany.dao;
import com.baeldung.manytomany.dao.common.IOperations;
import com.baeldung.manytomany.model.Employee;
public interface IEmployeeDao extends IOperations<Employee>{
}

View File

@ -1,8 +0,0 @@
package com.baeldung.manytomany.dao;
import com.baeldung.manytomany.dao.common.IOperations;
import com.baeldung.manytomany.model.Project;
public interface IProjectDao extends IOperations<Project>{
}

View File

@ -1,18 +0,0 @@
package com.baeldung.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.manytomany.dao.IProjectDao;
import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.manytomany.model.Project;
@Repository
public class ProjectDao extends AbstractHibernateDao<Project> implements IProjectDao {
public ProjectDao() {
super();
setClazz(Project.class);
}
}

View File

@ -6,7 +6,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.manytomany.PersistenceConfig;
import com.baeldung.hibernate.manytomany.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)

View File

@ -0,0 +1,158 @@
package com.baeldung.hibernate.booleanconverters;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.UUID;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.booleanconverters.model.Question;
public class HibernateBooleanConverterIntegrationTest {
private static final String PROPERTY_FILE_NAME = "booleanconverters.cfg.xml";
private static SessionFactory sessionFactory;
private static Session session;
@BeforeAll
static void createSessionFactory() {
sessionFactory = HibernateUtil.getSessionFactory(PROPERTY_FILE_NAME);
}
@BeforeEach
void openSessionAndBeginTransaction() {
session = sessionFactory.openSession();
}
@AfterAll
static void closeSessionFactory() {
sessionFactory.close();
}
@Test
void whenFieldAnnotatedWithYesNoConverter_ThenConversionWorks() {
session.beginTransaction();
UUID likeJavaQuestionId = UUID.randomUUID();
UUID sydneyCapitalOfAustraliaQuestionId = UUID.randomUUID();
session.persist(new QuestionBuilder().id(likeJavaQuestionId)
.content("Do you like Java?")
.correctAnswer(true)
.build());
session.persist(new QuestionBuilder().id(sydneyCapitalOfAustraliaQuestionId)
.content("Is Sydney the capital of Australia?")
.correctAnswer(false)
.build());
session.flush();
char likeJavaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class)
.getSingleResult();
char sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", sydneyCapitalOfAustraliaQuestionId), Character.class)
.getSingleResult();
session.close();
assertEquals('Y', likeJavaQuestionCorrectAnswerDbValue);
assertEquals('N', sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue);
}
@Test
void whenFieldAnnotatedWithTrueFalseConverter_ThenConversionWorks() {
session.beginTransaction();
UUID codeTestedQuestionId = UUID.randomUUID();
UUID earningsQuestionId = UUID.randomUUID();
session.persist(new QuestionBuilder().id(codeTestedQuestionId)
.content("Is this code tested?")
.shouldBeAsked(true)
.build());
session.persist(new QuestionBuilder().id(earningsQuestionId)
.content("How much do you earn?")
.shouldBeAsked(false)
.build());
session.flush();
char codeTestedQuestionShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", codeTestedQuestionId), Character.class)
.getSingleResult();
char earningsQuestionsShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", earningsQuestionId), Character.class)
.getSingleResult();
session.close();
assertEquals('T', codeTestedQuestionShouldBeAskedDbValue);
assertEquals('F', earningsQuestionsShouldBeAskedDbValue);
}
@Test
void whenFieldAnnotatedWithNumericBooleanConverter_ThenConversionWorks() {
session.beginTransaction();
UUID earthFlatQuestionId = UUID.randomUUID();
UUID shouldLearnProgrammingQuestionId = UUID.randomUUID();
session.persist(new QuestionBuilder().id(earthFlatQuestionId)
.content("Is the Earth flat?")
.isEasy(true)
.build());
session.persist(new QuestionBuilder().id(shouldLearnProgrammingQuestionId)
.content("Should one learn programming")
.isEasy(false)
.build());
session.flush();
int earthFlatQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", earthFlatQuestionId), Integer.class)
.getSingleResult();
int shouldLearnProgrammingQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", shouldLearnProgrammingQuestionId), Integer.class)
.getSingleResult();
session.close();
assertEquals(1, earthFlatQuestionIsEasyDbValue);
assertEquals(0, shouldLearnProgrammingQuestionIsEasyDbValue);
}
@Test
void givenFieldAnnotatedWithYesNoConverter_WhenDbValueIsLowercase_ThenDomainModelValueNull() {
session.beginTransaction();
UUID mappedToNullQuestionId = UUID.randomUUID();
UUID behaviorIntuitiveQuestionId = UUID.randomUUID();
session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Will correctAnswer be mapped to null?', 'y')", mappedToNullQuestionId))
.executeUpdate();
session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Is this behavior intuitive?', 'n')", behaviorIntuitiveQuestionId))
.executeUpdate();
Question behaviorIntuitiveQuestion = session.get(Question.class, behaviorIntuitiveQuestionId);
Question mappedToNullQuestion = session.get(Question.class, mappedToNullQuestionId);
session.close();
assertNull(behaviorIntuitiveQuestion.getCorrectAnswer());
assertNull(mappedToNullQuestion.getCorrectAnswer());
}
@Test
void givenConverterRegisteredToAutoApply_whenFieldIsNotAnnotated_ThenConversionWorks() {
session.beginTransaction();
UUID likeJavaQuestionId = UUID.randomUUID();
UUID likeKotlinQuestionId = UUID.randomUUID();
session.persist(new QuestionBuilder().id(likeJavaQuestionId)
.content("Do you like Java?")
.wasAskedBefore(true)
.build());
session.persist(new QuestionBuilder().id(likeKotlinQuestionId)
.content("Do you like Kotlin?")
.wasAskedBefore(false)
.build());
session.flush();
char likeJavaQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class)
.getSingleResult();
char likeKotlinQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeKotlinQuestionId), Character.class)
.getSingleResult();
session.close();
assertEquals('Y', likeJavaQuestionWasAskedBeforeDbValue);
assertEquals('N', likeKotlinQuestionWasAskedBeforeDbValue);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.hibernate.booleanconverters;
import java.util.UUID;
import com.baeldung.hibernate.booleanconverters.model.Question;
public class QuestionBuilder {
private UUID id;
private String content;
private Boolean correctAnswer;
private Boolean shouldBeAsked;
private Boolean isEasy;
private Boolean wasAskedBefore;
public QuestionBuilder id(UUID id) {
this.id = id;
return this;
}
public QuestionBuilder content(String content) {
this.content = content;
return this;
}
public QuestionBuilder correctAnswer(Boolean correctAnswer) {
this.correctAnswer = correctAnswer;
return this;
}
public QuestionBuilder shouldBeAsked(Boolean shouldBeAsked) {
this.shouldBeAsked = shouldBeAsked;
return this;
}
public QuestionBuilder isEasy(Boolean isEasy) {
this.isEasy = isEasy;
return this;
}
public QuestionBuilder wasAskedBefore(Boolean wasAskedBefore) {
this.wasAskedBefore = wasAskedBefore;
return this;
}
public Question build() {
return new Question(id, content, correctAnswer, shouldBeAsked, isEasy, wasAskedBefore);
}
}

View File

@ -13,9 +13,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.manytomany.PersistenceConfig;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)

View File

@ -15,9 +15,9 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
import com.baeldung.HibernateUtil;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
import com.baeldung.hibernate.HibernateUtil;
/**
* Configured in: manytomany.cfg.xml

View File

@ -1,18 +1,12 @@
package com.baeldung.hibernate.uuids;
import com.baeldung.HibernateUtil;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.uuids.Reservation;
import com.baeldung.uuids.Sale;
import com.baeldung.uuids.WebSiteUser;
import com.baeldung.uuids.Element;
import org.assertj.core.api.Assertions;
import java.io.IOException;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import java.util.UUID;

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:h2:mem:booleanconvertersdb;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/test/resources/booleanconverters/init_database.sql'</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">none</property>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,9 @@
CREATE TABLE Question (
id UUID,
content VARCHAR,
correctAnswer CHAR,
shouldBeAsked CHAR,
isEasy TINYINT,
wasAskedBefore CHAR,
PRIMARY KEY (id)
)

12
pom.xml
View File

@ -363,7 +363,6 @@
<module>muleesb</module>
<module>web-modules</module>
<module>persistence-modules/deltaspike</module> <!-- delta spike it doesn't yet the jakarta API-->
</modules>
@ -412,7 +411,6 @@
<module>spring-4</module>
<module>spring-aop</module>
<module>spring-bom</module>
<module>spring-cloud-modules</module>
<!-- <module>spring-cloud-cli</module> --> <!-- Not a maven project -->
@ -551,7 +549,6 @@
<module>lombok-modules/lombok-custom</module>
<module>muleesb</module>
<module>web-modules</module>
<module>persistence-modules/deltaspike</module> <!-- delta spike it doesn't yet the jakarta API-->
</modules>
@ -591,7 +588,6 @@
<module>spring-4</module>
<module>spring-bom</module>
<module>spring-cloud-modules</module>
<!-- <module>spring-cloud-cli</module> --> <!-- Not a maven project -->
@ -836,7 +832,6 @@
<module>apache-olingo</module>
<module>apache-poi-2</module>
<module>apache-rocketmq</module>
<module>apache-thrift</module>
<module>apache-tika</module>
@ -849,7 +844,6 @@
<module>bazel</module>
<module>google-auto-project</module>
<module>ddd</module>
<module>discord4j</module>
<module>disruptor</module>
<module>dozer</module>
<module>dubbo</module>
@ -906,7 +900,6 @@
<module>protobuffer</module>
<module>reactor-core</module>
<module>rsocket</module>
<module>slack</module>
<!-- Modules from default second-->
@ -941,6 +934,7 @@
<module>persistence-modules/questdb</module>
<module>vaadin</module>
<module>libraries-3</module>
<module>web-modules/apache-tapestry</module>
</modules>
<properties>
@ -1088,7 +1082,6 @@
<module>apache-olingo</module>
<module>apache-poi-2</module>
<module>apache-rocketmq</module>
<module>apache-thrift</module>
<module>apache-tika</module>
@ -1101,7 +1094,6 @@
<module>bazel</module>
<module>google-auto-project</module>
<module>ddd</module>
<module>discord4j</module>
<module>disruptor</module>
<module>dozer</module>
@ -1160,7 +1152,6 @@
<module>protobuffer</module>
<module>reactor-core</module>
<module>rsocket</module>
<module>slack</module>
<!-- Modules from default second-->
@ -1195,6 +1186,7 @@
<module>persistence-modules/questdb</module>
<module>vaadin</module>
<module>libraries-3</module>
<module>web-modules/apache-tapestry</module>
</modules>
<properties>

View File

@ -9,9 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<artifactId>saas-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -16,11 +16,13 @@
</parent>
<modules>
<module>discord4j</module>
<module>jira-rest-integration</module>
<module>sentry-servlet</module>
<module>slack</module>
<module>stripe</module>
<module>twilio</module>
<module>twitter4j</module>
<module>sentry-servlet</module>
</modules>
<build>

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