Merge remote-tracking branch 'upstream/master' into feature/BAEL-7062-GetIndex
This commit is contained in:
commit
ce61cf5e7d
@ -0,0 +1,102 @@
|
|||||||
|
package com.baeldung.algorithms.rotatearray;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* To speed up the rotation, we narrow k rotations to the remainder of k divided by the array length, or k module the array length.
|
||||||
|
* Therefore, a large rotation number will be translated into the relative smallest rotation.
|
||||||
|
* All solutions replace the original array, although they might use an extra array to compute the rotation.
|
||||||
|
*/
|
||||||
|
public class RotateArray {
|
||||||
|
|
||||||
|
private RotateArray() {
|
||||||
|
throw new IllegalStateException("Rotate array algorithm utility methods class");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void bruteForce(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k %= arr.length;
|
||||||
|
int temp;
|
||||||
|
int previous;
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
previous = arr[arr.length - 1];
|
||||||
|
for (int j = 0; j < arr.length; j++) {
|
||||||
|
temp = arr[j];
|
||||||
|
arr[j] = previous;
|
||||||
|
previous = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void withExtraArray(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
int[] extraArray = new int[arr.length];
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
extraArray[(i + k) % arr.length] = arr[i];
|
||||||
|
}
|
||||||
|
System.arraycopy(extraArray, 0, arr, 0, arr.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void cyclicReplacement(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k = k % arr.length;
|
||||||
|
int count = 0;
|
||||||
|
for (int start = 0; count < arr.length; start++) {
|
||||||
|
int current = start;
|
||||||
|
int prev = arr[start];
|
||||||
|
do {
|
||||||
|
int next = (current + k) % arr.length;
|
||||||
|
int temp = arr[next];
|
||||||
|
arr[next] = prev;
|
||||||
|
prev = temp;
|
||||||
|
current = next;
|
||||||
|
count++;
|
||||||
|
} while (start != current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void reverse(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k %= arr.length;
|
||||||
|
reverse(arr, 0, arr.length - 1);
|
||||||
|
reverse(arr, 0, k - 1);
|
||||||
|
reverse(arr, k, arr.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reverse(int[] nums, int start, int end) {
|
||||||
|
while (start < end) {
|
||||||
|
int temp = nums[start];
|
||||||
|
nums[start] = nums[end];
|
||||||
|
nums[end] = temp;
|
||||||
|
start++;
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void checkInvalidInput(int[] arr, int rotation) {
|
||||||
|
if (rotation < 1 || arr == null)
|
||||||
|
throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,124 @@
|
|||||||
|
package com.baeldung.algorithms.rotatearray;
|
||||||
|
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.bruteForce;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.cyclicReplacement;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.reverse;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.withExtraArray;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class RotateArrayUnitTest {
|
||||||
|
|
||||||
|
private final int[] arr = { 1, 2, 3, 4, 5, 6 };
|
||||||
|
private final int rotationLtArrayLength = 1;
|
||||||
|
private final int rotationGtArrayLength = arr.length + 2;
|
||||||
|
private final int[] ltArrayLengthRotation = { 6, 1, 2, 3, 4, 5 };
|
||||||
|
private final int[] gtArrayLengthRotation = { 5, 6, 1, 2, 3, 4 };
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenNoRotationOrEmptyArray_thenThrowIllegalArgumentException() {
|
||||||
|
final int noRotation = 0;
|
||||||
|
final int someRotation = arr.length - 1;
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bruteForce(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> withExtraArray(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> reverse(arr, noRotation));
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bruteForce(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> withExtraArray(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> reverse(null, someRotation));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
bruteForce(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
bruteForce(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] expected = arr.clone();
|
||||||
|
|
||||||
|
bruteForce(arr, arr.length);
|
||||||
|
assertArrayEquals(expected, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
withExtraArray(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
withExtraArray(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayWithRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
withExtraArray(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
cyclicReplacement(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
cyclicReplacement(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
cyclicReplacement(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
reverse(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
reverse(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationEqArrayLength_thenDoNothing() {
|
||||||
|
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
reverse(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
}
|
2
aws-modules/aws-dynamodb/.gitignore
vendored
Normal file
2
aws-modules/aws-dynamodb/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/target/
|
||||||
|
.idea/
|
7
aws-modules/aws-dynamodb/README.md
Normal file
7
aws-modules/aws-dynamodb/README.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
## AWS DYNAMODB
|
||||||
|
|
||||||
|
This module contains articles about AWS DynamoDB
|
||||||
|
|
||||||
|
### Relevant articles
|
||||||
|
- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests)
|
||||||
|
|
87
aws-modules/aws-dynamodb/pom.xml
Normal file
87
aws-modules/aws-dynamodb/pom.xml
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
<?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>aws-dynamodb</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>aws-dynamodb</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>aws-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk</artifactId>
|
||||||
|
<version>${aws-java-sdk.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>DynamoDBLocal</artifactId>
|
||||||
|
<version>${dynamodblocal.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>${commons-io.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
<artifactId>gson</artifactId>
|
||||||
|
<version>${gson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<version>${maven-shade-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<version>${maven-plugins-version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>copy</id>
|
||||||
|
<phase>compile</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-dependencies</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includeScope></includeScope>
|
||||||
|
<includeTypes>so,dll,dylib</includeTypes>
|
||||||
|
<outputDirectory>native-libs</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<gson.version>2.8.0</gson.version>
|
||||||
|
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
||||||
|
<maven-plugins-version>3.1.1</maven-plugins-version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
13
aws-modules/aws-dynamodb/src/main/resources/logback.xml
Normal file
13
aws-modules/aws-dynamodb/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -16,31 +16,9 @@
|
|||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.amazonaws</groupId>
|
<groupId>software.amazon.awssdk</groupId>
|
||||||
<artifactId>aws-java-sdk</artifactId>
|
<artifactId>aws-sdk-java</artifactId>
|
||||||
<version>${aws-java-sdk.version}</version>
|
<version>${aws-java-sdk-v2.version}</version>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-core</artifactId>
|
|
||||||
<version>${aws-lambda-java-core.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-events</artifactId>
|
|
||||||
<version>${aws-lambda-java-events.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
@ -52,12 +30,6 @@
|
|||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>${gson.version}</version>
|
<version>${gson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>DynamoDBLocal</artifactId>
|
|
||||||
<version>${dynamodblocal.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -101,8 +73,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
|
||||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
|
||||||
<gson.version>2.8.0</gson.version>
|
<gson.version>2.8.0</gson.version>
|
||||||
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
||||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||||
|
@ -2,136 +2,148 @@ package com.baeldung.ec2;
|
|||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import software.amazon.awssdk.regions.Region;
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||||
import com.amazonaws.regions.Regions;
|
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
||||||
import com.amazonaws.services.ec2.AmazonEC2;
|
import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
|
||||||
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
|
import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
|
||||||
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
|
||||||
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
|
import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsRequest;
|
||||||
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
|
||||||
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
|
import software.amazon.awssdk.services.ec2.model.IpPermission;
|
||||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
|
import software.amazon.awssdk.services.ec2.model.IpRange;
|
||||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
|
import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.IpPermission;
|
import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.IpRange;
|
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.RunInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StartInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.StartInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.StopInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
|
|
||||||
|
|
||||||
public class EC2Application {
|
public class EC2Application {
|
||||||
|
|
||||||
private static final AWSCredentials credentials;
|
|
||||||
|
|
||||||
static {
|
|
||||||
// put your accesskey and secretkey here
|
|
||||||
credentials = new BasicAWSCredentials(
|
|
||||||
"<AWS accesskey>",
|
|
||||||
"<AWS secretkey>"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
// Set up the client
|
// Set up the client
|
||||||
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
|
Ec2Client ec2Client = Ec2Client.builder()
|
||||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
.credentialsProvider(ProfileCredentialsProvider.create("default"))
|
||||||
.withRegion(Regions.US_EAST_1)
|
.region(Region.US_EAST_1)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Create a security group
|
// Create a security group
|
||||||
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
|
CreateSecurityGroupRequest createSecurityGroupRequest = CreateSecurityGroupRequest.builder()
|
||||||
.withDescription("Baeldung Security Group");
|
.groupName("BaeldungSecurityGroup")
|
||||||
|
.description("Baeldung Security Group")
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
||||||
|
|
||||||
// Allow HTTP and SSH traffic
|
// Allow HTTP and SSH traffic
|
||||||
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
|
IpRange ipRange1 = IpRange.builder()
|
||||||
|
.cidrIp("0.0.0.0/0")
|
||||||
|
.build();
|
||||||
|
|
||||||
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
IpPermission ipPermission1 = IpPermission.builder()
|
||||||
.withIpProtocol("tcp")
|
.ipRanges(Arrays.asList(ipRange1))
|
||||||
.withFromPort(80)
|
.ipProtocol("tcp")
|
||||||
.withToPort(80);
|
.fromPort(80)
|
||||||
|
.toPort(80)
|
||||||
|
.build();
|
||||||
|
|
||||||
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
IpPermission ipPermission2 = IpPermission.builder()
|
||||||
.withIpProtocol("tcp")
|
.ipRanges(Arrays.asList(ipRange1))
|
||||||
.withFromPort(22)
|
.ipProtocol("tcp")
|
||||||
.withToPort(22);
|
.fromPort(22)
|
||||||
|
.toPort(22)
|
||||||
|
.build();
|
||||||
|
|
||||||
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
|
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = AuthorizeSecurityGroupIngressRequest
|
||||||
.withGroupName("BaeldungSecurityGroup")
|
.builder()
|
||||||
.withIpPermissions(ipPermission1, ipPermission2);
|
.groupName("BaeldungSecurityGroup")
|
||||||
|
.ipPermissions(ipPermission1, ipPermission2)
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
||||||
|
|
||||||
// Create KeyPair
|
// Create KeyPair
|
||||||
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
|
CreateKeyPairRequest createKeyPairRequest = CreateKeyPairRequest.builder()
|
||||||
.withKeyName("baeldung-key-pair");
|
.keyName("baeldung-key-pair")
|
||||||
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
|
.build();
|
||||||
String privateKey = createKeyPairResult
|
|
||||||
.getKeyPair()
|
CreateKeyPairResponse createKeyPairResponse = ec2Client.createKeyPair(createKeyPairRequest);
|
||||||
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
|
String privateKey = createKeyPairResponse.keyMaterial();
|
||||||
|
// make sure you keep it, the private key, Amazon doesn't store the private key
|
||||||
|
|
||||||
// See what key-pairs you've got
|
// See what key-pairs you've got
|
||||||
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
|
DescribeKeyPairsRequest describeKeyPairsRequest = DescribeKeyPairsRequest.builder()
|
||||||
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
.build();
|
||||||
|
DescribeKeyPairsResponse describeKeyPairsResponse = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
||||||
|
|
||||||
// Launch an Amazon Instance
|
// Launch an Amazon Instance
|
||||||
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
|
RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()
|
||||||
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
.imageId("ami-97785bed")
|
||||||
.withMinCount(1)
|
.instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
||||||
.withMaxCount(1)
|
.minCount(1)
|
||||||
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
.maxCount(1)
|
||||||
.withSecurityGroups("BaeldungSecurityGroup");
|
.keyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
||||||
|
.securityGroups("BaeldungSecurityGroup")
|
||||||
|
.build();
|
||||||
|
|
||||||
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
|
RunInstancesResponse runInstancesResponse = ec2Client.runInstances(runInstancesRequest);
|
||||||
|
String yourInstanceId = runInstancesResponse.instances().get(0).instanceId();
|
||||||
|
|
||||||
// Start an Instance
|
// Start an Instance
|
||||||
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
|
StartInstancesRequest startInstancesRequest = StartInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
StartInstancesResponse startInstancesResponse = ec2Client.startInstances(startInstancesRequest);
|
||||||
|
|
||||||
ec2Client.startInstances(startInstancesRequest);
|
|
||||||
|
|
||||||
// Monitor Instances
|
// Monitor Instances
|
||||||
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
|
MonitorInstancesRequest monitorInstancesRequest = MonitorInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
|
||||||
ec2Client.monitorInstances(monitorInstancesRequest);
|
ec2Client.monitorInstances(monitorInstancesRequest);
|
||||||
|
|
||||||
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
|
UnmonitorInstancesRequest unmonitorInstancesRequest = UnmonitorInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
||||||
|
|
||||||
// Reboot an Instance
|
// Reboot an Instance
|
||||||
|
RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder()
|
||||||
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
|
.instanceIds(yourInstanceId)
|
||||||
.withInstanceIds(yourInstanceId);
|
.build();
|
||||||
|
|
||||||
ec2Client.rebootInstances(rebootInstancesRequest);
|
ec2Client.rebootInstances(rebootInstancesRequest);
|
||||||
|
|
||||||
// Stop an Instance
|
// Stop an Instance
|
||||||
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
|
StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
|
||||||
ec2Client.stopInstances(stopInstancesRequest)
|
ec2Client.stopInstances(stopInstancesRequest)
|
||||||
.getStoppingInstances()
|
.stoppingInstances()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getPreviousState()
|
.previousState()
|
||||||
.getName();
|
.name();
|
||||||
|
|
||||||
// Describe an Instance
|
// Describe an Instance
|
||||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
|
DescribeInstancesRequest describeInstancesRequest = DescribeInstancesRequest.builder().build();
|
||||||
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
|
DescribeInstancesResponse response = ec2Client.describeInstances(describeInstancesRequest);
|
||||||
System.out.println(response.getReservations()
|
System.out.println(response.reservations()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getInstances()
|
.instances()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getKernelId());
|
.kernelId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package com.baeldung.rds;
|
package com.baeldung.rds;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
|
||||||
import com.amazonaws.regions.Regions;
|
|
||||||
import com.amazonaws.services.rds.AmazonRDS;
|
|
||||||
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
|
|
||||||
import com.amazonaws.services.rds.model.*;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.sql.*;
|
import java.sql.*;
|
||||||
@ -16,12 +8,22 @@ import java.util.Properties;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
|
import software.amazon.awssdk.regions.Region;
|
||||||
|
import software.amazon.awssdk.services.rds.RdsClient;
|
||||||
|
import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest;
|
||||||
|
import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DBInstance;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.Endpoint;
|
||||||
|
|
||||||
public class AWSRDSService {
|
public class AWSRDSService {
|
||||||
|
|
||||||
|
|
||||||
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
||||||
private AWSCredentialsProvider credentials;
|
private RdsClient rdsClient;
|
||||||
private AmazonRDS amazonRDS;
|
|
||||||
private String db_username;
|
private String db_username;
|
||||||
private String db_password;
|
private String db_password;
|
||||||
private String db_database;
|
private String db_database;
|
||||||
@ -34,22 +36,17 @@ public class AWSRDSService {
|
|||||||
* **/
|
* **/
|
||||||
public AWSRDSService() throws IOException {
|
public AWSRDSService() throws IOException {
|
||||||
//Init RDS client with credentials and region.
|
//Init RDS client with credentials and region.
|
||||||
credentials = new
|
|
||||||
AWSStaticCredentialsProvider(new
|
|
||||||
BasicAWSCredentials("<ACCESS_KEY>",
|
|
||||||
"<SECRET_KEY>"));
|
|
||||||
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
|
|
||||||
.withRegion(Regions.AP_SOUTHEAST_2).build();
|
|
||||||
Properties prop = new Properties();
|
Properties prop = new Properties();
|
||||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||||
prop.load(input);
|
prop.load(input);
|
||||||
db_username = prop.getProperty("db_username");
|
db_username = prop.getProperty("db_username");
|
||||||
db_password = prop.getProperty("db_password");
|
db_password = prop.getProperty("db_password");
|
||||||
db_database = prop.getProperty("db_database");
|
db_database = prop.getProperty("db_database");
|
||||||
}
|
|
||||||
|
|
||||||
public AWSRDSService(AmazonRDS amazonRDS){
|
rdsClient = RdsClient.builder()
|
||||||
this.amazonRDS = amazonRDS;
|
.region(Region.AP_SOUTHEAST_2)
|
||||||
|
.credentialsProvider(ProfileCredentialsProvider.create("default"))
|
||||||
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -60,29 +57,29 @@ public class AWSRDSService {
|
|||||||
public String launchInstance() {
|
public String launchInstance() {
|
||||||
|
|
||||||
String identifier = "";
|
String identifier = "";
|
||||||
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
|
CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
|
||||||
// RDS instance name
|
.dbInstanceIdentifier("Sydney")
|
||||||
request.setDBInstanceIdentifier("Sydney");
|
.engine("postgres")
|
||||||
request.setEngine("postgres");
|
.multiAZ(false)
|
||||||
request.setMultiAZ(false);
|
.masterUsername(db_username)
|
||||||
request.setMasterUsername(db_username);
|
.masterUserPassword(db_password)
|
||||||
request.setMasterUserPassword(db_password);
|
.dbName(db_database)
|
||||||
request.setDBName(db_database);
|
.storageType("gp2")
|
||||||
request.setStorageType("gp2");
|
.allocatedStorage(10)
|
||||||
request.setAllocatedStorage(10);
|
.build();
|
||||||
|
|
||||||
DBInstance instance = amazonRDS.createDBInstance(request);
|
CreateDbInstanceResponse createDbInstanceResponse = rdsClient.createDBInstance(instanceRequest);
|
||||||
|
|
||||||
// Information about the new RDS instance
|
// Information about the new RDS instance
|
||||||
identifier = instance.getDBInstanceIdentifier();
|
identifier = createDbInstanceResponse.dbInstance().dbInstanceIdentifier();
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = createDbInstanceResponse.dbInstance().dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = createDbInstanceResponse.dbInstance().endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
logger.info(identifier + "\t" + status);
|
logger.info(identifier + "\t" + status);
|
||||||
logger.info(endpoint_url);
|
logger.info(endpointUrl);
|
||||||
|
|
||||||
return identifier;
|
return identifier;
|
||||||
|
|
||||||
@ -90,44 +87,44 @@ public class AWSRDSService {
|
|||||||
|
|
||||||
// Describe DB instances
|
// Describe DB instances
|
||||||
public void listInstances() {
|
public void listInstances() {
|
||||||
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
|
DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
|
||||||
List<DBInstance> instances = result.getDBInstances();
|
List<DBInstance> instances = response.dbInstances();
|
||||||
for (DBInstance instance : instances) {
|
for (DBInstance instance : instances) {
|
||||||
// Information about each RDS instance
|
// Information about each RDS instance
|
||||||
String identifier = instance.getDBInstanceIdentifier();
|
String identifier = instance.dbInstanceIdentifier();
|
||||||
String engine = instance.getEngine();
|
String engine = instance.engine();
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = instance.dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = instance.endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
logger.info(identifier + "\t" + engine + "\t" + status);
|
logger.info(identifier + "\t" + engine + "\t" + status);
|
||||||
logger.info("\t" + endpoint_url);
|
logger.info("\t" + endpointUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete RDS instance
|
//Delete RDS instance
|
||||||
public void terminateInstance(String identifier) {
|
public void terminateInstance(String identifier) {
|
||||||
|
|
||||||
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
|
DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
|
||||||
request.setDBInstanceIdentifier(identifier);
|
.dbInstanceIdentifier(identifier)
|
||||||
request.setSkipFinalSnapshot(true);
|
.skipFinalSnapshot(true)
|
||||||
|
.build();
|
||||||
|
|
||||||
// Delete the RDS instance
|
// Delete the RDS instance
|
||||||
DBInstance instance = amazonRDS.deleteDBInstance(request);
|
DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(request);
|
||||||
|
|
||||||
// Information about the RDS instance being deleted
|
// Information about the RDS instance being deleted
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = response.dbInstance().dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = response.dbInstance().endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(identifier + "\t" + status);
|
logger.info(identifier + "\t" + status);
|
||||||
logger.info(endpoint_url);
|
logger.info(endpointUrl);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,140 +5,190 @@ import java.util.HashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import software.amazon.awssdk.regions.Region;
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||||
import com.amazonaws.regions.Regions;
|
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
|
||||||
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
|
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
|
||||||
import com.amazonaws.services.sqs.model.CreateQueueRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
|
||||||
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
|
||||||
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
|
||||||
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
|
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
|
||||||
import com.amazonaws.services.sqs.model.MessageAttributeValue;
|
import software.amazon.awssdk.services.sqs.model.Message;
|
||||||
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
|
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
|
||||||
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
|
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
|
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
|
||||||
import com.amazonaws.services.sqs.model.Message;
|
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
|
||||||
import com.amazonaws.services.sqs.AmazonSQS;
|
import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
|
||||||
|
|
||||||
public class SQSApplication {
|
public class SQSApplication {
|
||||||
|
|
||||||
private static final AWSCredentials credentials;
|
private static final String STANDARD_QUEUE_NAME = "baeldung-queue";
|
||||||
|
private static final String FIFO_QUEUE_NAME = "baeldung-queue.fifo";
|
||||||
static {
|
private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue";
|
||||||
// put your accesskey and secretkey here
|
|
||||||
credentials = new BasicAWSCredentials(
|
|
||||||
"<AWS accesskey>",
|
|
||||||
"<AWS secretkey>"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
// Set up the client
|
// Set up the client
|
||||||
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
|
SqsClient sqsClient = SqsClient.builder()
|
||||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
.region(Region.US_EAST_1)
|
||||||
.withRegion(Regions.US_EAST_1)
|
.credentialsProvider(ProfileCredentialsProvider.create())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Create a standard queue
|
// Create a standard queue
|
||||||
|
CreateQueueRequest createStandardQueueRequest = CreateQueueRequest.builder()
|
||||||
|
.queueName(STANDARD_QUEUE_NAME)
|
||||||
|
.build();
|
||||||
|
|
||||||
CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue");
|
sqsClient.createQueue(createStandardQueueRequest);
|
||||||
String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
|
|
||||||
.getQueueUrl();
|
System.out.println("\nGet queue url");
|
||||||
|
|
||||||
|
GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
|
||||||
|
.queueName(STANDARD_QUEUE_NAME)
|
||||||
|
.build());
|
||||||
|
String standardQueueUrl = getQueueUrlResponse.queueUrl();
|
||||||
|
|
||||||
System.out.println(standardQueueUrl);
|
System.out.println(standardQueueUrl);
|
||||||
|
|
||||||
// Create a fifo queue
|
// Create a fifo queue
|
||||||
|
Map<QueueAttributeName, String> queueAttributes = new HashMap<>();
|
||||||
|
queueAttributes.put(QueueAttributeName.FIFO_QUEUE, "true");
|
||||||
|
queueAttributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, "true");
|
||||||
|
|
||||||
Map<String, String> queueAttributes = new HashMap<String, String>();
|
CreateQueueRequest createFifoQueueRequest = CreateQueueRequest.builder()
|
||||||
queueAttributes.put("FifoQueue", "true");
|
.queueName(FIFO_QUEUE_NAME)
|
||||||
queueAttributes.put("ContentBasedDeduplication", "true");
|
.attributes(queueAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes);
|
sqsClient.createQueue(createFifoQueueRequest);
|
||||||
String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
|
|
||||||
.getQueueUrl();
|
GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
|
||||||
|
.queueName(FIFO_QUEUE_NAME)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl();
|
||||||
|
|
||||||
System.out.println(fifoQueueUrl);
|
System.out.println(fifoQueueUrl);
|
||||||
|
|
||||||
// Set up a dead letter queue
|
// Set up a dead letter queue
|
||||||
|
CreateQueueRequest createDeadLetterQueueRequest = CreateQueueRequest.builder()
|
||||||
|
.queueName(DEAD_LETTER_QUEUE_NAME)
|
||||||
|
.build();
|
||||||
|
|
||||||
String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue")
|
String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest)
|
||||||
.getQueueUrl();
|
.queueUrl();
|
||||||
|
|
||||||
GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn"));
|
GetQueueAttributesRequest getQueueAttributesRequest = GetQueueAttributesRequest.builder()
|
||||||
|
.queueUrl(deadLetterQueueUrl)
|
||||||
|
.attributeNames(QueueAttributeName.QUEUE_ARN)
|
||||||
|
.build();
|
||||||
|
|
||||||
String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes()
|
GetQueueAttributesResponse deadLetterQueueAttributes = sqsClient.getQueueAttributes(getQueueAttributesRequest);
|
||||||
|
|
||||||
|
String deadLetterQueueARN = deadLetterQueueAttributes.attributes()
|
||||||
.get("QueueArn");
|
.get("QueueArn");
|
||||||
|
|
||||||
SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl)
|
Map<QueueAttributeName, String> attributes = new HashMap<>();
|
||||||
.addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
|
attributes.put(QueueAttributeName.REDRIVE_POLICY, "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
|
||||||
|
|
||||||
sqs.setQueueAttributes(queueAttributesRequest);
|
SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder()
|
||||||
|
.queueUrl(standardQueueUrl)
|
||||||
|
.attributes(attributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
sqsClient.setQueueAttributes(queueAttributesRequest);
|
||||||
|
|
||||||
// Send a message to a standard queue
|
// Send a message to a standard queue
|
||||||
|
|
||||||
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
|
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
|
||||||
|
MessageAttributeValue messageAttributeValue = MessageAttributeValue.builder()
|
||||||
|
.stringValue("This is an attribute")
|
||||||
|
.dataType("String")
|
||||||
|
.build();
|
||||||
|
|
||||||
messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute")
|
messageAttributes.put("AttributeOne", messageAttributeValue);
|
||||||
.withDataType("String"));
|
|
||||||
|
|
||||||
SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl)
|
SendMessageRequest sendMessageStandardQueue = SendMessageRequest.builder()
|
||||||
.withMessageBody("A simple message.")
|
.queueUrl(standardQueueUrl)
|
||||||
.withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
|
.messageBody("A simple message.")
|
||||||
.withMessageAttributes(messageAttributes);
|
.delaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
|
||||||
|
.messageAttributes(messageAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.sendMessage(sendMessageStandardQueue);
|
sqsClient.sendMessage(sendMessageStandardQueue);
|
||||||
|
|
||||||
// Send a message to a fifo queue
|
// Send a message to a fifo queue
|
||||||
|
|
||||||
SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl)
|
SendMessageRequest sendMessageFifoQueue = SendMessageRequest.builder()
|
||||||
.withMessageBody("FIFO Queue")
|
.queueUrl(fifoQueueUrl)
|
||||||
.withMessageGroupId("baeldung-group-1")
|
.messageBody("FIFO Queue")
|
||||||
.withMessageAttributes(messageAttributes);
|
.messageGroupId("baeldung-group-1")
|
||||||
|
.messageAttributes(messageAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.sendMessage(sendMessageFifoQueue);
|
sqsClient.sendMessage(sendMessageFifoQueue);
|
||||||
|
|
||||||
// Send multiple messages
|
// Send multiple messages
|
||||||
|
|
||||||
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
|
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
|
||||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1")
|
SendMessageBatchRequestEntry messageBatchRequestEntry1 = SendMessageBatchRequestEntry.builder()
|
||||||
.withMessageBody("batch-1")
|
.id("id-1")
|
||||||
.withMessageGroupId("baeldung-group-1"));
|
.messageBody("batch-1")
|
||||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2")
|
.messageGroupId("baeldung-group-1")
|
||||||
.withMessageBody("batch-2")
|
.build();
|
||||||
.withMessageGroupId("baeldung-group-1"));
|
|
||||||
|
|
||||||
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries);
|
SendMessageBatchRequestEntry messageBatchRequestEntry2 = SendMessageBatchRequestEntry.builder()
|
||||||
sqs.sendMessageBatch(sendMessageBatchRequest);
|
.id("id-2")
|
||||||
|
.messageBody("batch-2")
|
||||||
|
.messageGroupId("baeldung-group-1")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
messageEntries.add(messageBatchRequestEntry1);
|
||||||
|
messageEntries.add(messageBatchRequestEntry2);
|
||||||
|
|
||||||
|
SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
|
||||||
|
.queueUrl(fifoQueueUrl)
|
||||||
|
.entries(messageEntries)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
sqsClient.sendMessageBatch(sendMessageBatchRequest);
|
||||||
|
|
||||||
// Read a message from a queue
|
// Read a message from a queue
|
||||||
|
|
||||||
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling;
|
ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
|
||||||
.withMaxNumberOfMessages(1); // Max is 10
|
.waitTimeSeconds(10)
|
||||||
|
.maxNumberOfMessages(10)
|
||||||
|
.build();
|
||||||
|
|
||||||
List<Message> sqsMessages = sqs.receiveMessage(receiveMessageRequest)
|
List<Message> sqsMessages = sqsClient.receiveMessage(receiveMessageRequest)
|
||||||
.getMessages();
|
.messages();
|
||||||
|
|
||||||
sqsMessages.get(0)
|
sqsMessages.get(0)
|
||||||
.getAttributes();
|
.attributes();
|
||||||
sqsMessages.get(0)
|
sqsMessages.get(0)
|
||||||
.getBody();
|
.body();
|
||||||
|
|
||||||
// Delete a message from a queue
|
// Delete a message from a queue
|
||||||
|
DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
|
||||||
|
.queueUrl(fifoQueueUrl)
|
||||||
|
.receiptHandle(sqsMessages.get(0)
|
||||||
|
.receiptHandle())
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl)
|
sqsClient.deleteMessage(deleteMessageRequest);
|
||||||
.withReceiptHandle(sqsMessages.get(0)
|
|
||||||
.getReceiptHandle()));
|
|
||||||
|
|
||||||
// Monitoring
|
// Monitoring
|
||||||
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All");
|
GetQueueAttributesRequest getQueueAttributesRequestForMonitoring = GetQueueAttributesRequest.builder()
|
||||||
GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest);
|
.queueUrl(standardQueueUrl)
|
||||||
System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes()
|
.build();
|
||||||
|
|
||||||
|
GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring);
|
||||||
|
System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes()
|
||||||
.get("ApproximateNumberOfMessages")));
|
.get("ApproximateNumberOfMessages")));
|
||||||
System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes()
|
System.out.println(String.format("The number of messages in flight: %s", attributesResponse.attributes()
|
||||||
.get("ApproximateNumberOfMessagesNotVisible")));
|
.get("ApproximateNumberOfMessagesNotVisible")));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,14 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>aws-modules</artifactId>
|
<artifactId>aws-modules</artifactId>
|
||||||
<name>aws-modules</name>
|
<name>aws-modules</name>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||||
|
<version>1.12.523</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
@ -15,6 +23,7 @@
|
|||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>aws-app-sync</module>
|
<module>aws-app-sync</module>
|
||||||
|
<module>aws-dynamodb</module>
|
||||||
<module>aws-lambda-modules</module>
|
<module>aws-lambda-modules</module>
|
||||||
<module>aws-miscellaneous</module>
|
<module>aws-miscellaneous</module>
|
||||||
<module>aws-reactive</module>
|
<module>aws-reactive</module>
|
||||||
@ -24,6 +33,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
||||||
|
<aws-java-sdk-v2.version>2.20.147</aws-java-sdk-v2.version>
|
||||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -30,6 +30,11 @@ public final class Point {
|
|||||||
return new Point(x, y, z);
|
return new Point(x, y, z);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
if (other == null || getClass() != other.getClass())
|
if (other == null || getClass() != other.getClass())
|
||||||
|
@ -1,14 +1,17 @@
|
|||||||
package com.baeldung.value_based_class;
|
package com.baeldung.value_based_class;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ValueBasedClassUnitTest {
|
public class ValueBasedClassUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
||||||
int primitive_a = 125;
|
List<Integer> list = new ArrayList<>();
|
||||||
Integer obj_a = 125; // this is autoboxed
|
list.add(1); // this is autoboxed
|
||||||
Assert.assertSame(primitive_a, obj_a);
|
Assert.assertEquals(list.get(0), Integer.valueOf(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
0
core-java-modules/core-java-18/README.md
Normal file
0
core-java-modules/core-java-18/README.md
Normal file
55
core-java-modules/core-java-18/pom.xml
Normal file
55
core-java-modules/core-java-18/pom.xml
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
<?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-18</artifactId>
|
||||||
|
<name>core-java-18</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<release>${maven.compiler.release}</release>
|
||||||
|
<compilerArgs>--enable-preview</compilerArgs>
|
||||||
|
<source>${maven.compiler.source.version}</source>
|
||||||
|
<target>${maven.compiler.target.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${surefire.plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<forkCount>1</forkCount>
|
||||||
|
</configuration>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.maven.surefire</groupId>
|
||||||
|
<artifactId>surefire-api</artifactId>
|
||||||
|
<version>${surefire.plugin.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>18</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>18</maven.compiler.target.version>
|
||||||
|
<maven.compiler.release>18</maven.compiler.release>
|
||||||
|
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class FinalizationExamples {
|
||||||
|
FileInputStream fis = null;
|
||||||
|
|
||||||
|
public void readFileOperationWithFinalization() throws IOException {
|
||||||
|
try {
|
||||||
|
fis = new FileInputStream("input.txt");
|
||||||
|
// perform operation on the file
|
||||||
|
System.out.println(fis.readAllBytes().length);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (fis != null)
|
||||||
|
fis.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void readFileOperationWithTryWith() throws IOException {
|
||||||
|
try (FileInputStream fis = new FileInputStream("input.txt")) {
|
||||||
|
// perform operations
|
||||||
|
System.out.println(fis.readAllBytes().length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.lang.ref.Cleaner;
|
||||||
|
|
||||||
|
public class MyCleanerResourceClass implements AutoCloseable {
|
||||||
|
private static Resource resource;
|
||||||
|
|
||||||
|
private static final Cleaner cleaner = Cleaner.create();
|
||||||
|
private final Cleaner.Cleanable cleanable;
|
||||||
|
|
||||||
|
public MyCleanerResourceClass() {
|
||||||
|
resource = new Resource();
|
||||||
|
this.cleanable = cleaner.register(this, new CleaningState());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void useResource() {
|
||||||
|
// using the resource here
|
||||||
|
resource.use();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
// perform actions to close all underlying resources
|
||||||
|
this.cleanable.clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
static class CleaningState implements Runnable {
|
||||||
|
CleaningState() {
|
||||||
|
// constructor
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// some cleanup action
|
||||||
|
System.out.println("Cleanup done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Resource {
|
||||||
|
void use() {
|
||||||
|
System.out.println("Using the resource");
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
System.out.println("Cleanup done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class MyCloseableResourceClass implements AutoCloseable {
|
||||||
|
|
||||||
|
private final FileInputStream fis;
|
||||||
|
|
||||||
|
public MyCloseableResourceClass() throws FileNotFoundException {
|
||||||
|
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getByteLength() throws IOException {
|
||||||
|
System.out.println("Some operation");
|
||||||
|
return this.fis.readAllBytes().length;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
System.out.println("Finalized object");
|
||||||
|
this.fis.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class MyFinalizableResourceClass {
|
||||||
|
private FileInputStream fis;
|
||||||
|
|
||||||
|
public MyFinalizableResourceClass() throws FileNotFoundException {
|
||||||
|
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getByteLength() throws IOException {
|
||||||
|
System.out.println("Some operation");
|
||||||
|
return this.fis.readAllBytes().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void finalize() throws Throwable {
|
||||||
|
System.out.println("Finalized object");
|
||||||
|
this.fis.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
This is a test file.
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FinalizationCloseableCleanerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMyFinalizationResource_whenUsingFinalize_thenShouldClean() {
|
||||||
|
assertDoesNotThrow(() -> {
|
||||||
|
MyFinalizableResourceClass mfr = new MyFinalizableResourceClass();
|
||||||
|
mfr.getByteLength();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenMyCleanerResource_whenUsingCleanerAPI_thenShouldClean() {
|
||||||
|
assertDoesNotThrow(() -> {
|
||||||
|
try (MyCleanerResourceClass myCleanerResourceClass = new MyCleanerResourceClass()) {
|
||||||
|
myCleanerResourceClass.useResource();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCloseableResource_whenUsingTryWith_thenShouldClose() throws IOException {
|
||||||
|
int length = 0;
|
||||||
|
try (MyCloseableResourceClass mcr = new MyCloseableResourceClass()) {
|
||||||
|
length = mcr.getByteLength();
|
||||||
|
}
|
||||||
|
Assert.assertEquals(20, length);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.array.conversions;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class CharArrayToIntArrayUtils {
|
||||||
|
|
||||||
|
static int[] usingGetNumericValueMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Character.getNumericValue(chars[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingDigitMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Character.digit(chars[i], 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingStreamApiMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new String(chars).chars()
|
||||||
|
.map(c -> c - 48)
|
||||||
|
.toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingParseIntMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Integer.parseInt(String.valueOf(chars[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingArraysSetAllMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
Arrays.setAll(ints, i -> Character.getNumericValue(chars[i]));
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
package com.baeldung.array.conversions;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class CharArrayToIntArrayUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 2, 3, 4, 5 };
|
||||||
|
char[] chars = { '2', '3', '4', '5' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 1, 2, 3, 6 };
|
||||||
|
char[] chars = { '1', '2', '3', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingStreamApi_shouldGetIntArray() {
|
||||||
|
int[] expected = { 9, 8, 7, 6 };
|
||||||
|
char[] chars = { '9', '8', '7', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 9, 8, 7, 6 };
|
||||||
|
char[] chars = { '9', '8', '7', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 4, 9, 2, 3 };
|
||||||
|
char[] chars = { '4', '9', '2', '3' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,72 @@
|
|||||||
|
package com.baeldung.rmlinebreaks;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
public class RemoveLinebreaksUnitTest {
|
||||||
|
|
||||||
|
private Path file1Path() throws Exception {
|
||||||
|
return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-1.txt").toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path file2Path() throws Exception {
|
||||||
|
return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-2.txt").toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingLineSeparatorFromFile1_thenGetTheExpectedResult() throws Exception {
|
||||||
|
String content = Files.readString(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result = content.replace(System.getProperty("line.separator"), "");
|
||||||
|
assertEquals("A, B, C, D, E, F", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingLineSeparatorFromFile2_thenNotGetTheExpectedResult() throws Exception {
|
||||||
|
String content = Files.readString(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result = content.replace(System.getProperty("line.separator"), "");
|
||||||
|
assertNotEquals("A, B, C, D, E, F", result); // <-- NOT equals assertion!
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingAllLinebreaks_thenGetTheExpectedResult() throws Exception {
|
||||||
|
String content1 = Files.readString(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
// file contains CRLF
|
||||||
|
String content2 = Files.readString(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result1 = content1.replace("\r", "").replace("\n", "");
|
||||||
|
String result2 = content2.replace("\r", "").replace("\n", "");
|
||||||
|
|
||||||
|
assertEquals("A, B, C, D, E, F", result1);
|
||||||
|
assertEquals("A, B, C, D, E, F", result2);
|
||||||
|
|
||||||
|
String resultReplaceAll = content2.replaceAll("[\\n\\r]", "");
|
||||||
|
assertEquals("A, B, C, D, E, F", resultReplaceAll);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingReadAllLinesAndJoin_thenGetExpectedResult() throws Exception {
|
||||||
|
List<String> lines1 = Files.readAllLines(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
// file contains CRLF
|
||||||
|
List<String> lines2 = Files.readAllLines(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result1 = String.join("", lines1);
|
||||||
|
String result2 = String.join("", lines2);
|
||||||
|
|
||||||
|
assertEquals("A, B, C, D, E, F", result1);
|
||||||
|
assertEquals("A, B, C, D, E, F", result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
A,
|
||||||
|
B,
|
||||||
|
C,
|
||||||
|
D,
|
||||||
|
E,
|
||||||
|
F
|
@ -0,0 +1,4 @@
|
|||||||
|
A,
B,
|
||||||
|
C,
|
||||||
|
D,
E,
|
||||||
|
F
|
@ -2,10 +2,15 @@ package com.baeldung.networking.url;
|
|||||||
|
|
||||||
import static java.util.stream.Collectors.toList;
|
import static java.util.stream.Collectors.toList;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.net.MalformedURLException;
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.apache.http.client.utils.URIBuilder;
|
import org.apache.http.client.utils.URIBuilder;
|
||||||
@ -149,4 +154,24 @@ public class UrlUnitTest {
|
|||||||
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
|
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenURI_whenConvertingToURL_thenCorrect() throws IOException, URISyntaxException {
|
||||||
|
String aURIString = "http://courses.baeldung.com";
|
||||||
|
URI uri = new URI(aURIString);
|
||||||
|
URL url = uri.toURL();
|
||||||
|
assertNotNull(url);
|
||||||
|
assertEquals(aURIString, url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenConvertingToURIAndThenURL_thenCorrect() throws IOException, URISyntaxException {
|
||||||
|
String finalPath = "file:/D:/baeldung/java-url";
|
||||||
|
Path path = Paths.get("/baeldung/java-url");
|
||||||
|
URI uri = path.toUri();
|
||||||
|
URL url = uri.toURL();
|
||||||
|
assertNotNull(url);
|
||||||
|
// Adapt the finalPath value to match your own path
|
||||||
|
// assertEquals(finalPath, url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -1,6 +1,8 @@
|
|||||||
package com.baeldung.integerToBinary;
|
package com.baeldung.integerToBinary;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class IntegerToBinaryUnitTest {
|
public class IntegerToBinaryUnitTest {
|
||||||
@ -24,4 +26,18 @@ public class IntegerToBinaryUnitTest {
|
|||||||
String binaryString = Integer.toString(n, 2);
|
String binaryString = Integer.toString(n, 2);
|
||||||
assertEquals("111", binaryString);
|
assertEquals("111", binaryString);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnInteger_whenFormatAndReplaceCalled_thenZeroPaddedBinaryString() {
|
||||||
|
int n = 7;
|
||||||
|
String binaryString = String.format("%8s", Integer.toBinaryString(n)).replace(" ", "0");
|
||||||
|
assertEquals("00000111", binaryString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnInteger_whenUsingApacheStringUtils_thenZeroPaddedBinaryString() {
|
||||||
|
int n = 7;
|
||||||
|
String binaryString = StringUtils.leftPad(Integer.toBinaryString(n), 8, "0");
|
||||||
|
assertEquals("00000111", binaryString);
|
||||||
|
}
|
||||||
}
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class BigDecimalConversionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenConvertingDoubleToBigDecimal_thenConversionIsCorrect() {
|
||||||
|
double doubleValue = 123.456;
|
||||||
|
BigDecimal bigDecimalValue = BigDecimal.valueOf(doubleValue);
|
||||||
|
BigDecimal expected = new BigDecimal("123.456").setScale(3, RoundingMode.HALF_UP);
|
||||||
|
assertEquals(expected, bigDecimalValue.setScale(3, RoundingMode.HALF_UP));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDecimalPlacesGreaterThan15_whenConvertingBigDecimalToDouble_thenPrecisionIsLost() {
|
||||||
|
BigDecimal bigDecimalValue = new BigDecimal("789.1234567890123456");
|
||||||
|
double doubleValue = bigDecimalValue.doubleValue();
|
||||||
|
BigDecimal convertedBackToBigDecimal = BigDecimal.valueOf(doubleValue);
|
||||||
|
assertNotEquals(bigDecimalValue, convertedBackToBigDecimal);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class BigDecimalUnitTest {
|
||||||
|
|
||||||
|
private BigDecimal bigDecimal1 = new BigDecimal("124567890.0987654321");
|
||||||
|
private BigDecimal bigDecimal2 = new BigDecimal("987654321.123456789");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenAdd_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("1112222211.2222222211");
|
||||||
|
BigDecimal actual = bigDecimal1.add(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenMultiply_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("123030014929277547.5030955772112635269");
|
||||||
|
BigDecimal actual = bigDecimal1.multiply(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenSubtract_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("-863086431.0246913569");
|
||||||
|
BigDecimal actual = bigDecimal1.subtract(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenDivide_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("0.13");
|
||||||
|
BigDecimal actual = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class JavaDoubleUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDoubleLiteral_whenAssigningToDoubleVariable_thenValueIsNotExactlyEqual() {
|
||||||
|
double doubleValue = 0.1;
|
||||||
|
double epsilon = 0.0000000000000001;
|
||||||
|
assertEquals(0.1, doubleValue, epsilon);
|
||||||
|
}
|
||||||
|
}
|
@ -9,25 +9,21 @@ public class FloatDoubleConversionsTest {
|
|||||||
public void whenDoubleType_thenFloatTypeSuccess(){
|
public void whenDoubleType_thenFloatTypeSuccess(){
|
||||||
double interestRatesYearly = 13.333333333333334;
|
double interestRatesYearly = 13.333333333333334;
|
||||||
float interest = (float) interestRatesYearly;
|
float interest = (float) interestRatesYearly;
|
||||||
System.out.println(interest); //13.333333
|
Assert.assertEquals(13.333333f, interest, 0.000004f);
|
||||||
Assert.assertTrue(Float.class.isInstance(interest));//true
|
|
||||||
|
|
||||||
Double monthlyRates = 2.111111111111112;
|
Double monthlyRates = 2.111111111111112;
|
||||||
float rates = monthlyRates.floatValue();
|
float rates = monthlyRates.floatValue();
|
||||||
System.out.println(rates); //2.1111112
|
Assert.assertEquals(2.1111112f, rates, 0.00000013);
|
||||||
Assert.assertTrue(Float.class.isInstance(rates));//true
|
|
||||||
}
|
}
|
||||||
@Test
|
@Test
|
||||||
public void whenFloatType_thenDoubleTypeSuccess(){
|
public void whenFloatType_thenDoubleTypeSuccess(){
|
||||||
float gradeAverage =2.05f;
|
float gradeAverage =2.05f;
|
||||||
double average = gradeAverage;
|
double average = gradeAverage;
|
||||||
System.out.println(average); //2.049999952316284
|
Assert.assertEquals(2.05, average, 0.06);
|
||||||
Assert.assertTrue(Double.class.isInstance(average));//true
|
|
||||||
|
|
||||||
Float monthlyRates = 2.1111112f;
|
Float monthlyRates = 2.1111112f;
|
||||||
Double rates = monthlyRates.doubleValue();
|
Double rates = monthlyRates.doubleValue();
|
||||||
System.out.println(rates); //2.1111112
|
Assert.assertEquals(2.11111112, rates, 0.0000002);//true
|
||||||
Assert.assertTrue(Double.class.isInstance(rates));//true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.floattobigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class FloatToBigDecimalUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFloatComparedWithDifferentValues_thenCouldMatch() {
|
||||||
|
assertNotEquals(1.1f, 1.09f);
|
||||||
|
assertEquals(1.1f, 1.09999999f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromFloat_thenMatchesInternallyStoredValue() {
|
||||||
|
float floatToConvert = 1.10000002384185791015625f;
|
||||||
|
BigDecimal bdFromFloat = new BigDecimal(floatToConvert);
|
||||||
|
assertEquals("1.10000002384185791015625", bdFromFloat.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromString_thenPreservesTheOriginal() {
|
||||||
|
BigDecimal bdFromString = new BigDecimal("1.1");
|
||||||
|
assertEquals("1.1", bdFromString.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromFloatConvertedToString_thenFloatInternalValueGetsTruncated() {
|
||||||
|
String floatValue = Float.toString(1.10000002384185791015625f);
|
||||||
|
BigDecimal bdFromString = new BigDecimal(floatValue);
|
||||||
|
assertEquals("1.1", floatValue);
|
||||||
|
assertEquals("1.1", bdFromString.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedByValueOf_thenFloatValueGetsTruncated() {
|
||||||
|
assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDoubleConvertsFloatToString_thenFloatValueGetsTruncated() {
|
||||||
|
assertEquals("1.100000023841858", Double.toString(1.10000002384185791015625f));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -15,10 +15,8 @@ public class SimpleClient {
|
|||||||
SocketFactory factory = SSLSocketFactory.getDefault();
|
SocketFactory factory = SSLSocketFactory.getDefault();
|
||||||
|
|
||||||
try (Socket connection = factory.createSocket(host, port)) {
|
try (Socket connection = factory.createSocket(host, port)) {
|
||||||
((SSLSocket) connection).setEnabledCipherSuites(
|
((SSLSocket) connection).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
((SSLSocket) connection).setEnabledProtocols(new String[] { "TLSv1.2" });
|
||||||
((SSLSocket) connection).setEnabledProtocols(
|
|
||||||
new String[] { "TLSv1.2"});
|
|
||||||
SSLParameters sslParams = new SSLParameters();
|
SSLParameters sslParams = new SSLParameters();
|
||||||
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
||||||
((SSLSocket) connection).setSSLParameters(sslParams);
|
((SSLSocket) connection).setSSLParameters(sslParams);
|
||||||
@ -28,6 +26,7 @@ public class SimpleClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
System.out.println(startClient("localhost", 8443));
|
System.out.println(startClient("localhost", 8443));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,11 +14,10 @@ public class SimpleServer {
|
|||||||
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
||||||
|
|
||||||
try (ServerSocket listener = factory.createServerSocket(port)) {
|
try (ServerSocket listener = factory.createServerSocket(port)) {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
((SSLServerSocket) listener).setNeedClientAuth(true);
|
((SSLServerSocket) listener).setNeedClientAuth(true);
|
||||||
((SSLServerSocket) listener).setEnabledCipherSuites(
|
((SSLServerSocket) listener).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
((SSLServerSocket) listener).setEnabledProtocols(new String[] { "TLSv1.2" });
|
||||||
((SSLServerSocket) listener).setEnabledProtocols(
|
|
||||||
new String[] { "TLSv1.2"});
|
|
||||||
while (true) {
|
while (true) {
|
||||||
try (Socket socket = listener.accept()) {
|
try (Socket socket = listener.accept()) {
|
||||||
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
||||||
@ -29,6 +28,7 @@ public class SimpleServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
startServer(8443);
|
startServer(8443);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.charsequence;
|
package com.baeldung.charsequence;
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.Assert.assertNotEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
public class CharSequenceVsStringUnitTest {
|
public class CharSequenceVsStringUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -44,4 +44,43 @@ public class CharSequenceVsStringUnitTest {
|
|||||||
|
|
||||||
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCharSequenceAsString_whenConvertingUsingCasting_thenCorrect() {
|
||||||
|
String expected = "baeldung";
|
||||||
|
CharSequence charSequence = "baeldung";
|
||||||
|
String explicitCastedString = (String) charSequence;
|
||||||
|
|
||||||
|
assertEquals(expected, charSequence);
|
||||||
|
assertEquals(expected, explicitCastedString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ClassCastException.class)
|
||||||
|
public void givenCharSequenceAsStringBuiler_whenConvertingUsingCasting_thenThrowException() {
|
||||||
|
CharSequence charSequence = new StringBuilder("baeldung");
|
||||||
|
String castedString = (String) charSequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCharSequence_whenConvertingUsingToString_thenCorrect() {
|
||||||
|
String expected = "baeldung";
|
||||||
|
CharSequence charSequence1 = "baeldung";
|
||||||
|
CharSequence charSequence2 = new StringBuilder("baeldung");
|
||||||
|
|
||||||
|
assertEquals(expected, charSequence1.toString());
|
||||||
|
assertEquals(expected, charSequence2.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCharSequence_whenConvertingUsingValueOf_thenCorrect() {
|
||||||
|
String expected = "baeldung";
|
||||||
|
CharSequence charSequence1 = "baeldung";
|
||||||
|
CharSequence charSequence2 = new StringBuilder("baeldung");
|
||||||
|
CharSequence charSequence3 = null;
|
||||||
|
|
||||||
|
assertEquals(expected, String.valueOf(charSequence1));
|
||||||
|
assertEquals(expected, String.valueOf(charSequence2));
|
||||||
|
assertEquals("null", String.valueOf(charSequence3));
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -83,6 +83,7 @@
|
|||||||
<module>core-java-collections-maps</module>
|
<module>core-java-collections-maps</module>
|
||||||
<module>core-java-collections-maps-2</module>
|
<module>core-java-collections-maps-2</module>
|
||||||
<module>core-java-collections-maps-3</module>
|
<module>core-java-collections-maps-3</module>
|
||||||
|
<module>core-java-collections-maps-7</module>
|
||||||
<module>core-java-compiler</module>
|
<module>core-java-compiler</module>
|
||||||
<module>core-java-concurrency-2</module>
|
<module>core-java-concurrency-2</module>
|
||||||
<module>core-java-concurrency-advanced</module>
|
<module>core-java-concurrency-advanced</module>
|
||||||
|
@ -76,6 +76,11 @@
|
|||||||
<artifactId>jersey-apache-connector</artifactId>
|
<artifactId>jersey-apache-connector</artifactId>
|
||||||
<version>${jersey.version}</version>
|
<version>${jersey.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jersey.media</groupId>
|
||||||
|
<artifactId>jersey-media-multipart</artifactId>
|
||||||
|
<version>${jersey.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.jersey.server.form;
|
||||||
|
|
||||||
|
import jakarta.ws.rs.*;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
@Path("form")
|
||||||
|
public class FormExampleResource
|
||||||
|
{
|
||||||
|
@GET
|
||||||
|
@Path("/example1")
|
||||||
|
@Produces({MediaType.TEXT_HTML})
|
||||||
|
public InputStream getExample1() throws Exception
|
||||||
|
{
|
||||||
|
File f = new File("src/main/resources/html/example1.html");
|
||||||
|
return new FileInputStream(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/example2")
|
||||||
|
@Produces({MediaType.TEXT_HTML})
|
||||||
|
public InputStream getExample2() throws Exception
|
||||||
|
{
|
||||||
|
File f = new File("src/main/resources/html/example2.html");
|
||||||
|
return new FileInputStream(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/example1")
|
||||||
|
public String example1(@FormParam("first_name") String firstName,
|
||||||
|
@FormParam("last_name") String lastName,
|
||||||
|
@FormParam("age") String age)
|
||||||
|
{
|
||||||
|
return "Got: First = " + firstName + ", Last = " + lastName + ", Age = " + age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/example2")
|
||||||
|
@Consumes(MediaType.MULTIPART_FORM_DATA)
|
||||||
|
public String example2(@FormDataParam("first_name") String firstName,
|
||||||
|
@FormDataParam("last_name") String lastName,
|
||||||
|
@FormDataParam("age") String age,
|
||||||
|
@FormDataParam("photo") InputStream photo)
|
||||||
|
throws Exception
|
||||||
|
{
|
||||||
|
int len;
|
||||||
|
int size = 1024;
|
||||||
|
byte[] buf;
|
||||||
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||||
|
buf = new byte[size];
|
||||||
|
while ((len = photo.read(buf, 0, size)) != -1)
|
||||||
|
bos.write(buf, 0, len);
|
||||||
|
buf = bos.toByteArray();
|
||||||
|
return "Got: First = " + firstName + ", Last = " + lastName + ", Age = " + age + ", Photo (# of bytes) = " + buf.length;
|
||||||
|
}
|
||||||
|
}
|
16
jersey/src/main/resources/formexamples/example1.html
Normal file
16
jersey/src/main/resources/formexamples/example1.html
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Example 1 using @FormParam</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<form method="post" action="/form/example1">
|
||||||
|
<label for="first_name">First Name</label>
|
||||||
|
<input id="first_name" name="first_name" type="text">
|
||||||
|
<label for="last_name">Last Name</label>
|
||||||
|
<input id="last_name" name="last_name" type="text">
|
||||||
|
<label for="age">Age</label>
|
||||||
|
<input id="age" name="age" type="text">
|
||||||
|
<input type="submit">
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
18
jersey/src/main/resources/formexamples/example2.html
Normal file
18
jersey/src/main/resources/formexamples/example2.html
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Example 2 using @FormDataParam</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<form method="post" action="/form/example2" enctype="multipart/form-data">
|
||||||
|
<label for="first_name">First Name</label>
|
||||||
|
<input id="first_name" name="first_name" type="text">
|
||||||
|
<label for="last_name">Last Name</label>
|
||||||
|
<input id="last_name" name="last_name" type="text">
|
||||||
|
<label for="age">Age</label>
|
||||||
|
<input id="age" name="age" type="text">
|
||||||
|
<label for="photo">Profile Photo</label>
|
||||||
|
<input id="photo" name="photo" type="file">
|
||||||
|
<input type="submit">
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -11,6 +11,8 @@ public class LicenseDto {
|
|||||||
|
|
||||||
private LocalDateTime endDate;
|
private LocalDateTime endDate;
|
||||||
|
|
||||||
|
private String licenseType;
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@ -35,4 +37,12 @@ public class LicenseDto {
|
|||||||
this.endDate = endDate;
|
this.endDate = endDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLicenseType() {
|
||||||
|
return licenseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLicenseType(String licenseType) {
|
||||||
|
this.licenseType = licenseType;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ import java.time.OffsetDateTime;
|
|||||||
import java.time.ZoneOffset;
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
import org.mapstruct.AfterMapping;
|
import org.mapstruct.AfterMapping;
|
||||||
|
import org.mapstruct.Condition;
|
||||||
import org.mapstruct.Mapper;
|
import org.mapstruct.Mapper;
|
||||||
import org.mapstruct.Mapping;
|
import org.mapstruct.Mapping;
|
||||||
import org.mapstruct.MappingTarget;
|
import org.mapstruct.MappingTarget;
|
||||||
@ -40,4 +41,13 @@ public interface LicenseMapper {
|
|||||||
.toDays() <= 14;
|
.toDays() <= 14;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Condition
|
||||||
|
default boolean mapsToExpectedLicenseType(String licenseType) {
|
||||||
|
try {
|
||||||
|
return licenseType != null && License.LicenseType.valueOf(licenseType) != null;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -3,7 +3,6 @@ package com.baeldung.expression.model;
|
|||||||
import java.time.OffsetDateTime;
|
import java.time.OffsetDateTime;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
|
||||||
public class License {
|
public class License {
|
||||||
|
|
||||||
private UUID id;
|
private UUID id;
|
||||||
@ -16,6 +15,8 @@ public class License {
|
|||||||
|
|
||||||
private boolean renewalRequired;
|
private boolean renewalRequired;
|
||||||
|
|
||||||
|
private LicenseType licenseType;
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@ -55,4 +56,16 @@ public class License {
|
|||||||
public void setRenewalRequired(boolean renewalRequired) {
|
public void setRenewalRequired(boolean renewalRequired) {
|
||||||
this.renewalRequired = renewalRequired;
|
this.renewalRequired = renewalRequired;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public enum LicenseType {
|
||||||
|
INDIVIDUAL, FAMILY
|
||||||
|
}
|
||||||
|
|
||||||
|
public LicenseType getLicenseType() {
|
||||||
|
return licenseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLicenseType(LicenseType licenseType) {
|
||||||
|
this.licenseType = licenseType;
|
||||||
|
}
|
||||||
}
|
}
|
@ -6,6 +6,7 @@ import java.time.LocalDate;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mapstruct.factory.Mappers;
|
import org.mapstruct.factory.Mappers;
|
||||||
|
|
||||||
@ -74,4 +75,31 @@ class LicenseMapperUnitTest {
|
|||||||
assertThat(license.getId()).isSameAs(id);
|
assertThat(license.getId()).isSameAs(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLicenseDtoWithoutLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithoutLicenseType() {
|
||||||
|
LicenseDto licenseDto = new LicenseDto();
|
||||||
|
License license = licenseMapper.toLicense(licenseDto);
|
||||||
|
assertThat(license).isNotNull();
|
||||||
|
Assertions.assertNull(license.getLicenseType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLicenseDtoWithInvalidLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithoutLicenseType() {
|
||||||
|
LicenseDto licenseDto = new LicenseDto();
|
||||||
|
licenseDto.setLicenseType("invalid_license_type");
|
||||||
|
License license = licenseMapper.toLicense(licenseDto);
|
||||||
|
assertThat(license).isNotNull();
|
||||||
|
Assertions.assertNull(license.getLicenseType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLicenseDtoWithValidLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithMatchingLicenseType() {
|
||||||
|
LicenseDto licenseDto = new LicenseDto();
|
||||||
|
licenseDto.setLicenseType("INDIVIDUAL");
|
||||||
|
License license = licenseMapper.toLicense(licenseDto);
|
||||||
|
assertThat(license).isNotNull();
|
||||||
|
Assertions.assertNotNull(license.getLicenseType());
|
||||||
|
assertThat(license.getLicenseType()).isEqualTo(License.LicenseType.INDIVIDUAL);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,90 @@
|
|||||||
|
package com.baeldung.shardingsphere;
|
||||||
|
|
||||||
|
import org.assertj.core.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||||
|
import org.springframework.test.context.DynamicPropertySource;
|
||||||
|
import org.testcontainers.containers.MySQLContainer;
|
||||||
|
import org.testcontainers.junit.jupiter.Container;
|
||||||
|
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This Manual test requires: Docker service running.
|
||||||
|
*/
|
||||||
|
@Testcontainers
|
||||||
|
@SpringBootTest
|
||||||
|
class OrderServiceManualTest {
|
||||||
|
|
||||||
|
@Container
|
||||||
|
static MySQLContainer<?> mySQLContainer1 = new MySQLContainer<>("mysql:8.0.23")
|
||||||
|
.withDatabaseName("ds0")
|
||||||
|
.withUsername("test")
|
||||||
|
.withPassword("test");
|
||||||
|
|
||||||
|
@Container
|
||||||
|
static MySQLContainer<?> mySQLContainer2 = new MySQLContainer<>("mysql:8.0.23")
|
||||||
|
.withDatabaseName("ds1")
|
||||||
|
.withUsername("test")
|
||||||
|
.withPassword("test");
|
||||||
|
|
||||||
|
static {
|
||||||
|
mySQLContainer2.setPortBindings(List.of("13307:3306"));
|
||||||
|
mySQLContainer1.setPortBindings(List.of("13306:3306"));
|
||||||
|
}
|
||||||
|
@Autowired
|
||||||
|
private OrderService orderService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private OrderRepository orderRepository;
|
||||||
|
|
||||||
|
@DynamicPropertySource
|
||||||
|
static void setProperties(DynamicPropertyRegistry registry) {
|
||||||
|
registry.add("spring.jpa.hibernate.ddl-auto", () -> "create-drop");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldFindOrderInCorrectShard() {
|
||||||
|
// given
|
||||||
|
Order order1 = new Order(1L, 1L, BigDecimal.TEN, Status.PROCESSING, LocalDate.now(), "123 Main St");
|
||||||
|
Order order2 = new Order(2L, 2L, BigDecimal.valueOf(12.5), Status.SHIPPED, LocalDate.now(), "456 Main St");
|
||||||
|
|
||||||
|
// when
|
||||||
|
Order savedOrder1 = orderService.createOrder(order1);
|
||||||
|
Order savedOrder2 = orderService.createOrder(order2);
|
||||||
|
|
||||||
|
// then
|
||||||
|
// Assuming the sharding strategy is based on the order id, data for order1 should be present only in ds0
|
||||||
|
// and data for order2 should be present only in ds1
|
||||||
|
Assertions.assertThat(orderService.getOrder(savedOrder1.getOrderId())).isEqualTo(savedOrder1);
|
||||||
|
Assertions.assertThat(orderService.getOrder(savedOrder2.getOrderId())).isEqualTo(savedOrder2);
|
||||||
|
|
||||||
|
// Verify that the orders are not present in the wrong shards.
|
||||||
|
// You would need to implement these methods in your OrderService.
|
||||||
|
// They should use a JdbcTemplate or EntityManager to execute SQL directly against each shard.
|
||||||
|
Assertions.assertThat(assertOrderInShard(savedOrder1, mySQLContainer2)).isTrue();
|
||||||
|
Assertions.assertThat(assertOrderInShard(savedOrder2, mySQLContainer1)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean assertOrderInShard(Order order, MySQLContainer<?> container) {
|
||||||
|
try (Connection conn = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword())) {
|
||||||
|
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `order` WHERE order_id = ?");
|
||||||
|
stmt.setLong(1, order.getOrderId());
|
||||||
|
ResultSet rs = stmt.executeQuery();
|
||||||
|
return rs.next();
|
||||||
|
} catch (SQLException ex) {
|
||||||
|
throw new RuntimeException("Error querying order in shard", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
1
pom.xml
1
pom.xml
@ -1005,6 +1005,7 @@
|
|||||||
<module>spring-cloud-modules/spring-cloud-azure</module>
|
<module>spring-cloud-modules/spring-cloud-azure</module>
|
||||||
<module>spring-cloud-modules/spring-cloud-circuit-breaker</module>
|
<module>spring-cloud-modules/spring-cloud-circuit-breaker</module>
|
||||||
<module>spring-cloud-modules/spring-cloud-contract</module>
|
<module>spring-cloud-modules/spring-cloud-contract</module>
|
||||||
|
<module>spring-cloud-modules/spring-cloud-data-flow</module>
|
||||||
<module>spring-cloud-modules/spring-cloud-netflix-feign</module>
|
<module>spring-cloud-modules/spring-cloud-netflix-feign</module>
|
||||||
<module>spring-cloud-modules/spring-cloud-stream-starters</module>
|
<module>spring-cloud-modules/spring-cloud-stream-starters</module>
|
||||||
<module>spring-cloud-modules/spring-cloud-zuul-eureka-integration</module>
|
<module>spring-cloud-modules/spring-cloud-zuul-eureka-integration</module>
|
||||||
|
@ -25,6 +25,8 @@ import com.baeldung.testcontainers.support.MiddleEarthCharactersRepository;
|
|||||||
@Testcontainers
|
@Testcontainers
|
||||||
@SpringBootTest(webEnvironment = DEFINED_PORT)
|
@SpringBootTest(webEnvironment = DEFINED_PORT)
|
||||||
@DirtiesContext(classMode = AFTER_CLASS)
|
@DirtiesContext(classMode = AFTER_CLASS)
|
||||||
|
// Testcontainers require a valid docker installation.
|
||||||
|
// When running the tests, ensure you have a valid Docker environment
|
||||||
class DynamicPropertiesLiveTest {
|
class DynamicPropertiesLiveTest {
|
||||||
@Container
|
@Container
|
||||||
static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
|
static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
|
||||||
|
@ -8,6 +8,9 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.testcontainers.containers.MongoDBContainer;
|
import org.testcontainers.containers.MongoDBContainer;
|
||||||
import org.testcontainers.utility.DockerImageName;
|
import org.testcontainers.utility.DockerImageName;
|
||||||
|
|
||||||
|
|
||||||
|
// Testcontainers require a valid docker installation.
|
||||||
|
// When running the app locally, ensure you have a valid Docker environment
|
||||||
class LocalDevApplication {
|
class LocalDevApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
@ -24,6 +24,8 @@ import com.baeldung.testcontainers.support.MiddleEarthCharactersRepository;
|
|||||||
@Testcontainers
|
@Testcontainers
|
||||||
@SpringBootTest(webEnvironment = DEFINED_PORT)
|
@SpringBootTest(webEnvironment = DEFINED_PORT)
|
||||||
@DirtiesContext(classMode = AFTER_CLASS)
|
@DirtiesContext(classMode = AFTER_CLASS)
|
||||||
|
// Testcontainers require a valid docker installation.
|
||||||
|
// When running the tests, ensure you have a valid Docker environment
|
||||||
class ServiceConnectionLiveTest {
|
class ServiceConnectionLiveTest {
|
||||||
|
|
||||||
@Container
|
@Container
|
||||||
|
@ -60,7 +60,11 @@
|
|||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-params</artifactId>
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
<version>${jupiter.version}</version>
|
<version>${jupiter.version}</version>
|
||||||
<scope>test</scope>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-commons</artifactId>
|
||||||
|
<version>1.10.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mock-server</groupId>
|
<groupId>org.mock-server</groupId>
|
||||||
@ -204,7 +208,7 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<java.version>19</java.version>
|
<java.version>19</java.version>
|
||||||
<mapstruct.version>1.5.2.Final</mapstruct.version>
|
<mapstruct.version>1.5.2.Final</mapstruct.version>
|
||||||
<springdoc.version>2.0.0</springdoc.version>
|
<springdoc.version>2.2.0</springdoc.version>
|
||||||
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
|
||||||
<start-class>com.baeldung.sample.TodoApplication</start-class>
|
<start-class>com.baeldung.sample.TodoApplication</start-class>
|
||||||
<mockserver.version>5.14.0</mockserver.version>
|
<mockserver.version>5.14.0</mockserver.version>
|
||||||
|
@ -6,6 +6,8 @@ public class Article {
|
|||||||
Integer id;
|
Integer id;
|
||||||
String title;
|
String title;
|
||||||
|
|
||||||
|
public Article() {}
|
||||||
|
|
||||||
public Article(Integer id, String title) {
|
public Article(Integer id, String title) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.title = title;
|
this.title = title;
|
||||||
@ -19,6 +21,14 @@ public class Article {
|
|||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTitle(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
package com.baeldung.restclient;
|
package com.baeldung.restclient;
|
||||||
|
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
@ -13,13 +14,21 @@ public class ArticleController {
|
|||||||
Map<Integer, Article> database = new HashMap<>();
|
Map<Integer, Article> database = new HashMap<>();
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public Collection<Article> getArticles() {
|
public ResponseEntity<Collection<Article>> getArticles() {
|
||||||
return database.values();
|
Collection<Article> values = database.values();
|
||||||
|
if (values.isEmpty()) {
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(values);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public Article getArticle(@PathVariable Integer id) {
|
public ResponseEntity<Article> getArticle(@PathVariable("id") Integer id) {
|
||||||
return database.get(id);
|
Article article = database.get(id);
|
||||||
|
if (article == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(article);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@ -28,7 +37,7 @@ public class ArticleController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
public void updateArticle(@PathVariable Integer id, @RequestBody Article article) {
|
public void updateArticle(@PathVariable("id") Integer id, @RequestBody Article article) {
|
||||||
assert Objects.equals(id, article.getId());
|
assert Objects.equals(id, article.getId());
|
||||||
database.remove(id);
|
database.remove(id);
|
||||||
database.put(id, article);
|
database.put(id, article);
|
||||||
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.restclient;
|
||||||
|
|
||||||
|
public class ArticleNotFoundException extends RuntimeException {
|
||||||
|
public ArticleNotFoundException() {
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.restclient;
|
||||||
|
|
||||||
|
public class InvalidArticleResponseException extends RuntimeException {
|
||||||
|
public InvalidArticleResponseException() {
|
||||||
|
}
|
||||||
|
}
|
@ -1,17 +1,23 @@
|
|||||||
package com.baeldung.restclient;
|
package com.baeldung.restclient;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
import org.springframework.core.ParameterizedTypeReference;
|
||||||
|
import org.springframework.http.HttpStatusCode;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.client.RestClient;
|
import org.springframework.web.client.RestClient;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
|
||||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
@ -22,7 +28,10 @@ public class RestClientIntegrationTest {
|
|||||||
private String uriBase;
|
private String uriBase;
|
||||||
RestClient restClient = RestClient.create();
|
RestClient restClient = RestClient.create();
|
||||||
|
|
||||||
@BeforeAll
|
@Autowired
|
||||||
|
ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
public void setup() {
|
public void setup() {
|
||||||
uriBase = "http://localhost:" + port;
|
uriBase = "http://localhost:" + port;
|
||||||
}
|
}
|
||||||
@ -42,7 +51,7 @@ public class RestClientIntegrationTest {
|
|||||||
.retrieve()
|
.retrieve()
|
||||||
.body(String.class);
|
.body(String.class);
|
||||||
|
|
||||||
assertThat(articlesAsString).isEqualTo("[]");
|
assertThat(articlesAsString).isEqualTo("");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -63,6 +72,48 @@ public class RestClientIntegrationTest {
|
|||||||
assertThat(articles).isEqualTo(List.of(article));
|
assertThat(articles).isEqualTo(List.of(article));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldPostAndGetArticlesWithExchange() {
|
||||||
|
assertThatThrownBy(this::getArticlesWithExchange).isInstanceOf(ArticleNotFoundException.class);
|
||||||
|
|
||||||
|
Article article = new Article(1, "How to use RestClient");
|
||||||
|
restClient.post()
|
||||||
|
.uri(uriBase + "/articles")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.body(article)
|
||||||
|
.retrieve()
|
||||||
|
.toBodilessEntity();
|
||||||
|
|
||||||
|
List<Article> articles = getArticlesWithExchange();
|
||||||
|
|
||||||
|
assertThat(articles).isEqualTo(List.of(article));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Article> getArticlesWithExchange() {
|
||||||
|
return restClient.get()
|
||||||
|
.uri(uriBase + "/articles")
|
||||||
|
.exchange((request, response) -> {
|
||||||
|
if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(204))) {
|
||||||
|
throw new ArticleNotFoundException();
|
||||||
|
} else if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(200))) {
|
||||||
|
return objectMapper.readValue(response.getBody(), new TypeReference<>() {});
|
||||||
|
} else {
|
||||||
|
throw new InvalidArticleResponseException();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldPostAndGetArticlesWithErrorHandling() {
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
restClient.get()
|
||||||
|
.uri(uriBase + "/articles/1234")
|
||||||
|
.retrieve()
|
||||||
|
.onStatus(status -> status.value() == 404, (request, response) -> { throw new ArticleNotFoundException(); })
|
||||||
|
.body(new ParameterizedTypeReference<>() {});
|
||||||
|
}).isInstanceOf(ArticleNotFoundException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldPostAndPutAndGetArticles() {
|
void shouldPostAndPutAndGetArticles() {
|
||||||
Article article = new Article(1, "How to use RestClient");
|
Article article = new Article(1, "How to use RestClient");
|
||||||
@ -104,11 +155,12 @@ public class RestClientIntegrationTest {
|
|||||||
.retrieve()
|
.retrieve()
|
||||||
.toBodilessEntity();
|
.toBodilessEntity();
|
||||||
|
|
||||||
List<Article> articles = restClient.get()
|
ResponseEntity<Void> entity = restClient.get()
|
||||||
.uri(uriBase + "/articles")
|
.uri(uriBase + "/articles")
|
||||||
|
.accept(MediaType.APPLICATION_JSON)
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.body(new ParameterizedTypeReference<>() {});
|
.toBodilessEntity();
|
||||||
|
|
||||||
assertThat(articles).isEqualTo(List.of());
|
assertThat(entity.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(204));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,9 +9,10 @@
|
|||||||
<description>Demo project for Spring Boot</description>
|
<description>Demo project for Spring Boot</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-boot-modules</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -47,13 +48,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.rest-assured</groupId>
|
<groupId>io.rest-assured</groupId>
|
||||||
<artifactId>rest-assured</artifactId>
|
<artifactId>rest-assured</artifactId>
|
||||||
<version>${rest-assured.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
|
||||||
<version>${servlet.version}</version>
|
<version>${spring-boot-cloud-connectors.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -332,6 +332,7 @@
|
|||||||
<servlet.version>4.0.0</servlet.version>
|
<servlet.version>4.0.0</servlet.version>
|
||||||
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
|
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
|
||||||
<spring-cloud-gcp.version>1.0.0.RELEASE</spring-cloud-gcp.version>
|
<spring-cloud-gcp.version>1.0.0.RELEASE</spring-cloud-gcp.version>
|
||||||
|
<spring-boot-cloud-connectors.version>2.2.13.RELEASE</spring-boot-cloud-connectors.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -4,6 +4,7 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ -12,12 +13,11 @@ public class SecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests()
|
http.authorizeHttpRequests(expressionInterceptUrlRegistry ->
|
||||||
|
expressionInterceptUrlRegistry
|
||||||
.anyRequest()
|
.anyRequest()
|
||||||
.permitAll()
|
.permitAll())
|
||||||
.and()
|
.csrf(AbstractHttpConfigurer::disable);
|
||||||
.csrf()
|
|
||||||
.disable();
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.persistence.model;
|
package com.baeldung.persistence.model;
|
||||||
|
|
||||||
import javax.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Book {
|
public class Book {
|
||||||
|
@ -102,7 +102,7 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<start-class>com.baeldung.keycloak.SpringBoot</start-class>
|
<start-class>com.baeldung.keycloak.SpringBootKeycloakApp</start-class>
|
||||||
<jaxb-runtime.version>4.0.0</jaxb-runtime.version>
|
<jaxb-runtime.version>4.0.0</jaxb-runtime.version>
|
||||||
<wsdl4j.version>1.6.3</wsdl4j.version>
|
<wsdl4j.version>1.6.3</wsdl4j.version>
|
||||||
<jaxb2-maven-plugin.version>2.5.0</jaxb2-maven-plugin.version>
|
<jaxb2-maven-plugin.version>2.5.0</jaxb2-maven-plugin.version>
|
||||||
|
@ -6,11 +6,10 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
public class SpringBootKeycloakApp {
|
||||||
public class SpringBoot {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(SpringBoot.class, args);
|
SpringApplication.run(SpringBootKeycloakApp.class, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
@ -4,10 +4,9 @@ import org.junit.Test;
|
|||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
import com.baeldung.keycloak.SpringBoot;
|
|
||||||
|
|
||||||
@ExtendWith(SpringExtension.class)
|
@ExtendWith(SpringExtension.class)
|
||||||
@SpringBootTest(classes = { SpringBoot.class })
|
@SpringBootTest(classes = { SpringBootKeycloakApp.class })
|
||||||
public class KeycloakContextIntegrationTest {
|
public class KeycloakContextIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -3,10 +3,11 @@ package com.baeldung.swaggerkeycloak;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.config.Customizer;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.core.session.SessionRegistryImpl;
|
import org.springframework.security.core.session.SessionRegistryImpl;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
|
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
|
||||||
@ -24,16 +25,19 @@ public class GlobalSecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.csrf()
|
|
||||||
.disable()
|
http.csrf(AbstractHttpConfigurer::disable)
|
||||||
.authorizeRequests()
|
.authorizeHttpRequests((requests) -> requests.requestMatchers(HttpMethod.OPTIONS)
|
||||||
.requestMatchers(HttpMethod.OPTIONS)
|
|
||||||
.permitAll()
|
.permitAll()
|
||||||
.requestMatchers("/api/**")
|
.requestMatchers("/api/**")
|
||||||
.authenticated()
|
.authenticated()
|
||||||
.anyRequest()
|
.anyRequest()
|
||||||
.permitAll();
|
.permitAll());
|
||||||
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
|
|
||||||
|
http.oauth2ResourceServer((oauth2) -> oauth2
|
||||||
|
.jwt(Customizer.withDefaults())
|
||||||
|
);
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -41,28 +41,35 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-contract-wiremock</artifactId>
|
<artifactId>spring-cloud-contract-wiremock</artifactId>
|
||||||
<version>${spring-cloud.version}</version>
|
<version>${spring-cloud-contract.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-contract-stub-runner</artifactId>
|
<artifactId>spring-cloud-contract-stub-runner</artifactId>
|
||||||
<version>${spring-cloud.version}</version>
|
<version>${spring-cloud-contract.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||||||
<version>${spring-cloud.version}</version>
|
<version>${spring-cloud-contract.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud.version>4.0.3</spring-cloud.version>
|
<spring-cloud.version>4.0.3</spring-cloud.version>
|
||||||
|
<spring-cloud-contract.version>4.0.4</spring-cloud-contract.version>
|
||||||
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>
|
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>
|
||||||
<log4j2.version>2.17.1</log4j2.version>
|
<log4j2.version>2.17.1</log4j2.version>
|
||||||
|
<groovy.version>2.5.6</groovy.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -16,6 +16,15 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-rest</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-contract-wiremock</artifactId>
|
<artifactId>spring-cloud-contract-wiremock</artifactId>
|
||||||
@ -26,20 +35,13 @@
|
|||||||
<artifactId>spring-cloud-contract-stub-runner</artifactId>
|
<artifactId>spring-cloud-contract-stub-runner</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-data-rest</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
<artifactId>spring-cloud-contract-producer</artifactId>
|
<artifactId>spring-cloud-contract-producer</artifactId>
|
||||||
<version>${project.parent.version}</version>
|
<version>${project.parent.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.rest-assured</groupId>
|
<groupId>io.rest-assured</groupId>
|
||||||
<artifactId>rest-assured</artifactId>
|
<artifactId>rest-assured</artifactId>
|
||||||
@ -50,6 +52,12 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -16,19 +16,17 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.cloud</groupId>
|
|
||||||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-data-rest</artifactId>
|
<artifactId>spring-boot-starter-data-rest</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.rest-assured</groupId>
|
<groupId>io.rest-assured</groupId>
|
||||||
<artifactId>rest-assured</artifactId>
|
<artifactId>rest-assured</artifactId>
|
||||||
@ -39,6 +37,18 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -46,7 +56,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||||
<version>2.1.1.RELEASE</version>
|
<version>${spring-cloud-contract.version}</version>
|
||||||
<extensions>true</extensions>
|
<extensions>true</extensions>
|
||||||
<configuration>
|
<configuration>
|
||||||
<baseClassForTests>com.baeldung.spring.cloud.springcloudcontractproducer.BaseTestClass
|
<baseClassForTests>com.baeldung.spring.cloud.springcloudcontractproducer.BaseTestClass
|
||||||
|
@ -9,6 +9,7 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
import org.springframework.data.redis.connection.RedisConnection;
|
import org.springframework.data.redis.connection.RedisConnection;
|
||||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||||
|
import org.springframework.session.data.redis.config.ConfigureRedisAction;
|
||||||
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
@ -39,5 +40,10 @@ public class DataFlowServerApplicationIntegrationTest {
|
|||||||
|
|
||||||
return factory;
|
return factory;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public static ConfigureRedisAction configureRedisAction() {
|
||||||
|
return ConfigureRedisAction.NO_OP;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
import org.springframework.context.annotation.Scope;
|
import org.springframework.context.annotation.Scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
import com.baeldung.scope.singleton.SingletonFunctionBean;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class AppConfigFunctionBean {
|
public class AppConfigFunctionBean {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.scope;
|
package com.baeldung.scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonAppContextBean;
|
import com.baeldung.scope.singleton.SingletonAppContextBean;
|
||||||
import com.baeldung.scope.singletone.SingletonBean;
|
import com.baeldung.scope.singleton.SingletonBean;
|
||||||
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
|
import com.baeldung.scope.singleton.SingletonObjectFactoryBean;
|
||||||
import com.baeldung.scope.singletone.SingletonProviderBean;
|
import com.baeldung.scope.singleton.SingletonProviderBean;
|
||||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package com.baeldung.scope;
|
package com.baeldung.scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonBean;
|
import com.baeldung.scope.singleton.SingletonBean;
|
||||||
|
|
||||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||||
import org.springframework.context.annotation.*;
|
import org.springframework.context.annotation.*;
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package com.baeldung.scope;
|
package com.baeldung.scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonBean;
|
import com.baeldung.scope.singleton.SingletonBean;
|
||||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import org.springframework.beans.BeansException;
|
import org.springframework.beans.BeansException;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import org.apache.log4j.Logger;
|
import org.apache.log4j.Logger;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import org.springframework.beans.factory.annotation.Lookup;
|
import org.springframework.beans.factory.annotation.Lookup;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import org.springframework.beans.factory.ObjectFactory;
|
import org.springframework.beans.factory.ObjectFactory;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.scope.singletone;
|
package com.baeldung.scope.singleton;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
@ -1,10 +1,9 @@
|
|||||||
package com.baeldung.scope;
|
package com.baeldung.scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
import com.baeldung.scope.singleton.SingletonLookupBean;
|
||||||
import com.baeldung.scope.singletone.SingletonLookupBean;
|
import com.baeldung.scope.singleton.SingletonObjectFactoryBean;
|
||||||
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
|
import com.baeldung.scope.singleton.SingletonProviderBean;
|
||||||
import com.baeldung.scope.singletone.SingletonProviderBean;
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
@ -11,7 +11,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
|||||||
|
|
||||||
import com.baeldung.config.scope.AppConfigFunctionBean;
|
import com.baeldung.config.scope.AppConfigFunctionBean;
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
import com.baeldung.scope.singleton.SingletonFunctionBean;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class)
|
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user