Merge branch 'eugenp:master' into master
This commit is contained in:
+65
@@ -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;
|
||||
}
|
||||
}
|
||||
+30
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+126
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- TBD
|
||||
@@ -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>
|
||||
+33
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.scopedvalues.data;
|
||||
|
||||
public record Data(String id, String title, String description) {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.scopedvalues.data;
|
||||
|
||||
public record User(String id, String name, String password, boolean isAdmin) {}
|
||||
+37
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
public class ExternalService {
|
||||
|
||||
public String getData() {
|
||||
return "External data";
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -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("");
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -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("");
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -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("");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user