Merge branch 'eugenp:master' into master

This commit is contained in:
Kingsley✨ 2023-04-30 21:28:54 +05:30 committed by GitHub
commit 183761cb3f
216 changed files with 2828 additions and 727 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

@ -13,4 +13,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- More articles: [[<-- prev]](../apache-httpclient)

View File

@ -0,0 +1,126 @@
package com.baeldung.httpclient.expandUrl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hc.client5.http.classic.methods.HttpHead;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class HttpClientExpandUrlLiveTest {
private static CloseableHttpClient httpClient;
@BeforeAll
static void setup() {
httpClient = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
}
@AfterAll
static void tearDown() throws IOException {
if (httpClient != null) {
httpClient.close();
}
}
@Test
void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
private String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
return newUrl;
}
final String expandSafe(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
return newUrl;
}
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
try {
HttpHead request = new HttpHead(url);
Pair<Integer, String> resp = httpClient.execute(request, response -> {
final int statusCode = response.getCode();
if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<>(statusCode, url);
}
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return new ImmutablePair<>(statusCode, newUrl);
});
return resp;
} catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<>(500, url);
}
}
private String expandSingleLevel(final String url) throws IOException {
try {
HttpHead request = new HttpHead(url);
String expandedUrl = httpClient.execute(request, response -> {
final int statusCode = response.getCode();
if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
return headers[0].getValue();
});
return expandedUrl;
} catch (final IllegalArgumentException uriEx) {
return url;
}
}
}

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

@ -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

