Merge branch 'eugenp:master' into master

This commit is contained in:
Zahid Khan 2023-05-04 19:55:08 +05:30 committed by GitHub
commit e68a846239
411 changed files with 5756 additions and 1508 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

@ -3,9 +3,9 @@
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>lambda</artifactId>
<artifactId>lambda-function</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>lambda</name>
<name>lambda-function</name>
<packaging>jar</packaging>
<parent>

View File

@ -6,4 +6,5 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)

View File

@ -0,0 +1,2 @@
## Relevant Articles
- TBD

View File

@ -0,0 +1,65 @@
<?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>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>core-java-20</artifactId>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>20</source>
<target>20</target>
<compilerArgs>
<arg>--enable-preview</arg>
<arg>--add-modules=jdk.incubator.concurrent</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview --add-modules=jdk.incubator.concurrent</argLine>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,33 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
public class Controller {
private final Service service = new Service();
public void processRequest(HttpServletRequest request, HttpServletResponse response, User loggedInUser) {
Optional<Data> data = service.getData(request, loggedInUser);
if (data.isPresent()) {
try {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.print(data.get());
out.flush();
response.setStatus(200);
} catch (IOException e) {
response.setStatus(500);
}
} else {
response.setStatus(400);
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id, User user) {
return user.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
private final Controller controller = new Controller();
private final ExecutorService executor = Executors.newFixedThreadPool(5);
public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
Future<?> future = executor.submit(() ->
controller.processRequest(request, response, user.get()));
future.get();
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class Service {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request, User loggedInUser) {
String id = request.getParameter("data_id");
return repository.getData(id, loggedInUser);
}
}

View File

@ -0,0 +1,3 @@
package com.baeldung.scopedvalues.data;
public record Data(String id, String title, String description) {}

View File

@ -0,0 +1,3 @@
package com.baeldung.scopedvalues.data;
public record User(String id, String name, String password, boolean isAdmin) {}

View File

@ -0,0 +1,37 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
public class Controller {
private final Service internalService = new Service();
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
Optional<Data> data = internalService.getData(request);
ScopedValue.where(Server.LOGGED_IN_USER, null)
.run(internalService::extractData);
if (data.isPresent()) {
try {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.print(data.get());
out.flush();
response.setStatus(200);
} catch (IOException e) {
response.setStatus(500);
}
} else {
response.setStatus(400);
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id) {
User loggedInUser = Server.LOGGED_IN_USER.get();
return loggedInUser.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.util.List;
import java.util.Optional;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
private final Controller controller = new Controller();
public void serve(HttpServletRequest request, HttpServletResponse response) {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
ScopedValue.where(LOGGED_IN_USER, user.get())
.run(() -> controller.processRequest(request, response));
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class Service {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request) {
String id = request.getParameter("data_id");
return repository.getData(id);
}
public void extractData() {
User loggedInUser = Server.LOGGED_IN_USER.get();
assert loggedInUser == null;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.StructuredTaskScope;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class Controller {
private final InternalService internalService = new InternalService();
private final ExternalService externalService = new ExternalService();
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<Optional<Data>> internalData = scope.fork(() -> internalService.getData(request));
Future<String> externalData = scope.fork(externalService::getData);
try {
scope.join();
scope.throwIfFailed();
Optional<Data> data = internalData.resultNow();
if (data.isPresent()) {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.println(data.get());
out.print(externalData.resultNow());
out.flush();
response.setStatus(200);
} else {
response.setStatus(400);
}
} catch (InterruptedException | ExecutionException | IOException e) {
response.setStatus(500);
}
}
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.scopedvalues.scoped.inheriting;
public class ExternalService {
public String getData() {
return "External data";
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class InternalService {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request) {
String id = request.getParameter("data_id");
return repository.getData(id);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id) {
User loggedInUser = Server.LOGGED_IN_USER.get();
return loggedInUser.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.util.List;
import java.util.Optional;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
private final Controller controller = new Controller();
public void serve(HttpServletRequest request, HttpServletResponse response) {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
ScopedValue.where(LOGGED_IN_USER, user.get())
.run(() -> controller.processRequest(request, response));
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.classic;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.ExecutionException;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws InterruptedException, IOException, ExecutionException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws InterruptedException, ExecutionException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.scoped;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]\nExternal data");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}

View File

@ -11,5 +11,6 @@ This module contains articles about Java 8 core features
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
- [Java Helper vs. Utility Classes](https://www.baeldung.com/java-helper-vs-utility-classes)
- [[<-- Prev]](/core-java-modules/core-java-8)

View File

@ -2,4 +2,5 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)

View File

@ -8,5 +8,5 @@ This module contains articles about Project Jigsaw and the Java Platform Module
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)

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

@ -0,0 +1,17 @@
package com.baeldung.concurrent.completablefuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture;
public class NonBlockingExample {
private static final Logger logger = LoggerFactory.getLogger(NonBlockingExample.class);
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> "Baeldung")
.thenApply(String::length)
.thenAccept(s -> logger.info(String.valueOf(s)));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.concurrent.completablefuture;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BlockingUnitTest {
@Test
void givenCompletableFuture_whenGet_thenReturnResult()
throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture
.supplyAsync(() -> "Baeldung")
.thenApply(String::toUpperCase);
assertEquals("BAELDUNG", completableFuture.get());
}
@Test
void givenCompletableFuture_whenJoin_thenReturnResult() {
CompletableFuture<String> completableFuture = CompletableFuture
.supplyAsync(() -> "Blocking")
.thenApply(s -> s + " Operation")
.thenApply(String::toLowerCase);
assertEquals("blocking operation", completableFuture.join());
}
}

View File

@ -5,3 +5,5 @@ This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [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

@ -0,0 +1,31 @@
package com.baeldung.bufferedreadervsfilereader;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderUnitTest {
@Test
public void whenReadingAFile_thenReadsLineByLine() {
StringBuilder result = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
String line;
while((line = br.readLine()) != null) {
result.append(line);
result.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("first line\nsecond line\nthird line\n", result.toString());
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.bufferedreadervsfilereader;
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FileReaderUnitTest {
@Test
public void whenReadingAFile_thenReadsCharByChar() {
StringBuilder result = new StringBuilder();
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
int i = fr.read();
while(i != -1) {
result.append((char)i);
i = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("qwerty", result.toString());
}
}

View File

@ -0,0 +1,85 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
public class NextLineVsNextIntUnitTest {
@Test
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
String input = "42\n";
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
assertEquals(42, num1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
}
@Test
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
String input = "Nan\n";
//nextLine() -> NumberFormatException
Scanner sc1 = new Scanner(input);
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
//nextInt() -> InputMismatchException
Scanner sc2 = new Scanner(input);
assertThrows(InputMismatchException.class, sc2::nextInt);
}
@Test
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
String input = "42 is a magic number\n";
//nextInt() to read '42'
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// call nextInt() again on "is"
assertThrows(InputMismatchException.class, sc2::nextInt);
String theNextToken = sc2.next();
assertEquals("is", theNextToken);
theNextToken = sc2.next();
assertEquals("a", theNextToken);
}
@Test
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
String input = new StringBuilder().append("42\n")
.append("It is a magic number.\n")
.toString();
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
String nextLineText1 = sc1.nextLine();
assertEquals(42, num1);
assertEquals("It is a magic number.", nextLineText1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// nextInt() leaves the newline character (\n) behind
String nextLineText2 = sc2.nextLine();
assertEquals("", nextLineText2);
}
}

View File

@ -0,0 +1,3 @@
first line
second line
third line

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

@ -10,4 +10,3 @@
- [Serialize a Lambda in Java](https://www.baeldung.com/java-serialize-lambda)
- [Convert Anonymous Class into Lambda in Java](https://www.baeldung.com/java-from-anonymous-class-to-lambda)
- [When to Use Callable and Supplier in Java](https://www.baeldung.com/java-callable-vs-supplier)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)

View File

@ -10,4 +10,5 @@
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascals Triangle](https://www.baeldung.com/java-pascal-triangle)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)

View File

@ -23,11 +23,17 @@
<artifactId>javaluator</artifactId>
<version>${javaluator.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
</dependencies>
<properties>
<exp4j.version>0.4.8</exp4j.version>
<javaluator.version>3.0.3</javaluator.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
</properties>
</project>

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

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

@ -14,5 +14,4 @@ This module contains articles about core Java non-blocking input and output (IO)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
- [Find Files that Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [[<-- Prev]](/core-java-modules/core-java-nio)

View File

@ -1,4 +1,4 @@
### Relevant Articles:
- [Java Program to Calculate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
- More articles: [[<-- prev]](../core-java-numbers-5)
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
- More articles: [[<-- prev]](../core-java-numbers-5)

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

@ -0,0 +1,83 @@
package com.baeldung.regex.aftermatch;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GetTextAfterTheRegexMatchUnitTest {
private static final String INPUT1 = "Some text, targetValue=Regex is cool";
private static final String INPUT2 = "Some text. targetValue=Java is cool. some other text";
@Test
void whenUsingSplit_thenGetExpectedString() {
String result1 = INPUT1.split("targetValue=")[1];
assertEquals("Regex is cool", result1);
String afterFirstSplit = INPUT2.split("targetValue=")[1];
assertEquals("Java is cool. some other text", afterFirstSplit);
String result2 = afterFirstSplit.split("[.]")[0];
assertEquals("Java is cool", result2);
// if use the dot as the regex for splitting, the result array is empty
String[] splitByDot = INPUT2.split("targetValue=")[1].split(".");
assertEquals(0, splitByDot.length);
}
@Test
void whenUsingReplaceAll_thenGetExpectedString() {
String result1 = INPUT1.replaceAll(".*targetValue=", "");
assertEquals("Regex is cool", result1);
String afterFirstReplace = INPUT2.replaceAll(".*targetValue=", "");
assertEquals("Java is cool. some other text", afterFirstReplace);
String result2 = afterFirstReplace.replaceAll("[.].*", "");
assertEquals("Java is cool", result2);
}
@Test
void whenUsingRegexGrouping_thenGetExpectedString() {
Pattern p1 = Pattern.compile("targetValue=(.*)");
Matcher m1 = p1.matcher(INPUT1);
assertTrue(m1.find());
String result1 = m1.group(1);
assertEquals("Regex is cool", result1);
Pattern p2 = Pattern.compile("targetValue=([^.]*)");
Matcher m2 = p2.matcher(INPUT2);
assertTrue(m2.find());
String result2 = m2.group(1);
assertEquals("Java is cool", result2);
Pattern p3 = Pattern.compile("targetValue=(.*?)[.]");
Matcher m3 = p3.matcher(INPUT2);
assertTrue(m3.find());
String result3 = m3.group(1);
assertEquals("Java is cool", result3);
}
@Test
void whenUsingLookaround_thenGetExpectedString() {
Pattern p1 = Pattern.compile("(?<=targetValue=).*");
Matcher m1 = p1.matcher(INPUT1);
assertTrue(m1.find());
String result1 = m1.group();
assertEquals("Regex is cool", result1);
Pattern p2 = Pattern.compile("(?<=targetValue=)[^.]*");
Matcher m2 = p2.matcher(INPUT2);
assertTrue(m2.find());
String result2 = m2.group();
assertEquals("Java is cool", result2);
Pattern p3 = Pattern.compile("(?<=targetValue=).*(?=[.])");
Matcher m3 = p3.matcher(INPUT2);
assertTrue(m3.find());
String result3 = m3.group();
assertEquals("Java is cool", result3);
}
}

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,4 +10,3 @@
- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
- [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings)
- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)

View File

@ -0,0 +1 @@
- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)

View File

@ -0,0 +1,72 @@
<?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-streams-5</artifactId>
<name>core-java-streams-5</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>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit-jupiter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.23.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-streams-4</finalName>
<resources>
<resource>
<directory>../core-java-streams-4/src/main</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- testing -->
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
</properties>
</project>

View File

@ -34,4 +34,4 @@ public class Book {
public void setYearPublished(int yearPublished) {
this.yearPublished = yearPublished;
}
}
}

View File

@ -37,4 +37,4 @@ public class BookSpliterator<T> implements Spliterator<T> {
public int characteristics() {
return CONCURRENT;
}
}
}

View File

@ -1,6 +1,5 @@
package parallelstream;
package com.baeldung.parallelstream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;

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

@ -39,8 +39,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>

View File

@ -0,0 +1,58 @@
package com.baeldung.charfreq;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CharacterWithHighestFrequency {
public static Character byStream(String input) {
return input.chars()
.mapToObj(x -> (char) x)
.collect(groupingBy(x -> x, counting()))
.entrySet()
.stream()
.max(comparingByValue())
.get()
.getKey();
}
public static Set<Character> byMap(String input) {
Map<Character, Integer> map = new HashMap<>();
for (char c : input.toCharArray()) {
map.compute(c, (character, count) -> count == null ? 1 : ++count);
}
int maxCount = map.values()
.stream()
.mapToInt(Integer::intValue)
.max()
.getAsInt();
return map.keySet()
.stream()
.filter(c -> map.get(c) == maxCount)
.collect(toSet());
}
public static Set<Character> byBucket(String input) {
int[] buckets = new int[128];
int maxCount = 0;
for (char c : input.toCharArray()) {
buckets[c]++;
maxCount = Math.max(buckets[c], maxCount);
}
int finalMaxCount = maxCount;
return IntStream.range(0, 128)
.filter(c -> buckets[c] == finalMaxCount)
.mapToObj(i -> (char) i)
.collect(Collectors.toSet());
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.charfreq;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableSet;
class CharacterWithHighestFrequencyUnitTest {
private static final String INPUT1 = "aaaaaaaaaa(10) bbbbbbb ccccc dddd eee ff";
private static final Set<Character> EXPECTED1 = Collections.singleton('a');
private static final String INPUT2 = "YYYYYYY(7) bbbbb -------(7) dddd eee kkkkkkk(7) ff";
private static final Set<Character> EXPECTED2 = ImmutableSet.of('Y', '-', 'k');
@Test
void whenGettingSingleCharWithHighestFrequencyByStream_shouldSuccess() {
char result1 = CharacterWithHighestFrequency.byStream(INPUT1);
assertEquals('a', result1);
}
@Test
void whenGettingCharWithHighestFrequencyByMap_shouldSuccess() {
Set<Character> result1 = CharacterWithHighestFrequency.byMap(INPUT1);
assertEquals(EXPECTED1, result1);
Set<Character> result2 = CharacterWithHighestFrequency.byMap(INPUT2);
assertEquals(EXPECTED2, result2);
}
@Test
void whenGettingCharWithHighestFrequencyByBucket_shouldSuccess() {
Set<Character> result1 = CharacterWithHighestFrequency.byBucket(INPUT1);
assertEquals(EXPECTED1, result1);
Set<Character> result2 = CharacterWithHighestFrequency.byBucket(INPUT2);
assertEquals(EXPECTED2, result2);
}
}

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

@ -13,3 +13,4 @@ This module contains articles about strings in Java.
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)
- [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency)

View File

@ -5,3 +5,4 @@
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)

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,5 +0,0 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)

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,180 +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.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</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 -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<spring.core.version>4.3.20.RELEASE</spring.core.version>
</properties>
</project>

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