Merge branch 'eugenp:master' into PR-6910
This commit is contained in:
commit
c689513bb0
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>
|
@ -49,10 +49,10 @@ public class ProductInfoRepositoryIntegrationTest {
|
|||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setupClass() {
|
public static void setupClass() {
|
||||||
Properties testProperties = loadFromFileInClasspath("test.properties")
|
Properties testProperties = loadFromFileInClasspath("test.properties")
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
||||||
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
||||||
|
|
||||||
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
||||||
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
@ -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>
|
||||||
|
|
||||||
|
@ -5,7 +5,6 @@ This module contains articles about Java 11 core features
|
|||||||
### Relevant articles
|
### Relevant articles
|
||||||
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
|
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
|
||||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||||
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
||||||
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
||||||
|
@ -4,5 +4,4 @@
|
|||||||
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
||||||
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
||||||
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
||||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
|
||||||
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
|
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
|
||||||
|
@ -0,0 +1,89 @@
|
|||||||
|
package com.baeldung.recordproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.RecordComponent;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
record Player(String name, int age, Long score) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReadRecordPropertiesByReflectionUnitTest {
|
||||||
|
private static final Player ERIC = new Player("Eric", 28, 4242L);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingRecordComponent_thenGetExpectedResult() {
|
||||||
|
var fields = new ArrayList<Field>();
|
||||||
|
RecordComponent[] components = Player.class.getRecordComponents();
|
||||||
|
for (var comp : components) {
|
||||||
|
try {
|
||||||
|
Field field = ERIC.getClass()
|
||||||
|
.getDeclaredField(comp.getName());
|
||||||
|
field.setAccessible(true);
|
||||||
|
fields.add(field);
|
||||||
|
} catch (NoSuchFieldException e) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(3, fields.size());
|
||||||
|
|
||||||
|
var nameField = fields.get(0);
|
||||||
|
var ageField = fields.get(1);
|
||||||
|
var scoreField = fields.get(2);
|
||||||
|
try {
|
||||||
|
assertEquals("name", nameField.getName());
|
||||||
|
assertEquals(String.class, nameField.getType());
|
||||||
|
assertEquals("Eric", nameField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("age", ageField.getName());
|
||||||
|
assertEquals(int.class, ageField.getType());
|
||||||
|
assertEquals(28, ageField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("score", scoreField.getName());
|
||||||
|
assertEquals(Long.class, scoreField.getType());
|
||||||
|
assertEquals(4242L, scoreField.get(ERIC));
|
||||||
|
} catch (IllegalAccessException exception) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingClassGetDeclaredField_thenGetExpectedResult() {
|
||||||
|
// record has no public fields
|
||||||
|
assertEquals(0, Player.class.getFields().length);
|
||||||
|
|
||||||
|
var fields = new ArrayList<Field>();
|
||||||
|
for (var field : Player.class.getDeclaredFields()) {
|
||||||
|
field.setAccessible(true);
|
||||||
|
fields.add(field);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(3, fields.size());
|
||||||
|
var nameField = fields.get(0);
|
||||||
|
var ageField = fields.get(1);
|
||||||
|
var scoreField = fields.get(2);
|
||||||
|
|
||||||
|
try {
|
||||||
|
assertEquals("name", nameField.getName());
|
||||||
|
assertEquals(String.class, nameField.getType());
|
||||||
|
assertEquals("Eric", nameField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("age", ageField.getName());
|
||||||
|
assertEquals(int.class, ageField.getType());
|
||||||
|
assertEquals(28, ageField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("score", scoreField.getName());
|
||||||
|
assertEquals(Long.class, scoreField.getType());
|
||||||
|
assertEquals(4242L, scoreField.get(ERIC));
|
||||||
|
} catch (IllegalAccessException ex) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -10,3 +10,4 @@ This module contains articles about arrays conversion in Java
|
|||||||
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
|
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
|
||||||
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
||||||
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
||||||
|
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||||
|
@ -123,6 +123,7 @@ public class HttpClientPost {
|
|||||||
|
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(URI.create(serviceUrl))
|
.uri(URI.create(serviceUrl))
|
||||||
|
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
|
.POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class Book {
|
||||||
|
public String author;
|
||||||
|
public int isbn;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookDetails {
|
||||||
|
|
||||||
|
public String bookDetails(Book book) {
|
||||||
|
return "author name: " + book.author + " ISBN: " + book.isbn;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookEncapsulation {
|
||||||
|
public String author;
|
||||||
|
public int isbn;
|
||||||
|
public int id = 1;
|
||||||
|
|
||||||
|
public BookEncapsulation(String author, int isbn) {
|
||||||
|
this.author = author;
|
||||||
|
this.isbn = isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBookDetails() {
|
||||||
|
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookInformationHiding {
|
||||||
|
private String author;
|
||||||
|
private int isbn;
|
||||||
|
private int id = 1;
|
||||||
|
|
||||||
|
public BookInformationHiding(String author, int isbn) {
|
||||||
|
setAuthor(author);
|
||||||
|
setIsbn(isbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getIsbn() {
|
||||||
|
return isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsbn(int isbn) {
|
||||||
|
if (isbn < 0) {
|
||||||
|
throw new IllegalArgumentException("ISBN can't be negative");
|
||||||
|
}
|
||||||
|
this.isbn = isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBookDetails() {
|
||||||
|
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class EncapsulationAndInformationHidingUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnencapsulatedClass_whenImplementationClassIsSeparate_thenReturnResult() {
|
||||||
|
Book myBook = new Book();
|
||||||
|
myBook.author = "J.K Rowlings";
|
||||||
|
myBook.isbn = 67890;
|
||||||
|
BookDetails details = new BookDetails();
|
||||||
|
String result = details.bookDetails(myBook);
|
||||||
|
assertEquals("author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncapsulatedClass_whenDataIsNotHidden_thenReturnResult() {
|
||||||
|
BookEncapsulation myBook = new BookEncapsulation("J.K Rowlings", 67890);
|
||||||
|
String result = myBook.getBookDetails();
|
||||||
|
assertEquals("author id: " + 1 + " author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncapsulatedClass_whenDataIsHidden_thenReturnResult() {
|
||||||
|
BookInformationHiding myBook = new BookInformationHiding("J.K Rowlings", 67890);
|
||||||
|
String result = myBook.getBookDetails();
|
||||||
|
assertEquals("author id: " + 1 + " author name: " + myBook.getAuthor() + " ISBN: " + myBook.getIsbn(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -5,4 +5,5 @@
|
|||||||
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||||
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
||||||
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
||||||
|
- [Finding the Square Root of a BigInteger in Java](https://www.baeldung.com/java-find-square-root-biginteger)
|
||||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||||
|
2
core-java-modules/core-java-reflection-3/README.md
Normal file
2
core-java-modules/core-java-reflection-3/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Is Java Reflection Bad Practice?](https://www.baeldung.com/java-reflection-bad-practice)
|
78
core-java-modules/core-java-reflection-3/pom.xml
Normal file
78
core-java-modules/core-java-reflection-3/pom.xml
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
<?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-reflection-3</artifactId>
|
||||||
|
<name>core-java-reflection-3</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.reflections</groupId>
|
||||||
|
<artifactId>reflections</artifactId>
|
||||||
|
<version>${reflections.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-reflection-3</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${source.version}</source>
|
||||||
|
<target>${target.version}</target>
|
||||||
|
<compilerArgument>-parameters</compilerArgument>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.jacoco</groupId>
|
||||||
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
|
<version>0.8.8</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<reflections.version>0.9.12</reflections.version>
|
||||||
|
<source.version>1.8</source.version>
|
||||||
|
<target.version>1.8</target.version>
|
||||||
|
<spring.version>5.3.4</spring.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.encapsulation;
|
||||||
|
|
||||||
|
public class MyClass {
|
||||||
|
|
||||||
|
private String veryPrivateField;
|
||||||
|
|
||||||
|
public MyClass() {
|
||||||
|
|
||||||
|
this.veryPrivateField = "Secret Information";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
public class BenchmarkRunner {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class InitializationBenchmark {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void directInit() {
|
||||||
|
|
||||||
|
Person person = new Person("John", "Doe", 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void reflectiveInit() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
Constructor<Person> constructor = Person.class.getDeclaredConstructor(String.class, String.class, Integer.class);
|
||||||
|
Person person = constructor.newInstance("John", "Doe", 50);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class MethodInvocationBenchmark {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void directCall() {
|
||||||
|
|
||||||
|
directCall(new Person("John", "Doe", 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void reflectiveCall() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
|
||||||
|
|
||||||
|
reflectiveCall(new Person("John", "Doe", 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void directCall(Person person) {
|
||||||
|
|
||||||
|
person.getFirstName();
|
||||||
|
person.getLastName();
|
||||||
|
person.getAge();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reflectiveCall(Person person) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||||
|
|
||||||
|
Method getFirstNameMethod = Person.class.getMethod("getFirstName");
|
||||||
|
getFirstNameMethod.invoke(person);
|
||||||
|
|
||||||
|
Method getLastNameMethod = Person.class.getMethod("getLastName");
|
||||||
|
getLastNameMethod.invoke(person);
|
||||||
|
|
||||||
|
Method getAgeMethod = Person.class.getMethod("getAge");
|
||||||
|
getAgeMethod.invoke(person);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Integer age;
|
||||||
|
|
||||||
|
public Person(String firstName, String lastName, Integer age) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
this.lastName = lastName;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFirstName(String firstName) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastName(String lastName) {
|
||||||
|
this.lastName = lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(Integer age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.encapsulation;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class ReflectionEncapsulationUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrivateField_whenUsingReflection_thenIsAccessible() throws IllegalAccessException, NoSuchFieldException {
|
||||||
|
MyClass myClassInstance = new MyClass();
|
||||||
|
|
||||||
|
Field privateField = MyClass.class.getDeclaredField("veryPrivateField");
|
||||||
|
privateField.setAccessible(true);
|
||||||
|
|
||||||
|
String accessedField = privateField.get(myClassInstance).toString();
|
||||||
|
assertEquals(accessedField, "Secret Information");
|
||||||
|
}
|
||||||
|
}
|
@ -4,12 +4,9 @@ This module contains articles about the Stream API in Java.
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
|
||||||
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
|
||||||
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
|
||||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||||
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.streams;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -37,6 +38,7 @@ public class Java8StreamApiUnitTest {
|
|||||||
assertEquals(list.size() - 1, size);
|
assertEquals(list.size() - 1, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Ignore
|
||||||
@Test
|
@Test
|
||||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||||
|
|
||||||
|
@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
This module contains articles about the Stream API in Java.
|
This module contains articles about the Stream API in Java.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
|
||||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||||
@ -12,5 +11,4 @@ This module contains articles about the Stream API in Java.
|
|||||||
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
|
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
|
||||||
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
|
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
|
||||||
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
|
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
|
||||||
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
|
|
||||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||||
|
@ -3,3 +3,4 @@
|
|||||||
- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream)
|
- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream)
|
||||||
- [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions)
|
- [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions)
|
||||||
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)
|
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)
|
||||||
|
- [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream)
|
||||||
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.BinaryOperator;
|
||||||
|
import java.util.stream.Collector;
|
||||||
|
|
||||||
|
class SkippingCollector {
|
||||||
|
private static final BinaryOperator<SkippingCollector> IGNORE_COMBINE = (a, b) -> a;
|
||||||
|
private final int skip;
|
||||||
|
private final List<String> list = new ArrayList<>();
|
||||||
|
private int currentIndex = 0;
|
||||||
|
private SkippingCollector(int skip) {
|
||||||
|
this.skip = skip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void accept(String item) {
|
||||||
|
final int index = ++currentIndex % skip;
|
||||||
|
if (index == 0)
|
||||||
|
list.add(item);
|
||||||
|
}
|
||||||
|
private List<String> getResult() {
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Collector<String, SkippingCollector, List<String>> collector(int skip) {
|
||||||
|
return Collector.of(() -> new SkippingCollector(skip),
|
||||||
|
SkippingCollector::accept,
|
||||||
|
IGNORE_COMBINE,
|
||||||
|
SkippingCollector::getResult);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class SkippingElements {
|
||||||
|
|
||||||
|
private SkippingElements() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithFilter(List<String> sourceList, int n) {
|
||||||
|
return IntStream.range(0, sourceList.size())
|
||||||
|
.filter(s -> (s + 1) % n == 0)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithIterate(List<String> sourceList, int n) {
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
return IntStream.iterate(n - 1, i -> (i + n))
|
||||||
|
.limit(limit)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithSublist(List<String> sourceList, int n) {
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
return Stream.iterate(sourceList, s -> s.subList(n, s.size()))
|
||||||
|
.limit(limit)
|
||||||
|
.map(s -> s.get(n - 1))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithFor(List<String> sourceList, int n) {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (int i = n - 1; i < sourceList.size(); i += n) {
|
||||||
|
result.add(sourceList.get(i));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithIterator(Stream<String> sourceStream, int n) {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
final Iterator<String> iterator = sourceStream.iterator();
|
||||||
|
int count = 0;
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (count % n == n - 1) {
|
||||||
|
result.add(iterator.next());
|
||||||
|
} else {
|
||||||
|
iterator.next();
|
||||||
|
}
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInStreamWithCollector(Stream<String> sourceStream, int n) {
|
||||||
|
return sourceStream.collect(SkippingCollector.collector(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,114 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.Arguments;
|
||||||
|
import org.junit.jupiter.params.provider.MethodSource;
|
||||||
|
|
||||||
|
class SkippingElementsUnitTest {
|
||||||
|
|
||||||
|
private static Stream<Arguments> testSource() {
|
||||||
|
return Stream.of(
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty", "Thirty Three"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
1),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Wednesday", "Saturday"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Friday"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
1),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("March", "June", "September", "December"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("May", "October"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithFilter(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithIterate(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithSublist(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithFor(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final Stream<String> inputStream = input.stream();
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithIterator(inputStream, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final Stream<String> inputStream = input.stream();
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInStreamWithCollector(inputStream, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
14
core-java-modules/core-java-streams-simple/README.md
Normal file
14
core-java-modules/core-java-streams-simple/README.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
## Java Streams Ebook
|
||||||
|
|
||||||
|
This module contains articles about Streams that are part of the Java Streams Ebook.
|
||||||
|
|
||||||
|
### Relevant Articles
|
||||||
|
|
||||||
|
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||||
|
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||||
|
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
||||||
|
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||||
|
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||||
|
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
|
||||||
|
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||||
|
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
52
core-java-modules/core-java-streams-simple/pom.xml
Normal file
52
core-java-modules/core-java-streams-simple/pom.xml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-streams-simple</artifactId>
|
||||||
|
<name>core-java-streams-simple</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.pivovarit</groupId>
|
||||||
|
<artifactId>throwing-function</artifactId>
|
||||||
|
<version>${throwing-function.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-streams-simple</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<throwing-function.version>1.5.1</throwing-function.version>
|
||||||
|
<maven.compiler.source.version>17</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>17</maven.compiler.target.version>
|
||||||
|
<maven.compiler.release>17</maven.compiler.release>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.streams.filter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import javax.net.ssl.HttpsURLConnection;
|
||||||
|
|
||||||
|
public class Customer {
|
||||||
|
private String name;
|
||||||
|
private int points;
|
||||||
|
private String profilePhotoUrl;
|
||||||
|
|
||||||
|
public Customer(String name, int points) {
|
||||||
|
this(name, points, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(String name, int points, String profilePhotoUrl) {
|
||||||
|
this.name = name;
|
||||||
|
this.points = points;
|
||||||
|
this.profilePhotoUrl = profilePhotoUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPoints() {
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasOver(int points) {
|
||||||
|
return this.points > points;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasOverHundredPoints() {
|
||||||
|
return this.points > 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasValidProfilePhoto() throws IOException {
|
||||||
|
URL url = new URL(this.profilePhotoUrl);
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||||
|
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasValidProfilePhotoWithoutCheckedException() {
|
||||||
|
try {
|
||||||
|
URL url = new URL(this.profilePhotoUrl);
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||||
|
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import java.util.IntSummaryStatistics;
|
import java.util.IntSummaryStatistics;
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
public enum BlogPostType {
|
public enum BlogPostType {
|
||||||
NEWS, REVIEW, GUIDE
|
NEWS, REVIEW, GUIDE
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
@ -1,8 +1,7 @@
|
|||||||
package com.baeldung.reduce.application;
|
package com.baeldung.streams.reduce.application;
|
||||||
|
|
||||||
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.reduce.benchmarks;
|
package com.baeldung.streams.reduce.benchmarks;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.openjdk.jmh.annotations.Benchmark;
|
import org.openjdk.jmh.annotations.Benchmark;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
public class Review {
|
public class Review {
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
public class User {
|
public class User {
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.utilities;
|
package com.baeldung.streams.reduce.utilities;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.BiFunction;
|
import java.util.function.BiFunction;
|
@ -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>
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.collectors;
|
package com.baeldung.streams.collectors;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.stream.filter;
|
package com.baeldung.streams.filter;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import com.pivovarit.function.ThrowingPredicate;
|
import com.pivovarit.function.ThrowingPredicate;
|
||||||
@ -14,10 +14,10 @@ import java.util.stream.Stream;
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||||
|
|
||||||
public class StreamFilterUnitTest {
|
class StreamFilterUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
|
void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
|
||||||
Customer john = new Customer("John P.", 15);
|
Customer john = new Customer("John P.", 15);
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -53,7 +53,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
|
void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
|
||||||
Customer john = new Customer("John P.", 15);
|
Customer john = new Customer("John P.", 15);
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -70,7 +70,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
|
void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
|
||||||
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
|
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
|
||||||
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
|
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
|
||||||
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
|
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
|
||||||
@ -89,7 +89,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
|
void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
|
||||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -103,7 +103,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
|
void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
|
||||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.streams.flatmap.map;
|
package com.baeldung.streams.flatmap.map;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
@ -10,12 +11,12 @@ import java.util.stream.Collectors;
|
|||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class Java8MapAndFlatMapUnitTest {
|
|
||||||
|
class Java8MapAndFlatMapUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whenCalledMap_thenProduceList() {
|
void givenStream_whenCalledMap_thenProduceList() {
|
||||||
List<String> myList = Stream.of("a", "b")
|
List<String> myList = Stream.of("a", "b")
|
||||||
.map(String::toUpperCase)
|
.map(String::toUpperCase)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
@ -23,7 +24,7 @@ public class Java8MapAndFlatMapUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
|
void givenStream_whenCalledFlatMap_thenProduceFlattenedList() {
|
||||||
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
||||||
System.out.println(list);
|
System.out.println(list);
|
||||||
|
|
||||||
@ -33,13 +34,13 @@ public class Java8MapAndFlatMapUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenCalledMap_thenProduceOptional() {
|
void givenOptional_whenCalledMap_thenProduceOptional() {
|
||||||
Optional<String> s = Optional.of("test");
|
Optional<String> s = Optional.of("test");
|
||||||
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
||||||
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
||||||
.map(s -> Optional.of("STRING")));
|
.map(s -> Optional.of("STRING")));
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import static java.util.Comparator.comparingInt;
|
import static java.util.Comparator.comparingInt;
|
||||||
import static java.util.stream.Collectors.averagingInt;
|
import static java.util.stream.Collectors.averagingInt;
|
||||||
@ -33,13 +33,13 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
|
|||||||
import org.apache.commons.lang3.tuple.Pair;
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class JavaGroupingByCollectorUnitTest {
|
class JavaGroupingByCollectorUnitTest {
|
||||||
|
|
||||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType));
|
.collect(groupingBy(BlogPost::getType));
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||||
|
|
||||||
@ -62,7 +62,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||||
.collect(groupingByConcurrent(BlogPost::getType));
|
.collect(groupingByConcurrent(BlogPost::getType));
|
||||||
|
|
||||||
@ -114,7 +114,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -127,7 +127,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, counting()));
|
.collect(groupingBy(BlogPost::getType, counting()));
|
||||||
|
|
||||||
@ -140,7 +140,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||||
|
|
||||||
@ -164,7 +164,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||||
|
|
||||||
@ -189,7 +189,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -203,7 +203,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
|
void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
|
||||||
|
|
||||||
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
||||||
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));
|
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.streams;
|
package com.baeldung.streams.map;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -1,79 +1,80 @@
|
|||||||
package com.baeldung.reduce;
|
package com.baeldung.streams.reduce;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
|
||||||
import org.junit.Test;
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
|
import com.baeldung.streams.reduce.utilities.NumberUtils;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
class StreamReduceUnitTest {
|
||||||
|
|
||||||
public class StreamReduceUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||||
assertThat(result).isEqualTo(21);
|
assertThat(result).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
int result = numbers.stream().reduce(0, Integer::sum);
|
int result = numbers.stream().reduce(0, Integer::sum);
|
||||||
assertThat(result).isEqualTo(21);
|
assertThat(result).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", String::concat);
|
String result = letters.stream().reduce("", String::concat);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||||
assertThat(result).isEqualTo("ABCDE");
|
assertThat(result).isEqualTo("ABCDE");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
assertThat(result).isEqualTo(65);
|
assertThat(result).isEqualTo(65);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.parallelStream().reduce("", String::concat);
|
String result = letters.parallelStream().reduce("", String::concat);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
@ -9,7 +9,6 @@ This module contains articles about the Stream API in Java.
|
|||||||
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
|
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
|
||||||
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
|
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
|
||||||
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
||||||
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
|
||||||
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
||||||
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
|
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
|
||||||
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
|
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
|
||||||
|
@ -29,11 +29,6 @@
|
|||||||
<artifactId>streamex</artifactId>
|
<artifactId>streamex</artifactId>
|
||||||
<version>${streamex.version}</version>
|
<version>${streamex.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.pivovarit</groupId>
|
|
||||||
<artifactId>throwing-function</artifactId>
|
|
||||||
<version>${throwing-function.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -62,8 +57,6 @@
|
|||||||
<vavr.version>0.10.4</vavr.version>
|
<vavr.version>0.10.4</vavr.version>
|
||||||
<protonpack.version>1.16</protonpack.version>
|
<protonpack.version>1.16</protonpack.version>
|
||||||
<streamex.version>0.8.1</streamex.version>
|
<streamex.version>0.8.1</streamex.version>
|
||||||
<throwing-function.version>1.5.1</throwing-function.version>
|
|
||||||
|
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.joinasnl;
|
||||||
|
|
||||||
|
import static java.util.Collections.emptyList;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class JoinStringsAsNaturalLangUnitTest {
|
||||||
|
String joinItemsAsNaturalLanguage(List<String> list, boolean oxfordComma) {
|
||||||
|
if (list.size() < 3) {
|
||||||
|
return String.join(" and ", list);
|
||||||
|
}
|
||||||
|
// list has at least three elements
|
||||||
|
int lastIdx = list.size() - 1;
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
return sb.append(String.join(", ", list.subList(0, lastIdx)))
|
||||||
|
.append(oxfordComma ? ", and " : " and ")
|
||||||
|
.append(list.get(lastIdx))
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingJoinByGrammar_thenGetTheExpectedResult() {
|
||||||
|
assertEquals("", joinItemsAsNaturalLanguage(emptyList(), false));
|
||||||
|
assertEquals("A", joinItemsAsNaturalLanguage(List.of("A"), false));
|
||||||
|
assertEquals("A and B", joinItemsAsNaturalLanguage(List.of("A", "B"), false));
|
||||||
|
assertEquals("A, B, C, D and I have a comma (,)", joinItemsAsNaturalLanguage(List.of("A", "B", "C", "D", "I have a comma (,)"), false));
|
||||||
|
// with oxford comma = true
|
||||||
|
assertEquals("", joinItemsAsNaturalLanguage(emptyList(), true));
|
||||||
|
assertEquals("A", joinItemsAsNaturalLanguage(List.of("A"), true));
|
||||||
|
assertEquals("A and B", joinItemsAsNaturalLanguage(List.of("A", "B"), true));
|
||||||
|
assertEquals("A, B, C, D, and I have a comma (,)", joinItemsAsNaturalLanguage(List.of("A", "B", "C", "D", "I have a comma (,)"), true));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.stringsplitkeyvalue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.StringTokenizer;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class StringSplitKeyValueUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringData_whenUsingTokenizer_thenTokenizeAndValidate() {
|
||||||
|
String data = "name=John age=30 city=NewYork";
|
||||||
|
StringTokenizer tokenizer = new StringTokenizer(data);
|
||||||
|
|
||||||
|
// Create a map to store key-value pairs
|
||||||
|
Map<String, String> keyValueMap = new HashMap<>();
|
||||||
|
|
||||||
|
while (tokenizer.hasMoreTokens()) {
|
||||||
|
String token = tokenizer.nextToken();
|
||||||
|
String[] keyValue = token.split("=");
|
||||||
|
|
||||||
|
if (keyValue.length == 2) {
|
||||||
|
String key = keyValue[0];
|
||||||
|
String value = keyValue[1];
|
||||||
|
|
||||||
|
// Store key-value pairs in the map
|
||||||
|
keyValueMap.put(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use assertions to validate the key-value pairs in the map
|
||||||
|
assertEquals("John", keyValueMap.get("name"));
|
||||||
|
assertEquals("30", keyValueMap.get("age"));
|
||||||
|
assertEquals("NewYork", keyValueMap.get("city"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDataWithPattern_whenUsingMatcher_thenPerformPatternMatching() {
|
||||||
|
String data = "name=John,age=30;city=NewYork";
|
||||||
|
Pattern pattern = Pattern.compile("\\b(\\w+)=(\\w+)\\b");
|
||||||
|
Matcher matcher = pattern.matcher(data);
|
||||||
|
|
||||||
|
// Create a map to store key-value pairs
|
||||||
|
Map<String, String> keyValueMap = new HashMap<>();
|
||||||
|
|
||||||
|
while (matcher.find()) {
|
||||||
|
String key = matcher.group(1);
|
||||||
|
String value = matcher.group(2);
|
||||||
|
|
||||||
|
// Store key-value pairs in the map
|
||||||
|
keyValueMap.put(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use assertions to validate the key-value pairs in the map
|
||||||
|
assertEquals("John", keyValueMap.get("name"));
|
||||||
|
assertEquals("30", keyValueMap.get("age"));
|
||||||
|
assertEquals("NewYork", keyValueMap.get("city"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringData_whenUsingJavaMap_thenSplitAndValidate() {
|
||||||
|
String data = "name=John age=30 city=NewYork";
|
||||||
|
Map<String, String> keyValueMap = Arrays.stream(data.split(" "))
|
||||||
|
.map(kv -> kv.split("="))
|
||||||
|
.filter(kvArray -> kvArray.length == 2)
|
||||||
|
.collect(Collectors.toMap(kv -> kv[0], kv -> kv[1]));
|
||||||
|
|
||||||
|
assertEquals("John", keyValueMap.get("name"));
|
||||||
|
assertEquals("30", keyValueMap.get("age"));
|
||||||
|
assertEquals("NewYork", keyValueMap.get("city"));
|
||||||
|
}
|
||||||
|
}
|
@ -158,6 +158,7 @@
|
|||||||
<module>core-java-properties</module>
|
<module>core-java-properties</module>
|
||||||
<module>core-java-reflection</module>
|
<module>core-java-reflection</module>
|
||||||
<module>core-java-reflection-2</module>
|
<module>core-java-reflection-2</module>
|
||||||
|
<module>core-java-reflection-3</module>
|
||||||
<module>core-java-scanner</module>
|
<module>core-java-scanner</module>
|
||||||
<module>core-java-security-2</module>
|
<module>core-java-security-2</module>
|
||||||
<module>core-java-security-3</module>
|
<module>core-java-security-3</module>
|
||||||
@ -165,6 +166,7 @@
|
|||||||
<module>core-java-security-algorithms</module>
|
<module>core-java-security-algorithms</module>
|
||||||
<module>core-java-serialization</module>
|
<module>core-java-serialization</module>
|
||||||
<module>core-java-streams</module>
|
<module>core-java-streams</module>
|
||||||
|
<module>core-java-streams-simple</module>
|
||||||
<module>core-java-streams-3</module>
|
<module>core-java-streams-3</module>
|
||||||
<module>core-java-string-algorithms</module>
|
<module>core-java-string-algorithms</module>
|
||||||
<module>core-java-string-algorithms-2</module>
|
<module>core-java-string-algorithms-2</module>
|
||||||
|
@ -7,7 +7,7 @@ This module contains articles about Bean Validation.
|
|||||||
- [Validating Container Elements with Jakarta Bean Validation 3.0](https://www.baeldung.com/bean-validation-container-elements)
|
- [Validating Container Elements with Jakarta Bean Validation 3.0](https://www.baeldung.com/bean-validation-container-elements)
|
||||||
- [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums)
|
- [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums)
|
||||||
- [Javax BigDecimal Validation](https://www.baeldung.com/javax-bigdecimal-validation)
|
- [Javax BigDecimal Validation](https://www.baeldung.com/javax-bigdecimal-validation)
|
||||||
- [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups)
|
- [Grouping Jakarta (Javax) Validation Constraints](https://www.baeldung.com/javax-validation-groups)
|
||||||
- [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition)
|
- [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition)
|
||||||
- [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter)
|
- [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter)
|
||||||
- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
|
- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
|
||||||
|
@ -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>
|
||||||
@ -102,4 +107,4 @@
|
|||||||
<jersey.version>3.1.1</jersey.version>
|
<jersey.version>3.1.1</jersey.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -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>
|
@ -5,3 +5,4 @@ This module contains articles about Micronaut.
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Introduction to Micronaut Framework](https://www.baeldung.com/micronaut)
|
- [Introduction to Micronaut Framework](https://www.baeldung.com/micronaut)
|
||||||
- [Micronaut vs. Spring Boot](https://www.baeldung.com/micronaut-vs-spring-boot)
|
- [Micronaut vs. Spring Boot](https://www.baeldung.com/micronaut-vs-spring-boot)
|
||||||
|
- [API Versioning in Micronaut](https://www.baeldung.com/java-api-versioning-micronaut)
|
||||||
|
@ -9,9 +9,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-2</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -49,10 +49,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>mysql</groupId>
|
<groupId>mysql</groupId>
|
||||||
<artifactId>mysql-connector-java</artifactId>
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
</dependency>
|
<version>${mysql-connector-java.version}</version>
|
||||||
<dependency>
|
|
||||||
<groupId>javax.validation</groupId>
|
|
||||||
<artifactId>validation-api</artifactId>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.xerial</groupId>
|
<groupId>org.xerial</groupId>
|
||||||
@ -66,11 +63,17 @@
|
|||||||
<groupId>org.hsqldb</groupId>
|
<groupId>org.hsqldb</groupId>
|
||||||
<artifactId>hsqldb</artifactId>
|
<artifactId>hsqldb</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>jakarta.validation</groupId>
|
||||||
|
<artifactId>jakarta.validation-api</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<mockito.version>2.23.0</mockito.version>
|
<mockito.version>2.23.0</mockito.version>
|
||||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||||
|
<mysql-connector-java.version>8.0.31</mysql-connector-java.version>
|
||||||
|
<start-class>com.baeldung.boot.Application</start-class>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -13,7 +13,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
|||||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
import javax.persistence.EntityManagerFactory;
|
import jakarta.persistence.EntityManagerFactory;
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.boot.domain;
|
package com.baeldung.boot.domain;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author paullatzelsperger
|
* @author paullatzelsperger
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.boot.domain;
|
package com.baeldung.boot.domain;
|
||||||
|
|
||||||
import static javax.persistence.GenerationType.IDENTITY;
|
import static jakarta.persistence.GenerationType.IDENTITY;
|
||||||
|
|
||||||
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.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Country {
|
public class Country {
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.boot.domain;
|
package com.baeldung.boot.domain;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author harshavs
|
* @author harshavs
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.boot.domain;
|
package com.baeldung.boot.domain;
|
||||||
|
|
||||||
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 GenericEntity {
|
public class GenericEntity {
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.boot.domain;
|
package com.baeldung.boot.domain;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "users")
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.boot.naming.entity;
|
package com.baeldung.boot.naming.entity;
|
||||||
|
|
||||||
import javax.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.boot.naming.entity;
|
package com.baeldung.boot.naming.entity;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Preference {
|
public class Preference {
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.dataloading.model;
|
package com.baeldung.dataloading.model;
|
||||||
|
|
||||||
import static javax.persistence.GenerationType.IDENTITY;
|
import static jakarta.persistence.GenerationType.IDENTITY;
|
||||||
|
|
||||||
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.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Country {
|
public class Country {
|
||||||
|
@ -2,7 +2,7 @@ package com.baeldung.springbootcrudapp.application.controllers;
|
|||||||
|
|
||||||
import com.baeldung.springbootcrudapp.application.repositories.UserRepository;
|
import com.baeldung.springbootcrudapp.application.repositories.UserRepository;
|
||||||
import com.baeldung.springbootcrudapp.application.entities.User;
|
import com.baeldung.springbootcrudapp.application.entities.User;
|
||||||
import javax.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.springbootcrudapp.application.entities;
|
package com.baeldung.springbootcrudapp.application.entities;
|
||||||
|
|
||||||
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;
|
||||||
import javax.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class User {
|
public class User {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.springbootdatasourceconfig.application.entities;
|
package com.baeldung.springbootdatasourceconfig.application.entities;
|
||||||
|
|
||||||
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;
|
||||||
import javax.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "users")
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.springboothibernate.application.models;
|
package com.baeldung.springboothibernate.application.models;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Book {
|
public class Book {
|
||||||
|
@ -35,13 +35,13 @@ public class LegacyJpaImplNamingIntegrationTest extends NamingConfig {
|
|||||||
|
|
||||||
String tableNameCreated = table.getName();
|
String tableNameCreated = table.getName();
|
||||||
boolean columnNameIsQuoted = table
|
boolean columnNameIsQuoted = table
|
||||||
.getColumn(3)
|
.getColumn(2)
|
||||||
.isQuoted();
|
.isQuoted();
|
||||||
String physicalNameCreated = table
|
String physicalNameCreated = table
|
||||||
.getColumn(3)
|
.getColumn(2)
|
||||||
.getName();
|
.getName();
|
||||||
String implicitNameCreated = table
|
String implicitNameCreated = table
|
||||||
.getColumn(2)
|
.getColumn(3)
|
||||||
.getName();
|
.getName();
|
||||||
|
|
||||||
SoftAssertions.assertSoftly(softly -> {
|
SoftAssertions.assertSoftly(softly -> {
|
||||||
|
@ -16,10 +16,6 @@ import com.baeldung.boot.naming.entity.Account;
|
|||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@DataJpaTest
|
@DataJpaTest
|
||||||
@TestPropertySource(properties = {
|
|
||||||
"spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy",
|
|
||||||
"spring.jpa.hibernate.naming.implicit-strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
|
|
||||||
})
|
|
||||||
@Import(Config.class)
|
@Import(Config.class)
|
||||||
public class SpringBootDefaultNamingIntegrationTest extends NamingConfig {
|
public class SpringBootDefaultNamingIntegrationTest extends NamingConfig {
|
||||||
|
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.boot.naming;
|
package com.baeldung.boot.naming;
|
||||||
|
|
||||||
import com.baeldung.boot.naming.MetadataExtractorIntegrator;
|
|
||||||
import com.baeldung.boot.naming.NamingConfig.Config;
|
import com.baeldung.boot.naming.NamingConfig.Config;
|
||||||
import com.baeldung.boot.naming.entity.Preference;
|
import com.baeldung.boot.naming.entity.Preference;
|
||||||
|
|
||||||
@ -47,7 +46,7 @@ public class StrategyLegacyHbmImplIntegrationTest extends NamingConfig {
|
|||||||
String implicitNameExpected = "account";
|
String implicitNameExpected = "account";
|
||||||
|
|
||||||
String implicitNameCreated = preferenceTable
|
String implicitNameCreated = preferenceTable
|
||||||
.getColumn(3)
|
.getColumn(1)
|
||||||
.getName();
|
.getName();
|
||||||
String tableNameCreated = accountPreferencesTable.getName();
|
String tableNameCreated = accountPreferencesTable.getName();
|
||||||
|
|
||||||
|
@ -12,7 +12,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
|||||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
import javax.persistence.EntityManagerFactory;
|
import jakarta.persistence.EntityManagerFactory;
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user