@ -0,0 +1,98 @@
package com.baeldung.methods;
public class Car {
private final String make;
private final String model;
private final int year;
private final String color;
private final boolean automatic;
private final int numDoors;
private final String features;
private Car(CarBuilder carBuilder) {
this.make = carBuilder.make;
this.model = carBuilder.model;
this.year = carBuilder.year;
this.color = carBuilder.color;
this.automatic = carBuilder.automatic;
this.numDoors = carBuilder.numDoors;
this.features = carBuilder.features;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public String getColor() {
return color;
}
public boolean isAutomatic() {
return automatic;
}
public int getNumDoors() {
return numDoors;
}
public String getFeatures() {
return features;
}
public static class CarBuilder {
private final String make;
private final String model;
private final int year;
private String color = "unknown";
private boolean automatic = false;
private int numDoors = 4;
private String features = "";
public CarBuilder(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public CarBuilder color(String color) {
this.color = color;
return this;
}
public CarBuilder automatic(boolean automatic) {
this.automatic = automatic;
return this;
}
public CarBuilder numDoors(int numDoors) {
this.numDoors = numDoors;
return this;
}
public CarBuilder features(String features) {
this.features = features;
return this;
}
public Car build() {
return new Car(this);
}
}
@Override
public String toString() {
return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.methods;
import java.io.Serializable;
public class Motorcycle extends Vehicle implements Serializable {
private static final long serialVersionUID = 5973661295933599929L;
private int year;
private String features = "";
public Motorcycle() {
super();
}
public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
super(make, model, color, weight, statusNew);
this.year = year;
}
public Motorcycle(Vehicle vehicle, int year) {
super(vehicle);
this.year = year;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void setFeatures(String features) {
this.features = features;
}
public String getFeatures() {
return features;
}
public void addMotorcycleFeatures(String... features) {
StringBuilder str = new StringBuilder(this.getFeatures());
for (String feature : features) {
if (!str.toString().isEmpty())
str.append(", ");
str.append(feature);
}
this.setFeatures(str.toString());
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.methods;
public class Vehicle {
static String defaultValue = "DEFAULT";
private String make = defaultValue;
private String model = defaultValue;
private String color = defaultValue;
private int weight = 0;
private boolean statusNew = true;
public Vehicle() {
super();
}
public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
this.make = make;
this.model = model;
this.color = color;
this.weight = weight;
this.statusNew = statusNew;
}
public Vehicle(Vehicle vehicle) {
this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
}
@Override
public String toString() {
return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.methods;
public class VehicleProcessor {
Vehicle processVehicle(String make, String model, String color, int weight, boolean status) {
return new Vehicle(make, model, color, weight, status);
}
Vehicle processVehicle(Vehicle vehicle) {
return new Vehicle(vehicle);
}
Car processCar(Car car) {
return new Car.CarBuilder(car.getMake(), car.getModel(), car.getYear()).color(car.getColor())
.automatic(car.isAutomatic())
.features(car.getFeatures())
.build();
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.methods;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class VehicleProcessorUnitTest {
VehicleProcessor vehicleProcessor = new VehicleProcessor();
Vehicle vehicle = new Vehicle("Ford", "Focus", "red", 2200, true);
@Test
void givenAllArguments_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Vehicle veh = vehicleProcessor.processVehicle("Ford", "Focus", "red", 2200, true);
assertThat(veh.toString()).hasToString(vehicle.toString());
}
@Test
void givenParameterObject_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Vehicle veh = vehicleProcessor.processVehicle(vehicle);
assertThat(veh.toString()).hasToString(vehicle.toString());
}
@Test
void givenJavaBeanPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "yellow", 235, true, 2023);
motorcycle.setFeatures("GPS");
vehicleProcessor.processVehicle(motorcycle);
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("GPS");
}
@Test
void givenJavaVarargs_whenMethodCall_thenAssertTheReturnedConcatenatedString() {
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "red", 350, true, 2023);
motorcycle.addMotorcycleFeatures("abs");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs");
motorcycle.addMotorcycleFeatures("navi", "charger");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger");
motorcycle.addMotorcycleFeatures("wifi", "phone", "satellite");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger, wifi, phone, satellite");
}
@Test
void givenJavaBuilderPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Car car = new Car.CarBuilder("Ford", "Focus", 2023).color("blue")
.automatic(true)
.features("abs, navi, charger, wifi, phone, satellite")
.build();
Car result = vehicleProcessor.processCar(car);
assertThat(result.toString()).hasToString(car.toString());
}
}

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

@ -1,7 +1,7 @@
<?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">
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-networking</artifactId>
<name>core-java-networking</name>
@ -19,6 +19,11 @@
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache.httpclient.version}</version>
</dependency>
</dependencies>
<build>
@ -27,6 +32,7 @@
<properties>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<apache.httpclient.version>4.5.14</apache.httpclient.version>
</properties>
</project>

View File

@ -1,11 +1,19 @@
package com.baeldung.networking.url;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@ -101,4 +109,44 @@ public class UrlUnitTest {
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
}
@Test
public void givenUrlParameters_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameter("topic", "java");
uriBuilder.addParameter("version", "8");
URL url = uriBuilder.build().toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParametersInMap_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
Map<String, String> paramMap = ImmutableMap.of("topic", "java", "version", "8");
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameters(paramMap.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
URL url = uriBuilder.build().toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
URL url = UriComponentsBuilder.newInstance()
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
}

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

@ -1,4 +1,4 @@
package com.baeldung.java8;
package com.baeldung.streams.flatmap.map;
import org.junit.Test;
@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Java8MapAndFlatMap {
public class Java8MapAndFlatMapUnitTest {
@Test
public void givenStream_whenCalledMap_thenProduceList() {

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

@ -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

@ -1,25 +0,0 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -1,4 +0,0 @@
## Core Java Cookbooks and Examples
### Relevant Articles:

View File

@ -1,95 +0,0 @@
<?xml version="1.0"?>
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
<properties>
<command>SELECT * FROM customers</command>
<concurrency>1008</concurrency>
<datasource><null/></datasource>
<escape-processing>true</escape-processing>
<fetch-direction>1000</fetch-direction>
<fetch-size>0</fetch-size>
<isolation-level>2</isolation-level>
<key-columns>
</key-columns>
<map>
</map>
<max-field-size>0</max-field-size>
<max-rows>0</max-rows>
<query-timeout>0</query-timeout>
<read-only>true</read-only>
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
<show-deleted>false</show-deleted>
<table-name>customers</table-name>
<url>jdbc:h2:mem:testdb</url>
<sync-provider>
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-provider-name>
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
<sync-provider-version>1.0</sync-provider-version>
<sync-provider-grade>2</sync-provider-grade>
<data-source-lock>1</data-source-lock>
</sync-provider>
</properties>
<metadata>
<column-count>2</column-count>
<column-definition>
<column-index>1</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>true</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>11</column-display-size>
<column-label>ID</column-label>
<column-name>ID</column-name>
<schema-name>PUBLIC</schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>CUSTOMERS</table-name>
<catalog-name>TESTDB</catalog-name>
<column-type>4</column-type>
<column-type-name>INTEGER</column-type-name>
</column-definition>
<column-definition>
<column-index>2</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>true</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>50</column-display-size>
<column-label>NAME</column-label>
<column-name>NAME</column-name>
<schema-name>PUBLIC</schema-name>
<column-precision>50</column-precision>
<column-scale>0</column-scale>
<table-name>CUSTOMERS</table-name>
<catalog-name>TESTDB</catalog-name>
<column-type>12</column-type>
<column-type-name>VARCHAR</column-type-name>
</column-definition>
</metadata>
<data>
<currentRow>
<columnValue>1</columnValue>
<columnValue>Customer1</columnValue>
</currentRow>
<currentRow>
<columnValue>2</columnValue>
<columnValue>Customer2</columnValue>
</currentRow>
<currentRow>
<columnValue>3</columnValue>
<columnValue>Customer3</columnValue>
</currentRow>
<currentRow>
<columnValue>4</columnValue>
<columnValue>Customer4</columnValue>
</currentRow>
<currentRow>
<columnValue>5</columnValue>
<columnValue>Customer5</columnValue>
</currentRow>
</data>
</webRowSet>

View File

@ -1,174 +0,0 @@
<?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</artifactId>
<name>core-java</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.core.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<!-- maven plugins -->
<spring.core.version>4.3.20.RELEASE</spring.core.version>
</properties>
</project>

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,11 +0,0 @@
package com.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}

View File

@ -1,42 +0,0 @@
package com.baeldung.filesystem.jndi;
import java.io.File;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class LookupFSJNDI {
private InitialContext ctx = null;
public LookupFSJNDI() throws NamingException {
super();
init();
}
private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env);
}
public InitialContext getCtx() {
return ctx;
}
public File getFile(String fileName) {
File file;
try {
file = (File) getCtx().lookup(fileName);
} catch (NamingException e) {
file = null;
}
return file;
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.jsonposturlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}

View File

@ -1,9 +0,0 @@
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -1,5 +0,0 @@
Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
Main-Class: com.baeldung.instrumentation.application.Launcher

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<!-- JDO tutorial "unit" -->
<persistence-unit name="Tutorial">
<exclude-unlisted-classes/>
<properties>
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
<property name="javax.jdo.option.ConnectionPassword" value=""/>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -1,6 +0,0 @@
dataSourceClassName=//TBD
dataSource.user=//TBD
dataSource.password=//TBD
dataSource.databaseName=//TBD
dataSource.portNumber=//TBD
dataSource.serverName=//TBD

View File

@ -1,6 +0,0 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -1,9 +0,0 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

View File

@ -1,19 +0,0 @@
<?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>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

View File

@ -1,41 +0,0 @@
package com.baeldung.arrays;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
public class ArraysJoinAndSplitJUnitTest {
private final String[] sauces = { "Marinara", "Olive Oil" };
private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" };
private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" };
private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" };
@Test
public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
System.arraycopy(sauces, 0, toppings, 0, sauces.length);
int AddedSoFar = sauces.length;
System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
AddedSoFar += cheeses.length;
System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
}
@Test
public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
int ordersHalved = (customers.length / 2) + (customers.length % 2);
String[] driverOne = Arrays.copyOf(customers, ordersHalved);
String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" });
Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" });
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,2 +0,0 @@
#Copy a File with Java (www.Baeldung.com)
Copying Files with Java is Fun!

View File

@ -1 +0,0 @@
Test of JNDI on file.

View File

@ -1 +0,0 @@
Hello world

View File

@ -1 +0,0 @@
Hello world 1

View File

@ -1,2 +0,0 @@
Hello world
Test line

View File

@ -1 +0,0 @@
John,Adam-Tom

View File

@ -1,2 +0,0 @@
Hello world
Hi, John

View File

@ -17,7 +17,6 @@
<modules>
<!--Won't be upgraded to JDK 17 -->
<!--<module>core-java</module> -->
<!--<module>core-java-8</module> -->
<!--<module>core-java-8-2</module> -->
<!--<module>core-java-8-datetime</module> -->

View File

@ -4,6 +4,7 @@
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>javaxval-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>javaxval-2</name>
<parent>

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

@ -1 +1,4 @@
log4j.rootLogger=INFO, stdout
log4j.rootLogger=INFO,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.logger.org.datanucleus=DEBUG

View File

@ -115,6 +115,24 @@
<artifactId>mysql</artifactId>
<version>${testcontainers-version}</version>
</dependency>
<!-- flexypool -->
<dependency>
<groupId>com.vladmihalcea.flexy-pool</groupId>
<artifactId>flexy-micrometer-metrics</artifactId>
<version>${flexy-pool.version}</version>
</dependency>
<dependency>
<groupId>com.vladmihalcea.flexy-pool</groupId>
<artifactId>flexy-hikaricp</artifactId>
<version>${flexy-pool.version}</version>
<exclusions>
<exclusion>
<groupId>com.vladmihalcea.flexy-pool</groupId>
<artifactId>flexy-dropwizard-metrics</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring Core dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -147,6 +165,7 @@
<plugins>
<!-- Reladomo -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven-antrun-plugin.version}</version>
<executions>
@ -284,6 +303,7 @@
<HikariCP.version>5.0.1</HikariCP.version>
<ebean.version>13.15.2</ebean.version>
<debezium.version>2.1.3.Final</debezium.version>
<flexy-pool.version>2.2.3</flexy-pool.version>
<testcontainers-version>1.17.6</testcontainers-version>
</properties>

View File

@ -0,0 +1,109 @@
package com.baeldung.libraries.flexypool;
import com.vladmihalcea.flexypool.FlexyPoolDataSource;
import com.vladmihalcea.flexypool.adaptor.HikariCPPoolAdapter;
import com.vladmihalcea.flexypool.config.Configuration;
import com.vladmihalcea.flexypool.connection.ConnectionDecoratorFactoryResolver;
import com.vladmihalcea.flexypool.event.ConnectionAcquireTimeThresholdExceededEvent;
import com.vladmihalcea.flexypool.event.ConnectionAcquireTimeoutEvent;
import com.vladmihalcea.flexypool.event.ConnectionLeaseTimeThresholdExceededEvent;
import com.vladmihalcea.flexypool.event.EventListener;
import com.vladmihalcea.flexypool.metric.micrometer.MicrometerMetrics;
import com.vladmihalcea.flexypool.strategy.IncrementPoolOnTimeoutConnectionAcquiringStrategy;
import com.vladmihalcea.flexypool.strategy.RetryConnectionAcquiringStrategy;
import com.vladmihalcea.flexypool.strategy.UniqueNamingStrategy;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@org.springframework.context.annotation.Configuration
public class FlexypoolConfig {
@SuppressWarnings("unchecked")
@Bean(initMethod = "start", destroyMethod = "stop")
public FlexyPoolDataSource<HikariDataSource> flexypoolDataSource() {
Configuration<HikariDataSource> configuration = flexypoolConfiguration();
return new FlexyPoolDataSource<>(configuration, new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory<>(5), new RetryConnectionAcquiringStrategy.Factory<>(2));
}
@Bean
public Configuration<HikariDataSource> flexypoolConfiguration() {
HikariDataSource dataSource = hikariDataSource();
return new Configuration.Builder<>(UUID.randomUUID().toString(), dataSource, HikariCPPoolAdapter.FACTORY).setMetricsFactory(MicrometerMetrics::new)
.setConnectionProxyFactory(ConnectionDecoratorFactoryResolver.INSTANCE.resolve())
.setMetricLogReporterMillis(TimeUnit.SECONDS.toMillis(5))
.setMetricNamingUniqueName(UniqueNamingStrategy.INSTANCE)
.setJmxEnabled(true)
.setJmxAutoStart(true)
.setConnectionAcquireTimeThresholdMillis(50L)
.setConnectionLeaseTimeThresholdMillis(250L)
.setEventListenerResolver(() -> Arrays.asList(new ConnectionAcquireTimeoutEventListener(), new ConnectionAcquireTimeThresholdExceededEventListener(), new ConnectionLeaseTimeThresholdExceededEventListener()))
.build();
}
@Bean
public HikariDataSource hikariDataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
config.setUsername("");
config.setPassword("");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("minimumPoolSize", "1");
config.addDataSourceProperty("maximumPoolSize", "3");
config.addDataSourceProperty("connectionTimeout", "1000");
return new HikariDataSource(config);
}
}
class ConnectionAcquireTimeThresholdExceededEventListener extends EventListener<ConnectionAcquireTimeThresholdExceededEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeThresholdExceededEventListener.class);
public ConnectionAcquireTimeThresholdExceededEventListener() {
super(ConnectionAcquireTimeThresholdExceededEvent.class);
}
@Override
public void on(ConnectionAcquireTimeThresholdExceededEvent event) {
LOGGER.info("ConnectionAcquireTimeThresholdExceededEvent Caught event {}", event);
}
}
class ConnectionLeaseTimeThresholdExceededEventListener extends EventListener<ConnectionLeaseTimeThresholdExceededEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLeaseTimeThresholdExceededEventListener.class);
public ConnectionLeaseTimeThresholdExceededEventListener() {
super(ConnectionLeaseTimeThresholdExceededEvent.class);
}
@Override
public void on(ConnectionLeaseTimeThresholdExceededEvent event) {
LOGGER.info("ConnectionLeaseTimeThresholdExceededEvent Caught event {}", event);
}
}
class ConnectionAcquireTimeoutEventListener extends EventListener<ConnectionAcquireTimeoutEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeoutEventListener.class);
public ConnectionAcquireTimeoutEventListener() {
super(ConnectionAcquireTimeoutEvent.class);
}
@Override
public void on(ConnectionAcquireTimeoutEvent event) {
LOGGER.info("ConnectionAcquireTimeoutEvent Caught event {}", event);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.libraries.flexypool;
import com.baeldung.libraries.hikaricp.Employee;
import com.vladmihalcea.flexypool.FlexyPoolDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class FlexypoolDemoApplication {
private static FlexyPoolDataSource<HikariDataSource> poolDataSource;
public FlexypoolDemoApplication(FlexyPoolDataSource<HikariDataSource> poolDataSource) {
FlexypoolDemoApplication.poolDataSource = poolDataSource;
}
public static List<Employee> getEmployees() throws SQLException {
String SQL_QUERY = "select * from emp";
List<Employee> employees;
try (Connection con = poolDataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<>();
Employee employee;
while (rs.next()) {
employee = new Employee();
employee.setEmpNo(rs.getInt("empno"));
employee.setEname(rs.getString("ename"));
employee.setJob(rs.getString("job"));
employee.setMgr(rs.getInt("mgr"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSal(rs.getInt("sal"));
employee.setComm(rs.getInt("comm"));
employee.setDeptno(rs.getInt("deptno"));
employees.add(employee);
}
}
return employees;
}
public static void main(String[] args) throws SQLException {
SpringApplication.run(FlexypoolDemoApplication.class, args);
List<Employee> employees = getEmployees();
System.out.println(employees);
}
}

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);
}
}

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