diff --git a/javav2/example_code/acm/pom.xml b/javav2/example_code/acm/pom.xml index 89f71eb074e..eed4bb5e784 100644 --- a/javav2/example_code/acm/pom.xml +++ b/javav2/example_code/acm/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import @@ -64,6 +64,10 @@ software.amazon.awssdk secretsmanager + + software.amazon.awssdk + s3 + com.google.code.gson gson diff --git a/javav2/example_code/acm/src/main/java/com/example/acm/ImportCert.java b/javav2/example_code/acm/src/main/java/com/example/acm/ImportCert.java index bb69c094483..8a766f326c7 100644 --- a/javav2/example_code/acm/src/main/java/com/example/acm/ImportCert.java +++ b/javav2/example_code/acm/src/main/java/com/example/acm/ImportCert.java @@ -3,14 +3,19 @@ package com.example.acm; +import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.acm.AcmClient; import software.amazon.awssdk.services.acm.model.ImportCertificateRequest; import software.amazon.awssdk.services.acm.model.ImportCertificateResponse; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.utils.IoUtils; -import java.io.FileInputStream; + +import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.nio.ByteBuffer; // snippet-start:[acm.java2.import_cert.main] @@ -25,58 +30,79 @@ public class ImportCert { public static void main(String[] args) { - final String usage = """ - - Usage: - + Usage: + Where: - certificatePath - the path to the SSL/TLS certificate file. - privateKeyPath - the path to the private key file associated with the SSL/TLS certificate. + bucketName - The name of the S3 bucket containing the certificate and private key. + certificateKey - The object key for the SSL/TLS certificate file in S3. + privateKeyKey - The object key for the private key file in S3. """; - if (args.length != 2) { - System.out.println(usage); - return; - } + //if (args.length != 3) { + // System.out.println(usage); + // return; + // } + + String bucketName = "certbucket100" ; //args[0]; + String certificateKey = "certificate.pem" ; // args[1]; + String privateKeyKey = "private_key.pem" ; //args[2]; - String certificatePath = args[0]; - String privateKeyPath = args[1]; - String certificateArn = importCertificate(certificatePath, privateKeyPath); + String certificateArn = importCertificate(bucketName, certificateKey, privateKeyKey); System.out.println("Certificate imported with ARN: " + certificateArn); } /** - * Imports an SSL/TLS certificate and private key into AWS Certificate Manager (ACM) for use with - * AWS services. + * Imports an SSL/TLS certificate and private key from S3 into AWS Certificate Manager (ACM). * - * @param certificatePath the file path to the SSL/TLS certificate - * @param privateKeyPath the file path to the private key associated with the certificate - * @throws IOException if there is an error reading the certificate or private key files + * @param bucketName The name of the S3 bucket. + * @param certificateKey The key for the SSL/TLS certificate file in S3. + * @param privateKeyKey The key for the private key file in S3. + * @return The ARN of the imported certificate. */ - public static String importCertificate(String certificatePath, String privateKeyPath) { + public static String importCertificate(String bucketName, String certificateKey, String privateKeyKey) { AcmClient acmClient = AcmClient.create(); + S3Client s3Client = S3Client.create(); + try { - byte[] certificateBytes = readFileBytes(certificatePath); - byte[] privateKeyBytes = readFileBytes(privateKeyPath); + byte[] certificateBytes = downloadFileFromS3(s3Client, bucketName, certificateKey); + byte[] privateKeyBytes = downloadFileFromS3(s3Client, bucketName, privateKeyKey); ImportCertificateRequest request = ImportCertificateRequest.builder() - .certificate(SdkBytes.fromByteBuffer(ByteBuffer.wrap(certificateBytes))) - .privateKey(SdkBytes.fromByteBuffer(ByteBuffer.wrap(privateKeyBytes))) - .build(); + .certificate(SdkBytes.fromByteBuffer(ByteBuffer.wrap(certificateBytes))) + .privateKey(SdkBytes.fromByteBuffer(ByteBuffer.wrap(privateKeyBytes))) + .build(); ImportCertificateResponse response = acmClient.importCertificate(request); - String certificateArn = response.certificateArn(); - return certificateArn; + return response.certificateArn(); + } catch (IOException e) { - System.err.println("Error reading certificate or private key file: " + e.getMessage()); + System.err.println("Error downloading certificate or private key from S3: " + e.getMessage()); + } catch (S3Exception e) { + System.err.println("S3 error: " + e.awsErrorDetails().errorMessage()); } return ""; } - private static byte[] readFileBytes(String filePath) throws IOException { - try (InputStream inputStream = new FileInputStream(filePath)) { - return IoUtils.toByteArray(inputStream); + /** + * Downloads a file from Amazon S3 and returns its contents as a byte array. + * + * @param s3Client The S3 client. + * @param bucketName The name of the S3 bucket. + * @param objectKey The key of the object in S3. + * @return The file contents as a byte array. + * @throws IOException If an I/O error occurs. + */ + private static byte[] downloadFileFromS3(S3Client s3Client, String bucketName, String objectKey) throws IOException { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + try (ResponseInputStream s3Object = s3Client.getObject(getObjectRequest); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + IoUtils.copy(s3Object, byteArrayOutputStream); + return byteArrayOutputStream.toByteArray(); } } } diff --git a/javav2/example_code/acm/src/main/resources/log4j2.xml b/javav2/example_code/acm/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/acm/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/acm/src/test/java/ACMTests.java b/javav2/example_code/acm/src/test/java/ACMTests.java index 81437448bdc..6a015cf428e 100644 --- a/javav2/example_code/acm/src/test/java/ACMTests.java +++ b/javav2/example_code/acm/src/test/java/ACMTests.java @@ -9,30 +9,37 @@ import com.example.acm.ListCertTags; import com.example.acm.RemoveTagsFromCert; import com.example.acm.RequestCert; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; +import com.google.gson.Gson; +import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + +import java.io.IOException; + import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertNotNull; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ACMTests { - + private static final Logger logger = LoggerFactory.getLogger(ACMTests.class); private static String certificatePath = ""; private static String privateKeyPath = ""; - + private static String bucketName = ""; private static String certificateArn; @BeforeAll - public static void setUp() { - - certificatePath = "C:\\Users\\scmacdon\\cert_example\\certificate.pem"; - privateKeyPath = "C:\\Users\\scmacdon\\cert_example\\private_key.pem"; + public static void setUp() throws IOException { + Gson gson = new Gson(); + String json = getSecretValues(); + SecretValues values = gson.fromJson(json, SecretValues.class); + certificatePath = values.getCertificatePath(); + privateKeyPath = values.getPrivateKeyPath(); + bucketName = values.getBucketName(); } @Test @@ -40,9 +47,10 @@ public static void setUp() { @Order(1) public void testImportCert() { assertDoesNotThrow(() -> { - certificateArn = ImportCert.importCertificate(certificatePath, privateKeyPath); + certificateArn = ImportCert.importCertificate(bucketName, certificatePath, privateKeyPath); assertNotNull(certificateArn); }); + logger.info("Test 1 passed"); } @Test @@ -52,6 +60,7 @@ public void testAddTags() { assertDoesNotThrow(() -> { AddTagsToCertificate.addTags(certificateArn); }); + logger.info("Test 2 passed"); } @Test @@ -61,42 +70,75 @@ public void testDescribeCert() { assertDoesNotThrow(() -> { DescribeCert.describeCertificate(certificateArn); }); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void testListCertTags() { - assertDoesNotThrow(() -> { - ListCertTags.listCertTags(certificateArn); - }); - } - - @Test - @Tag("IntegrationTest") - @Order(5) public void testRemoveTagsFromCert() { assertDoesNotThrow(() -> { RemoveTagsFromCert.removeTags(certificateArn); }); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") - @Order(6) + @Order(5) public void testRequestCert() { assertDoesNotThrow(() -> { RequestCert.requestCertificate(); }); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") - @Order(7) + @Order(6) public void testDeleteCert() { assertDoesNotThrow(() -> { DeleteCert.deleteCertificate(certificateArn); }); + logger.info("Test 6 passed"); + } + + + private static String getSecretValues() { + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .build(); + String secretName = "test/acm"; + + GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() + .secretId(secretName) + .build(); + + GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); + return valueResponse.secretString(); + } + + @Nested + @DisplayName("A class used to get test values from test/cognito (an AWS Secrets Manager secret)") + class SecretValues { + private String certificatePath; + private String privateKeyPath; + private String bucketName; + + // Getter for certificatePath + public String getCertificatePath() { + return certificatePath; + } + + // Getter for privateKeyPath + public String getPrivateKeyPath() { + return privateKeyPath; + } + + // Getter for bucketName + public String getBucketName() { + return bucketName; + } } } diff --git a/javav2/example_code/apigateway/pom.xml b/javav2/example_code/apigateway/pom.xml index dc7829b5802..4c02b8eb0f4 100644 --- a/javav2/example_code/apigateway/pom.xml +++ b/javav2/example_code/apigateway/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -60,5 +67,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/apigateway/src/main/resources/log4j2.xml b/javav2/example_code/apigateway/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/apigateway/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java b/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java index 16bb2472742..9290af9f29a 100644 --- a/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java +++ b/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java @@ -3,7 +3,8 @@ import com.example.gateway.*; import com.google.gson.Gson; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.apigateway.ApiGatewayClient; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; @@ -21,7 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class APIGatewayTest { - + private static final Logger logger = LoggerFactory.getLogger(APIGatewayTest.class); private static ApiGatewayClient apiGateway; private static String restApiId = ""; private static String resourceId = ""; @@ -45,78 +46,48 @@ public static void setUp() throws IOException { httpMethod = values.getHttpMethod(); restApiName = values.getRestApiName() + randomNum; stageName = values.getStageName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * APIGatewayTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * //load a properties file from class path, inside static method - * prop.load(input); - * - * // Populate the data members required for all tests - * restApiId = prop.getProperty("restApiId"); - * resourceId = prop.getProperty("resourceId"); - * httpMethod = prop.getProperty("httpMethod"); - * restApiName = prop.getProperty("restApiName"); - * stageName = prop.getProperty("stageName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Order(1) - public void CreateRestApi() { + public void testCreateRestApi() { newApiId = CreateRestApi.createAPI(apiGateway, restApiId, restApiName); assertFalse(newApiId.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 1 passed"); } @Test @Order(2) - public void CreateDeployment() { + public void testCreateDeployment() { deploymentId = CreateDeployment.createNewDeployment(apiGateway, newApiId, stageName); assertFalse(deploymentId.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test @Order(3) - public void GetDeployments() { + public void testGetDeployments() { assertDoesNotThrow(() -> GetDeployments.getAllDeployments(apiGateway, newApiId)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test @Order(4) - public void GetStages() { + public void testGetStages() { assertDoesNotThrow(() -> GetStages.getAllStages(apiGateway, newApiId)); - System.out.println("Test 7 passed"); + logger.info("Test 4 passed"); } @Test @Order(5) - public void DeleteRestApi() { + public void testDeleteRestApi() { assertDoesNotThrow(() -> DeleteRestApi.deleteAPI(apiGateway, newApiId)); - System.out.println("Test 9 passed"); + logger.info("Test 5 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/apigateway"; diff --git a/javav2/example_code/appautoscale/pom.xml b/javav2/example_code/appautoscale/pom.xml index 68b192b296f..7db096cbc59 100644 --- a/javav2/example_code/appautoscale/pom.xml +++ b/javav2/example_code/appautoscale/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -68,5 +75,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/appautoscale/src/main/resources/log4j2.xml b/javav2/example_code/appautoscale/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/appautoscale/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/appautoscale/src/test/java/AppAutoTest.java b/javav2/example_code/appautoscale/src/test/java/AppAutoTest.java deleted file mode 100644 index a6517525a00..00000000000 --- a/javav2/example_code/appautoscale/src/test/java/AppAutoTest.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import com.example.appautoscale.DisableDynamoDBAutoscaling; -import com.example.appautoscale.EnableDynamoDBAutoscaling; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient; -import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension; -import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class AppAutoTest { - - private static ApplicationAutoScalingClient appAutoScalingClient; - private static String tableId = "" ; - private static String roleARN = "" ; - private static String policyName = "" ; - - ServiceNamespace ns = ServiceNamespace.DYNAMODB; - ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS; - - @BeforeAll - public static void setUp() throws IOException { - appAutoScalingClient = ApplicationAutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); - - try (InputStream input = AppAutoTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - tableId = prop.getProperty("tableId"); - roleARN = prop.getProperty("roleARN"); - policyName = prop.getProperty("policyName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - @Test - @Tag("IntegrationTest") - @Order(1) - public void testEnableDynamoDBAutoscaling() { - assertDoesNotThrow(() -> EnableDynamoDBAutoscaling.registerScalableTarget(appAutoScalingClient, tableId, roleARN, ns, tableWCUs), - "Failed to register scalable target."); - assertDoesNotThrow(() -> EnableDynamoDBAutoscaling.verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs), - "Verification of scalable target failed."); - assertDoesNotThrow(() -> EnableDynamoDBAutoscaling.configureScalingPolicy(appAutoScalingClient, tableId, ns, tableWCUs, policyName), - "Failed to configure scaling policy."); - System.out.println("\n EnableDynamoDBAutoscaling test passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void testDisableDynamoDBAutoscaling() { - assertDoesNotThrow(() -> DisableDynamoDBAutoscaling.deletePolicy(appAutoScalingClient, policyName, tableWCUs, ns, tableId), - "Failed to delete scaling policy."); - assertDoesNotThrow(() -> DisableDynamoDBAutoscaling.verifyScalingPolicies(appAutoScalingClient, tableId, ns, tableWCUs), - "Verification of scaling policies failed."); - assertDoesNotThrow(() -> DisableDynamoDBAutoscaling.deregisterScalableTarget(appAutoScalingClient, tableId, ns, tableWCUs), - "Failed to deregister scalable target."); - assertDoesNotThrow(() -> DisableDynamoDBAutoscaling.verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs), - "Verification of scalable target after deregistration failed."); - System.out.println("\n DisableDynamoDBAutoscaling test passed"); - } -} diff --git a/javav2/example_code/appsync/pom.xml b/javav2/example_code/appsync/pom.xml index fe71e25a8bf..1c1061a7674 100644 --- a/javav2/example_code/appsync/pom.xml +++ b/javav2/example_code/appsync/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,6 +76,23 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/appsync/src/main/resources/log4j2.xml b/javav2/example_code/appsync/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/appsync/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/appsync/src/test/java/AppSyncTest.java b/javav2/example_code/appsync/src/test/java/AppSyncTest.java index 65fb0e31993..394415ed9dd 100644 --- a/javav2/example_code/appsync/src/test/java/AppSyncTest.java +++ b/javav2/example_code/appsync/src/test/java/AppSyncTest.java @@ -6,6 +6,9 @@ import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.appsync.AppSyncClient; import java.io.*; @@ -21,6 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AppSyncTest { + private static final Logger logger = LoggerFactory.getLogger(AppSyncTest.class); private static AppSyncClient appSyncClient; private static String apiId = ""; private static String dsName = ""; @@ -36,7 +40,6 @@ public static void setUp() throws IOException { reg = region.toString(); appSyncClient = AppSyncClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -47,29 +50,6 @@ public static void setUp() throws IOException { dsName = values.getDsName(); dsRole = values.getDsRole(); tableName = values.getTableName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AppSyncTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * apiId = prop.getProperty("apiId"); - * dsName = prop.getProperty("dsName"); - * dsRole= prop.getProperty("dsRole"); - * tableName= prop.getProperty("tableName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @@ -78,7 +58,7 @@ public static void setUp() throws IOException { public void CreateApiKey() { keyId = CreateApiKey.createKey(appSyncClient, apiId); assertFalse(keyId.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 1 passed"); } @Test @@ -87,7 +67,7 @@ public void CreateApiKey() { public void CreateDataSource() { dsARN = CreateDataSource.createDS(appSyncClient, dsName, reg, dsRole, apiId, tableName); assertFalse(dsARN.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test @@ -95,7 +75,7 @@ public void CreateDataSource() { @Order(3) public void GetDataSource() { assertDoesNotThrow(() -> GetDataSource.getDS(appSyncClient, apiId, dsName)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test @@ -103,7 +83,7 @@ public void GetDataSource() { @Order(4) public void ListGraphqlApis() { assertDoesNotThrow(() -> ListGraphqlApis.getApis(appSyncClient)); - System.out.println("Test 5 passed"); + logger.info("Test 4 passed"); } @Test @@ -111,7 +91,7 @@ public void ListGraphqlApis() { @Order(5) public void ListApiKeys() { assertDoesNotThrow(() -> ListApiKeys.getKeys(appSyncClient, apiId)); - System.out.println("Test 6 passed"); + logger.info("Test 5 passed"); } @Test @@ -119,7 +99,7 @@ public void ListApiKeys() { @Order(6) public void DeleteDataSource() { assertDoesNotThrow(() -> DeleteDataSource.deleteDS(appSyncClient, apiId, dsName)); - System.out.println("Test 7 passed"); + logger.info("Test 6 passed"); } @Test @@ -127,13 +107,12 @@ public void DeleteDataSource() { @Order(7) public void DeleteApiKey() { assertDoesNotThrow(() -> DeleteApiKey.deleteKey(appSyncClient, keyId, apiId)); - System.out.println("Test 8 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/appsync"; diff --git a/javav2/example_code/athena/pom.xml b/javav2/example_code/athena/pom.xml index d471a8e0dd3..d1c01c80529 100644 --- a/javav2/example_code/athena/pom.xml +++ b/javav2/example_code/athena/pom.xml @@ -7,9 +7,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -25,7 +25,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -50,5 +57,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/resources/log4j2.xml b/javav2/example_code/athena/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/athena/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java b/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java index 46404858d48..33511e28932 100644 --- a/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java +++ b/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java @@ -3,6 +3,8 @@ import aws.example.athena.*; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; @@ -15,7 +17,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonAthenaTest { - + private static final Logger logger = LoggerFactory.getLogger(AmazonAthenaTest.class); private static AthenaClient athenaClient; private static String nameQuery; @@ -23,7 +25,6 @@ public class AmazonAthenaTest { public static void setUp() throws IOException { athenaClient = AthenaClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(ProfileCredentialsProvider.create()) .build(); try (InputStream input = AmazonAthenaTest.class.getClassLoader().getResourceAsStream("config.properties")) { @@ -49,49 +50,49 @@ public static void setUp() throws IOException { @Test @Order(1) - public void CreateNamedQueryExample() { + public void testCreateNamedQueryExample() { assertDoesNotThrow(() -> CreateNamedQueryExample.createNamedQuery(athenaClient, nameQuery)); - System.out.println("Test passed"); + logger.info("Test 1 passed"); } @Test @Order(2) - public void ListNamedQueryExample() { + public void testListNamedQueryExample() { assertDoesNotThrow(() -> ListNamedQueryExample.listNamedQueries(athenaClient)); - System.out.println("Test passed"); + logger.info("Test 2 passed"); } @Test @Order(3) - public void ListQueryExecutionsExample() { + public void testListQueryExecutionsExample() { assertDoesNotThrow(() -> ListQueryExecutionsExample.listQueryIds(athenaClient)); - System.out.println("Test passed"); + logger.info("Test 3 passed"); } @Test @Order(4) - public void DeleteNamedQueryExample() { + public void testDeleteNamedQueryExample() { String sampleNamedQueryId = DeleteNamedQueryExample.getNamedQueryId(athenaClient, nameQuery); assertDoesNotThrow(() -> DeleteNamedQueryExample.deleteQueryName(athenaClient, sampleNamedQueryId)); - System.out.println("Test passed"); + logger.info("Test 4 passed"); } @Test @Order(5) - public void StartQueryExample() { + public void testStartQueryExample() { String queryExecutionId = StartQueryExample.submitAthenaQuery(athenaClient); assertDoesNotThrow(() -> StartQueryExample.waitForQueryToComplete(athenaClient, queryExecutionId)); assertDoesNotThrow(() -> StartQueryExample.processResultRows(athenaClient, queryExecutionId)); - System.out.println("Test passed"); + logger.info("Test 5 passed"); } @Test @Order(6) - public void StopQueryExecutionExample() { + public void testStopQueryExecutionExample() { String sampleQueryExecutionId = StopQueryExecutionExample.submitAthenaQuery(athenaClient); assertDoesNotThrow(() -> StopQueryExecutionExample.stopAthenaQuery(athenaClient, sampleQueryExecutionId)); - System.out.println("Test passed"); + logger.info("Test 6 passed"); } } diff --git a/javav2/example_code/autoscale/pom.xml b/javav2/example_code/autoscale/pom.xml index 6a2dcbf9074..4697cbbe0a1 100644 --- a/javav2/example_code/autoscale/pom.xml +++ b/javav2/example_code/autoscale/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -52,6 +59,10 @@ software.amazon.awssdk autoscaling + + software.amazon.awssdk + ec2 + software.amazon.awssdk auth @@ -64,5 +75,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/scenario/AutoScalingScenario.java similarity index 96% rename from javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java rename to javav2/example_code/autoscale/src/main/java/com/example/autoscaling/scenario/AutoScalingScenario.java index c4c2f98c3c6..14b7ca01af3 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/scenario/AutoScalingScenario.java @@ -1,451 +1,458 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.autoscaling; - -// snippet-start:[autoscale.java2.create_scaling_scenario.import] -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.autoscaling.AutoScalingClient; -import software.amazon.awssdk.services.autoscaling.model.Activity; -import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; -import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup; -import software.amazon.awssdk.services.autoscaling.model.AutoScalingInstanceDetails; -import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest; -import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest; -import software.amazon.awssdk.services.autoscaling.model.DescribeAccountLimitsResponse; -import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; -import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; -import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingInstancesResponse; -import software.amazon.awssdk.services.autoscaling.model.DescribeScalingActivitiesRequest; -import software.amazon.awssdk.services.autoscaling.model.DescribeScalingActivitiesResponse; -import software.amazon.awssdk.services.autoscaling.model.DisableMetricsCollectionRequest; -import software.amazon.awssdk.services.autoscaling.model.EnableMetricsCollectionRequest; -import software.amazon.awssdk.services.autoscaling.model.Instance; -import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification; -import software.amazon.awssdk.services.autoscaling.model.SetDesiredCapacityRequest; -import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter; -import software.amazon.awssdk.services.autoscaling.model.UpdateAutoScalingGroupRequest; -import software.amazon.awssdk.services.autoscaling.model.TerminateInstanceInAutoScalingGroupRequest; -import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingInstancesRequest; -import java.util.List; -// snippet-end:[autoscale.java2.create_scaling_scenario.import] - -// snippet-start:[autoscale.java2.create_scaling_scenario.main] -/** - * Before running this SDK for Java (v2) code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - * In addition, create a launch template. For more information, see the - * following topic: - * - * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template - * - * This code example performs the following operations: - * 1. Creates an Auto Scaling group using an AutoScalingWaiter. - * 2. Gets a specific Auto Scaling group and returns an instance Id value. - * 3. Describes Auto Scaling with the Id value. - * 4. Enables metrics collection. - * 5. Update an Auto Scaling group. - * 6. Describes Account details. - * 7. Describe account details" - * 8. Updates an Auto Scaling group to use an additional instance. - * 9. Gets the specific Auto Scaling group and gets the number of instances. - * 10. List the scaling activities that have occurred for the group. - * 11. Terminates an instance in the Auto Scaling group. - * 12. Stops the metrics collection. - * 13. Deletes the Auto Scaling group. - */ - -public class AutoScalingScenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - - public static void main(String[] args) throws InterruptedException { - final String usage = """ - - Usage: - - - Where: - groupName - The name of the Auto Scaling group. - launchTemplateName - The name of the launch template.\s - vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String groupName = args[0]; - String launchTemplateName = args[1]; - String vpcZoneId = args[2]; - AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); - - System.out.println(DASHES); - System.out.println("Welcome to the Amazon EC2 Auto Scaling example scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("1. Create an Auto Scaling group named " + groupName); - createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); - System.out.println( - "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); - Thread.sleep(60000); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("2. Get Auto Scale group Id value"); - String instanceId = getSpecificAutoScalingGroups(autoScalingClient, groupName); - if (instanceId.compareTo("") == 0) { - System.out.println("Error - no instance Id value"); - System.exit(1); - } else { - System.out.println("The instance Id value is " + instanceId); - } - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. Describe Auto Scaling with the Id value " + instanceId); - describeAutoScalingInstance(autoScalingClient, instanceId); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Enable metrics collection " + instanceId); - enableMetricsCollection(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("5. Update an Auto Scaling group to update max size to 3"); - updateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("6. Describe Auto Scaling groups"); - describeAutoScalingGroups(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("7. Describe account details"); - describeAccountLimits(autoScalingClient); - System.out.println( - "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); - Thread.sleep(60000); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("8. Set desired capacity to 2"); - setDesiredCapacity(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("9. Get the two instance Id values and state"); - getSpecificAutoScalingGroups(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("10. List the scaling activities that have occurred for the group"); - describeScalingActivities(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("11. Terminate an instance in the Auto Scaling group"); - terminateInstanceInAutoScalingGroup(autoScalingClient, instanceId); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("12. Stop the metrics collection"); - disableMetricsCollection(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("13. Delete the Auto Scaling group"); - deleteAutoScalingGroup(autoScalingClient, groupName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("The Scenario has successfully completed."); - System.out.println(DASHES); - - autoScalingClient.close(); - } - - // snippet-start:[autoscale.java2.describe_scaling_activites.main] - public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) { - try { - DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder() - .autoScalingGroupName(groupName) - .maxRecords(10) - .build(); - - DescribeScalingActivitiesResponse response = autoScalingClient - .describeScalingActivities(scalingActivitiesRequest); - List activities = response.activities(); - for (Activity activity : activities) { - System.out.println("The activity Id is " + activity.activityId()); - System.out.println("The activity details are " + activity.details()); - } - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.describe_scaling_activites.main] - - // snippet-start:[autoscale.java2.set_capacity.main] - public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) { - try { - SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder() - .autoScalingGroupName(groupName) - .desiredCapacity(2) - .build(); - - autoScalingClient.setDesiredCapacity(capacityRequest); - System.out.println("You have set the DesiredCapacity to 2"); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.set_capacity.main] - - // snippet-start:[autoscale.java2.create_autoscalinggroup.main] - public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, - String groupName, - String launchTemplateName, - String vpcZoneId) { - try { - AutoScalingWaiter waiter = autoScalingClient.waiter(); - LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() - .launchTemplateName(launchTemplateName) - .build(); - - CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .availabilityZones("us-east-1a") - .launchTemplate(templateSpecification) - .maxSize(1) - .minSize(1) - .vpcZoneIdentifier(vpcZoneId) - .build(); - - autoScalingClient.createAutoScalingGroup(request); - DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); - - WaiterResponse waiterResponse = waiter - .waitUntilGroupExists(groupsRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("Auto Scaling Group created"); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.create_autoscalinggroup.main] - - // snippet-start:[autoscale.java2.describe_autoscalinggroup.main] - public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) { - try { - DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest - .builder() - .instanceIds(id) - .build(); - - DescribeAutoScalingInstancesResponse response = autoScalingClient - .describeAutoScalingInstances(describeAutoScalingInstancesRequest); - List instances = response.autoScalingInstances(); - for (AutoScalingInstanceDetails instance : instances) { - System.out.println("The instance lifecycle state is: " + instance.lifecycleState()); - } - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.describe_autoscalinggroup.main] - - // snippet-start:[autoscale.java2.describe_autoscalinggroups.main] - public static void describeAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { - try { - DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .maxRecords(10) - .build(); - - DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(groupsRequest); - List groups = response.autoScalingGroups(); - for (AutoScalingGroup group : groups) { - System.out.println("*** The service to use for the health checks: " + group.healthCheckType()); - } - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.describe_autoscalinggroups.main] - - // snippet-start:[autoscale.java2.get_autoscalinggroup.main] - public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { - try { - String instanceId = ""; - DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); - - DescribeAutoScalingGroupsResponse response = autoScalingClient - .describeAutoScalingGroups(scalingGroupsRequest); - List groups = response.autoScalingGroups(); - for (AutoScalingGroup group : groups) { - System.out.println("The group name is " + group.autoScalingGroupName()); - System.out.println("The group ARN is " + group.autoScalingGroupARN()); - List instances = group.instances(); - - for (Instance instance : instances) { - instanceId = instance.instanceId(); - System.out.println("The instance id is " + instanceId); - System.out.println("The lifecycle state is " + instance.lifecycleState()); - } - } - - return instanceId; - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return ""; - } - // snippet-end:[autoscale.java2.get_autoscalinggroup.main] - - // snippet-start:[autoscale.java2.enable_collection.main] - public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { - try { - EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder() - .autoScalingGroupName(groupName) - .metrics("GroupMaxSize") - .granularity("1Minute") - .build(); - - autoScalingClient.enableMetricsCollection(collectionRequest); - System.out.println("The enable metrics collection operation was successful"); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.enable_collection.main] - - // snippet-start:[autoscale.java2.disable_collection.main] - public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { - try { - DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder() - .autoScalingGroupName(groupName) - .metrics("GroupMaxSize") - .build(); - - autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest); - System.out.println("The disable metrics collection operation was successful"); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.disable_collection.main] - - // snippet-start:[autoscale.java2.describe_account.main] - public static void describeAccountLimits(AutoScalingClient autoScalingClient) { - try { - DescribeAccountLimitsResponse response = autoScalingClient.describeAccountLimits(); - System.out.println("The max number of auto scaling groups is " + response.maxNumberOfAutoScalingGroups()); - System.out.println("The current number of auto scaling groups is " + response.numberOfAutoScalingGroups()); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.describe_account.main] - - // snippet-start:[autoscale.java2.update_autoscalinggroup.main] - public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, - String launchTemplateName) { - try { - AutoScalingWaiter waiter = autoScalingClient.waiter(); - LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() - .launchTemplateName(launchTemplateName) - .build(); - - UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder() - .maxSize(3) - .autoScalingGroupName(groupName) - .launchTemplate(templateSpecification) - .build(); - - autoScalingClient.updateAutoScalingGroup(groupRequest); - DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); - - WaiterResponse waiterResponse = waiter - .waitUntilGroupInService(groupsRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("You successfully updated the auto scaling group " + groupName); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.update_autoscalinggroup.main] - - // snippet-start:[autoscale.java2.terminate_instance.main] - public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) { - try { - TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder() - .instanceId(instanceId) - .shouldDecrementDesiredCapacity(false) - .build(); - - autoScalingClient.terminateInstanceInAutoScalingGroup(request); - System.out.println("You have terminated instance " + instanceId); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.terminate_instance.main] - - // snippet-start:[autoscale.java2.del_group.main] - public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { - try { - DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .forceDelete(true) - .build(); - - autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); - System.out.println("You successfully deleted " + groupName); - - } catch (AutoScalingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[autoscale.java2.del_group.main] -} -// snippet-end:[autoscale.java2.create_scaling_scenario.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.autoscaling.scenario; + +// snippet-start:[autoscale.java2.create_scaling_scenario.import] +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.autoscaling.AutoScalingClient; +import software.amazon.awssdk.services.autoscaling.model.Activity; +import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; +import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup; +import software.amazon.awssdk.services.autoscaling.model.AutoScalingInstanceDetails; +import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest; +import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest; +import software.amazon.awssdk.services.autoscaling.model.DescribeAccountLimitsResponse; +import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; +import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; +import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingInstancesResponse; +import software.amazon.awssdk.services.autoscaling.model.DescribeScalingActivitiesRequest; +import software.amazon.awssdk.services.autoscaling.model.DescribeScalingActivitiesResponse; +import software.amazon.awssdk.services.autoscaling.model.DisableMetricsCollectionRequest; +import software.amazon.awssdk.services.autoscaling.model.EnableMetricsCollectionRequest; +import software.amazon.awssdk.services.autoscaling.model.Instance; +import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification; +import software.amazon.awssdk.services.autoscaling.model.SetDesiredCapacityRequest; +import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter; +import software.amazon.awssdk.services.autoscaling.model.UpdateAutoScalingGroupRequest; +import software.amazon.awssdk.services.autoscaling.model.TerminateInstanceInAutoScalingGroupRequest; +import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingInstancesRequest; +import software.amazon.awssdk.services.ec2.Ec2Client; + +import java.util.List; +// snippet-end:[autoscale.java2.create_scaling_scenario.import] + +// snippet-start:[autoscale.java2.create_scaling_scenario.main] +/** + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * In addition, create a launch template. For more information, see the + * following topic: + * + * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template + * + * This code example performs the following operations: + * 1. Creates an Auto Scaling group using an AutoScalingWaiter. + * 2. Gets a specific Auto Scaling group and returns an instance Id value. + * 3. Describes Auto Scaling with the Id value. + * 4. Enables metrics collection. + * 5. Update an Auto Scaling group. + * 6. Describes Account details. + * 7. Describe account details" + * 8. Updates an Auto Scaling group to use an additional instance. + * 9. Gets the specific Auto Scaling group and gets the number of instances. + * 10. List the scaling activities that have occurred for the group. + * 11. Terminates an instance in the Auto Scaling group. + * 12. Stops the metrics collection. + * 13. Deletes the Auto Scaling group. + */ + +public class AutoScalingScenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + public static void main(String[] args) throws InterruptedException { + final String usage = """ + + Usage: + + + Where: + groupName - The name of the Auto Scaling group. + launchTemplateName - The name of the launch template.\s + vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. + """; + + //if (args.length != 3) { + // System.out.println(usage); + // System.exit(1); + // } + + String groupName = "Scott250" ; //rgs[0]; + String launchTemplateName = "MyTemplate5" ;//args[1]; + String vpcZoneId = "subnet-0ddc451b8a8a1aa44" ; //args[2]; + + AutoScalingClient autoScalingClient = AutoScalingClient.builder() + .region(Region.US_EAST_1) + .build(); + + Ec2Client ec2 = Ec2Client.create(); + + System.out.println(DASHES); + System.out.println("Welcome to the Amazon EC2 Auto Scaling example scenario."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("1. Create an Auto Scaling group named " + groupName); + createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + Thread.sleep(60000); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("2. Get Auto Scale group Id value"); + String instanceId = getSpecificAutoScalingGroups(autoScalingClient, groupName); + if (instanceId.compareTo("") == 0) { + System.out.println("Error - no instance Id value"); + System.exit(1); + } else { + System.out.println("The instance Id value is " + instanceId); + } + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. Describe Auto Scaling with the Id value " + instanceId); + describeAutoScalingInstance(autoScalingClient, instanceId); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Enable metrics collection " + instanceId); + enableMetricsCollection(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("5. Update an Auto Scaling group to update max size to 3"); + updateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("6. Describe Auto Scaling groups"); + describeAutoScalingGroups(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("7. Describe account details"); + describeAccountLimits(autoScalingClient); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + Thread.sleep(60000); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("8. Set desired capacity to 2"); + setDesiredCapacity(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("9. Get the two instance Id values and state"); + getSpecificAutoScalingGroups(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("10. List the scaling activities that have occurred for the group"); + describeScalingActivities(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("11. Terminate an instance in the Auto Scaling group"); + terminateInstanceInAutoScalingGroup(autoScalingClient, instanceId); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("12. Stop the metrics collection"); + disableMetricsCollection(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("13. Delete the Auto Scaling group"); + deleteAutoScalingGroup(autoScalingClient, groupName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("The Scenario has successfully completed."); + System.out.println(DASHES); + + autoScalingClient.close(); + } + + + + // snippet-start:[autoscale.java2.describe_scaling_activites.main] + public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) { + try { + DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder() + .autoScalingGroupName(groupName) + .maxRecords(10) + .build(); + + DescribeScalingActivitiesResponse response = autoScalingClient + .describeScalingActivities(scalingActivitiesRequest); + List activities = response.activities(); + for (Activity activity : activities) { + System.out.println("The activity Id is " + activity.activityId()); + System.out.println("The activity details are " + activity.details()); + } + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.describe_scaling_activites.main] + + // snippet-start:[autoscale.java2.set_capacity.main] + public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) { + try { + SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder() + .autoScalingGroupName(groupName) + .desiredCapacity(2) + .build(); + + autoScalingClient.setDesiredCapacity(capacityRequest); + System.out.println("You have set the DesiredCapacity to 2"); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.set_capacity.main] + + // snippet-start:[autoscale.java2.create_autoscalinggroup.main] + public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, + String groupName, + String launchTemplateName, + String vpcZoneId) { + try { + AutoScalingWaiter waiter = autoScalingClient.waiter(); + LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() + .launchTemplateName(launchTemplateName) + .build(); + + CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() + .autoScalingGroupName(groupName) + .availabilityZones("us-east-1a") + .launchTemplate(templateSpecification) + .maxSize(1) + .minSize(1) + .vpcZoneIdentifier(vpcZoneId) + .build(); + + autoScalingClient.createAutoScalingGroup(request); + DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() + .autoScalingGroupNames(groupName) + .build(); + + WaiterResponse waiterResponse = waiter + .waitUntilGroupExists(groupsRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println("Auto Scaling Group created"); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.create_autoscalinggroup.main] + + // snippet-start:[autoscale.java2.describe_autoscalinggroup.main] + public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) { + try { + DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest + .builder() + .instanceIds(id) + .build(); + + DescribeAutoScalingInstancesResponse response = autoScalingClient + .describeAutoScalingInstances(describeAutoScalingInstancesRequest); + List instances = response.autoScalingInstances(); + for (AutoScalingInstanceDetails instance : instances) { + System.out.println("The instance lifecycle state is: " + instance.lifecycleState()); + } + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.describe_autoscalinggroup.main] + + // snippet-start:[autoscale.java2.describe_autoscalinggroups.main] + public static void describeAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { + try { + DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() + .autoScalingGroupNames(groupName) + .maxRecords(10) + .build(); + + DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(groupsRequest); + List groups = response.autoScalingGroups(); + for (AutoScalingGroup group : groups) { + System.out.println("*** The service to use for the health checks: " + group.healthCheckType()); + } + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.describe_autoscalinggroups.main] + + // snippet-start:[autoscale.java2.get_autoscalinggroup.main] + public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { + try { + String instanceId = ""; + DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder() + .autoScalingGroupNames(groupName) + .build(); + + DescribeAutoScalingGroupsResponse response = autoScalingClient + .describeAutoScalingGroups(scalingGroupsRequest); + List groups = response.autoScalingGroups(); + for (AutoScalingGroup group : groups) { + System.out.println("The group name is " + group.autoScalingGroupName()); + System.out.println("The group ARN is " + group.autoScalingGroupARN()); + List instances = group.instances(); + + for (Instance instance : instances) { + instanceId = instance.instanceId(); + System.out.println("The instance id is " + instanceId); + System.out.println("The lifecycle state is " + instance.lifecycleState()); + } + } + + return instanceId; + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } + // snippet-end:[autoscale.java2.get_autoscalinggroup.main] + + // snippet-start:[autoscale.java2.enable_collection.main] + public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { + try { + EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder() + .autoScalingGroupName(groupName) + .metrics("GroupMaxSize") + .granularity("1Minute") + .build(); + + autoScalingClient.enableMetricsCollection(collectionRequest); + System.out.println("The enable metrics collection operation was successful"); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.enable_collection.main] + + // snippet-start:[autoscale.java2.disable_collection.main] + public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { + try { + DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder() + .autoScalingGroupName(groupName) + .metrics("GroupMaxSize") + .build(); + + autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest); + System.out.println("The disable metrics collection operation was successful"); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.disable_collection.main] + + // snippet-start:[autoscale.java2.describe_account.main] + public static void describeAccountLimits(AutoScalingClient autoScalingClient) { + try { + DescribeAccountLimitsResponse response = autoScalingClient.describeAccountLimits(); + System.out.println("The max number of auto scaling groups is " + response.maxNumberOfAutoScalingGroups()); + System.out.println("The current number of auto scaling groups is " + response.numberOfAutoScalingGroups()); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.describe_account.main] + + // snippet-start:[autoscale.java2.update_autoscalinggroup.main] + public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, + String launchTemplateName) { + try { + AutoScalingWaiter waiter = autoScalingClient.waiter(); + LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() + .launchTemplateName(launchTemplateName) + .build(); + + UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder() + .maxSize(3) + .autoScalingGroupName(groupName) + .launchTemplate(templateSpecification) + .build(); + + autoScalingClient.updateAutoScalingGroup(groupRequest); + DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() + .autoScalingGroupNames(groupName) + .build(); + + WaiterResponse waiterResponse = waiter + .waitUntilGroupInService(groupsRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println("You successfully updated the auto scaling group " + groupName); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.update_autoscalinggroup.main] + + // snippet-start:[autoscale.java2.terminate_instance.main] + public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) { + try { + TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder() + .instanceId(instanceId) + .shouldDecrementDesiredCapacity(false) + .build(); + + autoScalingClient.terminateInstanceInAutoScalingGroup(request); + System.out.println("You have terminated instance " + instanceId); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.terminate_instance.main] + + // snippet-start:[autoscale.java2.del_group.main] + public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { + try { + DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() + .autoScalingGroupName(groupName) + .forceDelete(true) + .build(); + + autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); + System.out.println("You successfully deleted " + groupName); + + } catch (AutoScalingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[autoscale.java2.del_group.main] +} +// snippet-end:[autoscale.java2.create_scaling_scenario.main] diff --git a/javav2/example_code/autoscale/src/main/resources/log4j2.xml b/javav2/example_code/autoscale/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/autoscale/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java b/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java index a4192a8724a..9d7b174a733 100644 --- a/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java +++ b/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java @@ -3,24 +3,21 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; -import com.example.autoscaling.AutoScalingScenario; + +import com.example.autoscaling.scenario.AutoScalingScenario; import com.example.autoscaling.CreateAutoScalingGroup; import com.example.autoscaling.DeleteAutoScalingGroup; import com.example.autoscaling.DescribeAutoScalingInstances; import com.example.autoscaling.DetachInstances; import com.google.gson.Gson; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.autoscaling.AutoScalingClient; + import java.io.IOException; import java.util.Random; + import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; @@ -33,6 +30,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AutoScaleTest { + private static final Logger logger = LoggerFactory.getLogger(AutoScaleTest.class); private static AutoScalingClient autoScalingClient; private static String groupName = ""; private static String groupNameSc = ""; @@ -45,7 +43,6 @@ public class AutoScaleTest { public static void setUp() throws IOException { autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Random random = new Random(); @@ -58,68 +55,11 @@ public static void setUp() throws IOException { launchTemplateName = myValues.getLaunchTemplateName(); vpcZoneId = myValues.getVpcZoneId(); groupNameSc = myValues.getGroupNameSc() + randomNum; - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for the tests. - /* - * try (InputStream input = - * AutoScaleTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * groupName = prop.getProperty("groupName")+randomNum; - * launchTemplateName = prop.getProperty("launchTemplateName"); - * vpcZoneId = prop.getProperty("vpcZoneId"); - * groupNameSc = prop.getProperty("groupNameSc")+randomNum; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test + @Tag("IntegrationTest") @Order(1) - public void createAutoScalingGroup() { - assertDoesNotThrow(() -> CreateAutoScalingGroup.createAutoScalingGroup(autoScalingClient, groupName, - launchTemplateName, vpcZoneId)); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) - public void describeAutoScalingInstances() throws InterruptedException { - System.out.println("Wait 1 min for the resources"); - Thread.sleep(60000); - instanceId2 = DescribeAutoScalingInstances.getAutoScaling(autoScalingClient, groupName); - assertFalse(instanceId2.isEmpty()); - System.out.println(instanceId2); - System.out.println("Test 2 passed"); - } - - @Test - @Order(3) - public void detachInstances() throws InterruptedException { - System.out.println("Wait 1 min for the resources, including the instance"); - Thread.sleep(60000); - assertDoesNotThrow(() -> DetachInstances.detachInstance(autoScalingClient, groupName, instanceId2)); - System.out.println("Test 3 passed"); - } - - @Test - @Order(4) - public void deleteAutoScalingGroup() { - assertDoesNotThrow(() -> DeleteAutoScalingGroup.deleteAutoScalingGroup(autoScalingClient, groupName)); - System.out.println("Test 4 passed"); - } - - @Test - @Order(5) public void autoScalingScenario() throws InterruptedException { System.out.println("**** Create an Auto Scaling group named " + groupName); AutoScalingScenario.createAutoScalingGroup(autoScalingClient, groupNameSc, launchTemplateName, vpcZoneId); @@ -168,12 +108,12 @@ public void autoScalingScenario() throws InterruptedException { System.out.println("**** Delete the Auto Scaling group"); AutoScalingScenario.deleteAutoScalingGroup(autoScalingClient, groupNameSc); + logger.info("Test 1 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/autoscale"; diff --git a/javav2/example_code/batch/pom.xml b/javav2/example_code/batch/pom.xml index 9cef1e386d2..51d4217d04f 100644 --- a/javav2/example_code/batch/pom.xml +++ b/javav2/example_code/batch/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/batch/src/test/java/BatchTest.java b/javav2/example_code/batch/src/test/java/BatchTest.java index 30d6c0536f3..b01c571e051 100644 --- a/javav2/example_code/batch/src/test/java/BatchTest.java +++ b/javav2/example_code/batch/src/test/java/BatchTest.java @@ -12,6 +12,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentResponse; @@ -23,13 +25,16 @@ import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ThreadLocalRandom; + import static org.junit.jupiter.api.Assertions.assertNotNull; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class BatchTest { + private static final Logger logger = LoggerFactory.getLogger(BatchTest.class); private static String computeEnvironmentName = "my-compute-environment" ; - private static String jobQueueName = "my-job-queue"; + private static String jobQueueName = "my-job-queue12"; private static String jobDefinitionName = "my-job-definition"; private static String dockerImage = "dkr.ecr.us-east-1.amazonaws.com/echo-text:echo-text"; private static String subnet = "" ; @@ -56,6 +61,8 @@ public static void setUp() { dockerImage = accId[0]+"."+dockerImage; + int randomValue = ThreadLocalRandom.current().nextInt(1, 1001); + computeEnvironmentName += randomValue; // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); @@ -73,7 +80,7 @@ public void testCreateComputeEnvironment() { CompletableFuture future = batchActions.createComputeEnvironmentAsync(computeEnvironmentName, batchIAMRole, subnet, secGroup); CreateComputeEnvironmentResponse response = future.join(); System.out.println("Compute Environment ARN: " + response.computeEnvironmentArn()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @@ -88,7 +95,7 @@ public void testGetStatus() { CompletableFuture future = batchActions.checkComputeEnvironmentsStatus(computeEnvironmentName); String status = future.join(); System.out.println("Compute Environment Status: " + status); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @@ -99,7 +106,7 @@ public void testCreateJobQueue() { jobQueueArn = jobQueueFuture.join(); assertNotNull(jobQueueArn, "Job Queue ARN should not be null"); System.out.println("Job Queue ARN: " + jobQueueArn); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @@ -109,7 +116,7 @@ public void testRegisterJobDefinition() { jobARN = batchActions.registerJobDefinitionAsync(jobDefinitionName, executionRoleARN, dockerImage, "X86_64").join(); assertNotNull(jobARN, "Job ARN should not be null"); System.out.println("Job ARN: " + jobARN); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @@ -124,7 +131,7 @@ public void testSubmitJob() { } jobId = batchActions.submitJobAsync(jobDefinitionName, jobQueueName, jobARN).join(); System.out.println("Job Id: " + jobId); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @@ -136,7 +143,7 @@ public void testGetJobs() { System.out.printf("Job ID: %s, Job Name: %s, Job Status: %s%n", job.jobId(), job.jobName(), job.status()) ); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @@ -146,21 +153,21 @@ public void testJobStatus() { CompletableFuture future = batchActions.describeJobAsync(jobId); String jobStatus = future.join(); System.out.println("Job Status: " + jobStatus); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") - @Order(7) + @Order(8) public void testRegisterJobQueue() { batchActions.deregisterJobDefinitionAsync(jobARN); batchActions.disableJobQueueAsync(jobQueueArn); - System.out.println("Test 7 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") - @Order(8) + @Order(9) public void testDeleteJobQueue() { try { Thread.sleep(120_000); @@ -169,12 +176,12 @@ public void testDeleteJobQueue() { } batchActions.deleteJobQueueAsync(jobQueueArn); - System.out.println("Test 8 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") - @Order(9) + @Order(10) public void testDisableComputeEnvironment() { try { Thread.sleep(120_000); @@ -187,12 +194,13 @@ public void testDisableComputeEnvironment() { } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") - @Order(10) + @Order(11) public void testDeleteComputeEnvironment() { try { Thread.sleep(120_000); @@ -200,13 +208,12 @@ public void testDeleteComputeEnvironment() { Thread.currentThread().interrupt(); } batchActions.deleteComputeEnvironmentAsync(computeEnvironmentName); - System.out.println("Test 10 passed"); + logger.info("Test 11 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/batch"; diff --git a/javav2/example_code/cloudformation/pom.xml b/javav2/example_code/cloudformation/pom.xml index c59d464cb72..cff6a9bb1ea 100644 --- a/javav2/example_code/cloudformation/pom.xml +++ b/javav2/example_code/cloudformation/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/cloudformation/src/main/resources/log4j2.xml b/javav2/example_code/cloudformation/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/cloudformation/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java b/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java index 6ba0deb59d1..7307798f682 100644 --- a/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java +++ b/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java @@ -3,6 +3,8 @@ import com.example.cloudformation.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; import software.amazon.awssdk.regions.Region; @@ -19,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudFormationTest { + private static final Logger logger = LoggerFactory.getLogger(CloudFormationTest.class); private static CloudFormationClient cfClient; private static String stackName = ""; private static String roleARN = ""; @@ -30,7 +33,6 @@ public class CloudFormationTest { public static void setUp() { cfClient = CloudFormationClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -42,69 +44,43 @@ public static void setUp() { location = values.getLocation(); key = values.getKey(); value = values.getValue(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * CloudFormationTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * stackName = prop.getProperty("stackName"); - * roleARN = prop.getProperty("roleARN"); - * location = prop.getProperty("location"); - * key = prop.getProperty("key"); - * value = prop.getProperty("value"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateStack() { + public void testCreateStack() { assertDoesNotThrow(() -> CreateStack.createCFStack(cfClient, stackName, roleARN, location)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeStacks() { + public void testDescribeStacks() { assertDoesNotThrow(() -> DescribeStacks.describeAllStacks(cfClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetTemplate() { + public void testGetTemplate() { assertDoesNotThrow(() -> GetTemplate.getSpecificTemplate(cfClient, stackName)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DeleteStack() { + public void testDeleteStack() { assertDoesNotThrow(() -> DeleteStack.deleteSpecificTemplate(cfClient, stackName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/cloudformation"; diff --git a/javav2/example_code/cloudfront/pom.xml b/javav2/example_code/cloudfront/pom.xml index 03e4f20af6a..8e4cc9a1e79 100644 --- a/javav2/example_code/cloudfront/pom.xml +++ b/javav2/example_code/cloudfront/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,14 +35,14 @@ software.amazon.awssdk bom - 2.30.31 + 2.31.8 pom import org.apache.logging.log4j log4j-bom - 2.19.0 + 2.23.1 pom import diff --git a/javav2/example_code/cloudfront/src/main/resources/log4j2.xml b/javav2/example_code/cloudfront/src/main/resources/log4j2.xml index 7d6d9003cdf..914470047e7 100644 --- a/javav2/example_code/cloudfront/src/main/resources/log4j2.xml +++ b/javav2/example_code/cloudfront/src/main/resources/log4j2.xml @@ -1,17 +1,17 @@ - + + + + - - - + + + + - - - - \ No newline at end of file diff --git a/javav2/example_code/cloudfront/src/test/java/CloudFrontSigningTest.java b/javav2/example_code/cloudfront/src/test/java/CloudFrontSigningTest.java index 00cd1667364..c0f8f2e2bd6 100644 --- a/javav2/example_code/cloudfront/src/test/java/CloudFrontSigningTest.java +++ b/javav2/example_code/cloudfront/src/test/java/CloudFrontSigningTest.java @@ -58,12 +58,11 @@ static void setUp() throws IOException { // Run tests on Real AWS resources. cloudFrontClient = CloudFrontClient.builder() .region(Region.AWS_GLOBAL) - .credentialsProvider(ProfileCredentialsProvider.create()) .build(); + s3Client = S3Client.builder() .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .build(); try (InputStream input = CloudFrontSigningTest.class.getClassLoader().getResourceAsStream("config.properties")) { Properties prop = new Properties(); diff --git a/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java b/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java index 5b4f96563c4..8bb70e18ceb 100644 --- a/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java +++ b/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java @@ -13,6 +13,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; @@ -22,13 +24,12 @@ import java.util.Properties; import java.util.UUID; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudFrontTest { - + private static final Logger logger = LoggerFactory.getLogger(CloudFrontTest.class); private static CloudFrontClient cloudFrontClient ; private static Region region; private static String functionName = ""; @@ -45,7 +46,6 @@ public static void setUp() throws IOException { region = Region.AWS_GLOBAL; cloudFrontClient = CloudFrontClient.builder() .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) .build(); try (InputStream input = CloudFrontTest.class.getClassLoader().getResourceAsStream("config.properties")) { @@ -74,7 +74,7 @@ public void CreateFunction() { functionName = "FunctionUploadedByJava" + UUID.randomUUID(); funcARN = CreateFunction.createNewFunction(cloudFrontClient, functionName, functionFileName); assertTrue(!funcARN.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 1 passed"); } @Test @@ -82,28 +82,34 @@ public void CreateFunction() { public void DescribeFunction() { eTagVal = DescribeFunction.describeFunction(cloudFrontClient, functionName); assertTrue(!eTagVal.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test @Order(3) - public void ListFunctions(){ - ListFunctions.listAllFunctions(cloudFrontClient); - System.out.println("Test 4 passed"); + public void testListFunctions(){ + assertDoesNotThrow(() -> { + ListFunctions.listAllFunctions(cloudFrontClient); + }); + logger.info("Test 3 passed"); } @Test @Order(4) - public void GetDistribution() { - GetDistributions.getCFDistributions(cloudFrontClient); - System.out.println("Test 5 passed"); + public void testGetDistribution() { + assertDoesNotThrow(() -> { + GetDistributions.getCFDistributions(cloudFrontClient); + }); + logger.info("Test 4 passed"); } @Test @Order(5) - public void DeleteFunction(){ - DeleteFunction.deleteSpecificFunction(cloudFrontClient, functionName, eTagVal); - System.out.println("Test 7 passed"); + public void testDeleteFunction(){ + assertDoesNotThrow(() -> { + DeleteFunction.deleteSpecificFunction(cloudFrontClient, functionName, eTagVal); + }); + logger.info("Test 5 passed"); } } diff --git a/javav2/example_code/cloudtrail/pom.xml b/javav2/example_code/cloudtrail/pom.xml index 39ce3c4f893..8448a8ab106 100644 --- a/javav2/example_code/cloudtrail/pom.xml +++ b/javav2/example_code/cloudtrail/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/cloudtrail/src/main/resources/log4j2.xml b/javav2/example_code/cloudtrail/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/cloudtrail/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java b/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java index b46a3d19355..e489b19f228 100644 --- a/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java +++ b/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java @@ -3,6 +3,8 @@ import com.example.cloudtrail.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import org.junit.jupiter.api.*; @@ -19,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudTrailTest { + private static final Logger logger = LoggerFactory.getLogger(CloudTrailTest.class); private static CloudTrailClient cloudTrailClient; private static String trailName = ""; private static String s3BucketName = ""; @@ -27,8 +30,7 @@ public class CloudTrailTest { public static void setUp() { cloudTrailClient = CloudTrailClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -36,106 +38,84 @@ public static void setUp() { SecretValues values = gson.fromJson(json, SecretValues.class); trailName = values.getTrailName(); s3BucketName = values.getS3BucketName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * CloudTrailTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * trailName = prop.getProperty("trailName"); - * s3BucketName = prop.getProperty("s3BucketName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateTrail() { + public void testCreateTrail() { assertDoesNotThrow(() -> CreateTrail.createNewTrail(cloudTrailClient, trailName, s3BucketName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void PutEventSelectors() { + public void testPutEventSelectors() { assertDoesNotThrow(() -> PutEventSelectors.setSelector(cloudTrailClient, trailName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetEventSelectors() { + public void testGetEventSelectors() { assertDoesNotThrow(() -> GetEventSelectors.getSelectors(cloudTrailClient, trailName)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void LookupEvents() { + public void testLookupEvents() { assertDoesNotThrow(() -> LookupEvents.lookupAllEvents(cloudTrailClient)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DescribeTrails() { + public void testDescribeTrails() { assertDoesNotThrow(() -> DescribeTrails.describeSpecificTrails(cloudTrailClient, trailName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void GetTrailLoggingTime() { + public void testGetTrailLoggingTime() { assertDoesNotThrow(() -> GetTrailLoggingTime.getLogTime(cloudTrailClient, trailName)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void StartLogging() { + public void testStartLogging() { assertDoesNotThrow(() -> StartLogging.startLog(cloudTrailClient, trailName)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void StopLogging() { + public void testStopLogging() { assertDoesNotThrow(() -> StartLogging.stopLog(cloudTrailClient, trailName)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void DeleteTrail() { + public void testDeleteTrail() { assertDoesNotThrow(() -> DeleteTrail.deleteSpecificTrail(cloudTrailClient, trailName)); - System.out.println("Test 9 passed"); + logger.info("Test 9 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + //.credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/cloudtrail"; diff --git a/javav2/example_code/cloudwatch/pom.xml b/javav2/example_code/cloudwatch/pom.xml index 733bdb41dbd..e55deee46ad 100755 --- a/javav2/example_code/cloudwatch/pom.xml +++ b/javav2/example_code/cloudwatch/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java b/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java index fc1716a9a3d..8c466931546 100644 --- a/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java +++ b/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java @@ -36,6 +36,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudWatchTest { + private static final Logger logger = LoggerFactory.getLogger(CloudWatchTest.class); private static CloudWatchClient cw; private static String namespace = ""; private static String myDateSc = ""; @@ -44,19 +45,14 @@ public class CloudWatchTest { private static String dashboardJsonSc = ""; private static String dashboardAddSc = ""; private static String settingsSc = ""; - private static String alarmName = ""; - private static final CloudWatchActions cwActions = new CloudWatchActions(); - private static Dimension myDimension = null; - private static final Logger logger = LoggerFactory.getLogger(CloudWatchTest.class); @BeforeAll public static void setUp() throws IOException { cw = CloudWatchClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -89,10 +85,9 @@ public void testListNameSpaces() { ArrayList list = future.join(); assertFalse(list.isEmpty()); }); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } - @Test @Tag("IntegrationTest") @Order(3) @@ -101,7 +96,7 @@ void testCreateDashboard() { CompletableFuture future = cwActions.createDashboardWithMetricsAsync(dashboardNameSc, dashboardJsonSc); future.join(); }); - logger.info("\n Test 6 passed"); + logger.info("\n Test 3 passed"); } @Test @@ -112,7 +107,7 @@ public void testGetMetricData() { CompletableFuture future = cwActions.getMetricStatisticsAsync(costDateWeekSc); future.join(); }); - logger.info("\n Test 7 passed"); + logger.info("\n Test 4 passed"); } @Test @@ -123,7 +118,7 @@ public void testListDashboards() { CompletableFuture future = cwActions.listDashboardsAsync(); future.join(); }); - logger.info("\n Test 8 passed"); + logger.info("\n Test 5 passed"); } @Test @@ -135,7 +130,7 @@ public void testListMetrics() { CompletableFuture future = cwActions.createNewCustomMetricAsync(dataPoint); future.join(); }); - logger.info("\n Test 9 passed"); + logger.info("\n Test 6 passed"); } @Test @@ -147,7 +142,7 @@ public void testMetricToDashboard() { future.join(); }); - logger.info("\n Test 10 passed"); + logger.info("\n Test 7 passed"); } @Test @Tag("IntegrationTest") @@ -158,7 +153,7 @@ public void testCreateAlarm() { alarmName = future.join(); assertFalse(alarmName.isEmpty()); }); - logger.info("\n Test 11 passed"); + logger.info("\n Test 8 passed"); } @Test @@ -169,7 +164,7 @@ public void testDescribeAlarms() { CompletableFuture future = cwActions.describeAlarmsAsync(); future.join(); }); - logger.info("\n Test 12 passed"); + logger.info("\n Test 9 passed"); } @Test @@ -180,7 +175,7 @@ public void testCustomMetricData() { CompletableFuture future = cwActions.getCustomMetricDataAsync(settingsSc); future.join(); }); - logger.info("\n Test 13 passed"); + logger.info("\n Test 10 passed"); } @Test @@ -191,7 +186,7 @@ public void testMetricDataForAlarm() { CompletableFuture future = cwActions.addMetricDataForAlarmAsync(settingsSc); future.join(); }); - logger.info("\n Test 14 passed"); + logger.info("\n Test 11 passed"); } @Test @@ -202,7 +197,7 @@ public void testMetricAlarmAsync() { CompletableFuture future = cwActions.checkForMetricAlarmAsync(settingsSc); future.join(); }); - logger.info("\n Test 15 passed"); + logger.info("\n Test 12 passed"); } @Test @@ -213,7 +208,7 @@ public void testAlarmHistory() { CompletableFuture future = cwActions.getAlarmHistoryAsync(settingsSc, myDateSc); future.join(); }); - logger.info("\n Test 16 passed"); + logger.info("\n Test 13 passed"); } @Test @@ -224,7 +219,7 @@ public void testAnomalyDetector() { CompletableFuture future = cwActions.addAnomalyDetectorAsync(settingsSc); future.join(); }); - logger.info("\n Test 17 passed"); + logger.info("\n Test 14 passed"); } @Test @@ -236,7 +231,7 @@ public void testDeleteDashboard() { future.join(); }); - logger.info("\n Test 18 passed"); + logger.info("\n Test 15 passed"); } @Test @@ -248,7 +243,7 @@ public void testCWAlarmAsync() { future.join(); }); - logger.info("\n Test 19 passed"); + logger.info("\n Test 16 passed"); } @Test @@ -260,13 +255,12 @@ public void testDeleteAnomalyDetector() { future.join(); }); - logger.info("\n Test 20 passed"); + logger.info("\n Test 17 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/cloudwatch"; diff --git a/javav2/example_code/codecommit/pom.xml b/javav2/example_code/codecommit/pom.xml index 13f6846a57d..cfc86e79a97 100644 --- a/javav2/example_code/codecommit/pom.xml +++ b/javav2/example_code/codecommit/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.23.1 pom import diff --git a/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java b/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java deleted file mode 100644 index 1a942a1c6b2..00000000000 --- a/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import com.example.commit.*; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.codecommit.CodeCommitClient; -import org.junit.jupiter.api.*; - -import java.io.*; -import java.net.URISyntaxException; -import java.util.*; -import static org.junit.jupiter.api.Assertions.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class CodeCommitTest { - - - private static String branchCommitId =""; // needs to be updated to use latest for each test - required for PutFile test - private static CodeCommitClient codeCommitClient ; - private static String newRepoName =""; - private static String existingRepoName =""; - private static String newBranchName=""; - private static String existingBranchName=""; - private static String commitId ="" ; - private static String filePath =""; - private static String email =""; - private static String name =""; - private static String repoPath =""; // change for each test - private static String targetBranch =""; - private static String prID = ""; - - @BeforeAll - public static void setUp() throws IOException, URISyntaxException { - - Region region = Region.US_EAST_1; - codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); - - try (InputStream input = CodeCommitClient.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - newRepoName = prop.getProperty("newRepoName"); - existingRepoName = prop.getProperty("existingRepoName"); - newBranchName = prop.getProperty("newBranchName"); - existingBranchName = prop.getProperty("existingBranchName"); - branchCommitId = prop.getProperty("branchCommitId"); - filePath = prop.getProperty("filePath"); - name = prop.getProperty("name"); - repoPath = prop.getProperty("repoPath"); - email = prop.getProperty("email"); - targetBranch = prop.getProperty("targetBranch"); - prID = prop.getProperty("prID"); - - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - @Test - @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(codeCommitClient); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) - public void CreateRepository() { - CreateRepository.createRepo(codeCommitClient, newRepoName); - System.out.println("Test 2 passed"); - } - - @Test - @Order(3) - public void PutFile() { - PutFile.uploadFile(codeCommitClient, filePath, existingRepoName, existingBranchName, email, name, repoPath, branchCommitId); - System.out.println("Test 3 passed"); - } - - @Test - @Order(4) - public void CreatePullRequest() { - prID = CreatePullRequest.createPR(codeCommitClient, existingRepoName, targetBranch, existingBranchName); - assertTrue(!prID.isEmpty()); - System.out.println("Test 4 passed"); - } - - @Test - @Order(5) - public void GetMergeOptions() { - commitId = GetMergeOptions.getMergeValues(codeCommitClient, existingRepoName, targetBranch, existingBranchName ); - assertTrue(!commitId.isEmpty()); - System.out.println("Test 5 passed"); - } - - @Test - @Order(6) - public void MergeBranches() { - MergeBranches.merge(codeCommitClient, existingRepoName, targetBranch, existingBranchName, commitId); - System.out.println("Test 6 passed"); - } - - @Test - @Order(7) - public void CreateBranch() { - CreateBranch.createSpecificBranch(codeCommitClient, existingRepoName, newBranchName, commitId); - System.out.println("Test 7 passed"); - } - - @Test - @Order(8) - public void ListRepositories() { - ListRepositories.listRepos(codeCommitClient); - System.out.println("Test 8 passed"); - } - - - @Test - @Order(9) - public void DeleteRepository() { - DeleteRepository.deleteRepo(codeCommitClient, newRepoName); - System.out.println("Test 9 passed"); - } - - @Test - @Order(10) - public void DeleteBranch() { - DeleteBranch.deleteSpecificBranch(codeCommitClient, existingRepoName, newBranchName); - System.out.println("Test 10 passed"); - } - - @Test - @Order(11) - public void DescribePullRequestEvents() { - DescribePullRequestEvents.describePREvents(codeCommitClient, prID); - System.out.println("Test 11 passed"); - } - - @Test - @Order(12) - public void GetRepository() { - GetRepository.getRepInformation(codeCommitClient, existingRepoName); - System.out.println("Test 12 passed"); - } -} diff --git a/javav2/example_code/codedeploy/pom.xml b/javav2/example_code/codedeploy/pom.xml index 08de3728a26..49e0a406e89 100644 --- a/javav2/example_code/codedeploy/pom.xml +++ b/javav2/example_code/codedeploy/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,10 +35,17 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + @@ -69,5 +76,23 @@ software.amazon.awssdk ssooidc + + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/codedeploy/src/main/resources/log4j2.xml b/javav2/example_code/codedeploy/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/codedeploy/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java b/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java index a464a6d73b0..24123a078a7 100644 --- a/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java +++ b/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java @@ -3,6 +3,8 @@ import com.example.deploy.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.junit.jupiter.api.*; @@ -19,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CodeDeployTest { + private static final Logger logger = LoggerFactory.getLogger(CodeDeployTest.class); private static CodeDeployClient deployClient; private static String appName = ""; private static String existingApp = ""; @@ -37,7 +40,6 @@ public static void setUp() { Region region = Region.US_EAST_1; deployClient = CodeDeployClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Gson gson = new Gson(); @@ -53,110 +55,79 @@ public static void setUp() { serviceRoleArn = values.getServiceRoleArn(); tagKey = values.getTagKey(); tagValue = values.getTagValue(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * CodeDeployTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * appName = prop.getProperty("appName"); - * existingApp = prop.getProperty("existingApp"); - * existingDeployment = prop.getProperty("existingDeployment"); - * bucketName = prop.getProperty("bucketName"); - * key = prop.getProperty("key"); - * bundleType = prop.getProperty("bundleType"); - * newDeploymentGroupName = prop.getProperty("newDeploymentGroupName"); - * serviceRoleArn = prop.getProperty("serviceRoleArn"); - * tagKey = prop.getProperty("tagKey"); - * tagValue = prop.getProperty("tagValue"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateApplication() { + public void testCreateApplication() { assertDoesNotThrow(() -> CreateApplication.createApp(deployClient, appName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void ListApplications() { + public void testListApplications() { assertDoesNotThrow(() -> ListApplications.listApps(deployClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DeployApplication() { + public void testDeployApplication() { deploymentId = DeployApplication.createAppDeployment(deployClient, existingApp, bucketName, bundleType, key, existingDeployment); assertFalse(deploymentId.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void CreateDeploymentGroup() { + public void testCreateDeploymentGroup() { assertDoesNotThrow(() -> CreateDeploymentGroup.createNewDeploymentGroup(deployClient, newDeploymentGroupName, appName, serviceRoleArn, tagKey, tagValue)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListDeploymentGroups() { + public void testListDeploymentGroups() { assertDoesNotThrow(() -> ListDeploymentGroups.listDeployGroups(deployClient, appName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void GetDeployment() { + public void testGetDeployment() { assertDoesNotThrow(() -> GetDeployment.getSpecificDeployment(deployClient, deploymentId)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteDeploymentGroup() { + public void testDeleteDeploymentGroup() { assertDoesNotThrow( () -> DeleteDeploymentGroup.delDeploymentGroup(deployClient, appName, newDeploymentGroupName)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void DeleteApplication() { + public void testDeleteApplication() { assertDoesNotThrow(() -> DeleteApplication.delApplication(deployClient, appName)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/codedeploy"; diff --git a/javav2/example_code/codepipeline/pom.xml b/javav2/example_code/codepipeline/pom.xml index 84531eff85c..28517e170c6 100644 --- a/javav2/example_code/codepipeline/pom.xml +++ b/javav2/example_code/codepipeline/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -70,5 +77,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/codepipeline/src/main/resources/log4j2.xml b/javav2/example_code/codepipeline/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/codepipeline/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/cognito/pom.xml b/javav2/example_code/cognito/pom.xml index 14979e52597..36c61c60dbf 100644 --- a/javav2/example_code/cognito/pom.xml +++ b/javav2/example_code/cognito/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/resources/log4j2.xml b/javav2/example_code/cognito/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/cognito/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java b/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java index 1d3d87058f3..95d065509b4 100644 --- a/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java +++ b/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java @@ -4,7 +4,8 @@ import com.example.cognito.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; @@ -22,6 +23,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @Tag("integ") public class AmazonCognitoTest { + private static final Logger logger = LoggerFactory.getLogger(AmazonCognitoTest.class); private static CognitoIdentityProviderClient cognitoclient; private static CognitoIdentityProviderClient cognitoIdentityProviderClient; private static CognitoIdentityClient cognitoIdclient; @@ -54,17 +56,14 @@ public static void setUp() throws IOException { // Run tests on Real AWS Resources cognitoclient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); cognitoIdclient = CognitoIdentityClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); cognitoIdentityProviderClient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Gson gson = new Gson(); @@ -89,172 +88,127 @@ public static void setUp() throws IOException { userNameMVP = values.getUserNameMVP(); passwordMVP = values.getPasswordMVP(); emailMVP = values.getEmailMVP(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonCognitoTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * //load a properties file from class path, inside static method - * prop.load(input); - * - * // Populate the data members required for all tests - * userPoolName = prop.getProperty("userPoolName"); - * username= prop.getProperty("username")+"_"+ java.util.UUID.randomUUID(); - * email= prop.getProperty("email"); - * clientName = prop.getProperty("clientName"); - * identityPoolName = prop.getProperty("identityPoolName"); - * identityId = prop.getProperty("identityId"); // used in the - * GetIdentityCredentials test - * appId = prop.getProperty("appId"); - * existingUserPoolId = prop.getProperty("existingUserPoolId"); - * existingIdentityPoolId = prop.getProperty("existingIdentityPoolId"); - * providerName = prop.getProperty("providerName"); - * existingPoolName = prop.getProperty("existingPoolName"); - * clientId = prop.getProperty("clientId"); - * secretkey = prop.getProperty("secretkey"); - * password = prop.getProperty("password"); - * poolIdMVP = prop.getProperty("poolIdMVP"); - * clientIdMVP = prop.getProperty("clientIdMVP"); - * userNameMVP = prop.getProperty("userNameMVP"); - * passwordMVP = prop.getProperty("passwordMVP"); - * emailMVP = prop.getProperty("emailMVP"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateUserPool() { + public void testCreateUserPool() { userPoolId = CreateUserPool.createPool(cognitoclient, userPoolName); assertFalse(userPoolId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateUser() { + public void testCreateUser() { assertDoesNotThrow(() -> CreateUser.createNewUser(cognitoclient, userPoolId, username, email, password)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void CreateUserPoolClient() { + public void testCreateUserPoolClient() { assertDoesNotThrow(() -> CreateUserPoolClient.createPoolClient(cognitoclient, clientName, userPoolId)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void CreateIdentityPool() { + public void testCreateIdentityPool() { identityPoolId = CreateIdentityPool.createIdPool(cognitoIdclient, identityPoolName); assertFalse(identityPoolId.isEmpty()); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListUserPools() { + public void testListUserPools() { assertDoesNotThrow(() -> ListUserPools.listAllUserPools(cognitoclient)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ListIdentityPools() { + public void testListIdentityPools() { assertDoesNotThrow(() -> ListIdentityPools.listIdPools(cognitoIdclient)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void ListUserPoolClients() { + public void testListUserPoolClients() { assertDoesNotThrow( () -> ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, existingUserPoolId)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void ListUsers() { + public void testListUsers() { assertDoesNotThrow(() -> ListUsers.listAllUsers(cognitoclient, existingUserPoolId)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void ListIdentities() { + public void testListIdentities() { assertDoesNotThrow(() -> ListIdentities.listPoolIdentities(cognitoIdclient, existingIdentityPoolId)); - System.out.println("Test 9 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void AddLoginProvider() { + public void testAddLoginProvider() { assertDoesNotThrow(() -> AddLoginProvider.setLoginProvider(cognitoIdclient, appId, existingPoolName, existingIdentityPoolId, providerName)); - System.out.println("Test 10 passed"); + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void GetIdentityCredentials() { + public void testGetIdentityCredentials() { assertDoesNotThrow(() -> GetIdentityCredentials.getCredsForIdentity(cognitoIdclient, identityId)); - System.out.println("Test 11 passed"); + logger.info("Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void GetId() { + public void testGetId() { assertDoesNotThrow(() -> GetId.getClientID(cognitoIdclient, existingIdentityPoolId)); - System.out.println("Test 12 passed"); + logger.info("Test 12 passed"); } @Test @Tag("IntegrationTest") @Order(13) - public void DeleteUserPool() { + public void testDeleteUserPool() { assertDoesNotThrow(() -> DeleteUserPool.deletePool(cognitoclient, userPoolId)); - System.out.println("Test 13 passed"); + logger.info("Test 13 passed"); } @Test @Tag("IntegrationTest") @Order(14) - public void DeleteIdentityPool() { + public void testDeleteIdentityPool() { assertDoesNotThrow(() -> DeleteIdentityPool.deleteIdPool(cognitoIdclient, identityPoolId)); - System.out.println("Test 15 passed"); + logger.info("Test 15 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/cognito"; diff --git a/javav2/example_code/comprehend/pom.xml b/javav2/example_code/comprehend/pom.xml index 0d7f5980f7c..e8659800c9b 100644 --- a/javav2/example_code/comprehend/pom.xml +++ b/javav2/example_code/comprehend/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,10 +35,18 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + + @@ -73,5 +81,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/comprehend/src/main/resources/log4j2.xml b/javav2/example_code/comprehend/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/comprehend/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java b/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java index 9b52539c1c2..72ec6eb761a 100644 --- a/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java +++ b/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java @@ -4,6 +4,8 @@ import com.example.comprehend.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; @@ -20,7 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonComprehendTest { - + private static final Logger logger = LoggerFactory.getLogger(AmazonComprehendTest.class); private static ComprehendClient comClient; private static String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing"; private static String frText = "Il pleut aujourd'hui à Seattle"; @@ -32,7 +34,6 @@ public class AmazonComprehendTest { public static void setUp() throws IOException { comClient = ComprehendClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -42,84 +43,56 @@ public static void setUp() throws IOException { dataAccessRoleArn = values.getDataAccessRoleArn(); s3Uri = values.getS3Uri(); documentClassifierName = values.getDocumentClassifier(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonComprehendTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * //load a properties file from class path, inside static method - * prop.load(input); - * - * // Populate the data members required for all tests - * dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); - * s3Uri = prop.getProperty("s3Uri"); - * documentClassifierName = prop.getProperty("documentClassifier"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("weathertop") @Tag("IntegrationTest") @Order(1) - public void DetectEntities() { + public void testDetectEntities() { assertDoesNotThrow(() -> DetectEntities.detectAllEntities(comClient, text)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("weathertop") @Tag("IntegrationTest") @Order(2) - public void DetectKeyPhrases() { + public void testDetectKeyPhrases() { assertDoesNotThrow(() -> DetectKeyPhrases.detectAllKeyPhrases(comClient, text)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("weathertop") @Tag("IntegrationTest") @Order(3) - public void DetectLanguage() { + public void testDetectLanguage() { assertDoesNotThrow(() -> DetectLanguage.detectTheDominantLanguage(comClient, frText)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("weathertop") @Tag("IntegrationTest") @Order(4) - public void DetectSentiment() { + public void testDetectSentiment() { assertDoesNotThrow(() -> DetectSentiment.detectSentiments(comClient, text)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("weathertop") @Tag("IntegrationTest") @Order(5) - public void DetectSyntax() { + public void testDetectSyntax() { assertDoesNotThrow(() -> DetectSyntax.detectAllSyntax(comClient, text)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/comprehend"; diff --git a/javav2/example_code/connect/pom.xml b/javav2/example_code/connect/pom.xml index 59f926860ff..581f9c984a0 100644 --- a/javav2/example_code/connect/pom.xml +++ b/javav2/example_code/connect/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/connect/src/main/resources/log4j2.xml b/javav2/example_code/connect/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/connect/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/connect/src/test/java/ConnectTest.java b/javav2/example_code/connect/src/test/java/ConnectTest.java index 69efdd580fd..dbef1dd6fe5 100644 --- a/javav2/example_code/connect/src/test/java/ConnectTest.java +++ b/javav2/example_code/connect/src/test/java/ConnectTest.java @@ -21,12 +21,17 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.connect.ConnectClient; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + +import java.util.Random; + import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -37,6 +42,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ConnectTest { + private static final Logger logger = LoggerFactory.getLogger(ConnectTest.class); private static ConnectClient connectClient; private static String instanceAlias = ""; private static String instanceId = ""; @@ -48,116 +54,65 @@ public class ConnectTest { public static void setUp() { connectClient = ConnectClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); + int randomValue = new Random().nextInt(1000) + 1; String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - instanceAlias = values.getInstanceAlias(); + instanceAlias = values.getInstanceAlias()+randomValue; contactId = values.getContactId(); existingInstanceId = values.getExistingInstanceId(); targetArn = values.getTargetArn(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * ConnectTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Load a properties file. - * prop.load(input); - * instanceAlias = prop.getProperty("instanceAlias"); - * contactId = prop.getProperty("contactId"); - * existingInstanceId = prop.getProperty("existingInstanceId"); - * targetArn = prop.getProperty("targetArn"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void createInstance() { + public void testCreateInstance() { instanceId = CreateInstance.createConnectInstance(connectClient, instanceAlias); assertFalse(instanceId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void describeInstance() throws InterruptedException { + public void testDescribeInstance() throws InterruptedException { assertDoesNotThrow(() -> DescribeInstance.describeSpecificInstance(connectClient, instanceId)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void listInstances() { + public void testListInstances() { assertDoesNotThrow(() -> ListInstances.listAllInstances(connectClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void deleteInstance() { + public void testDeleteInstance() { assertDoesNotThrow(() -> DeleteInstance.deleteSpecificInstance(connectClient, instanceId)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void describeInstanceAttribute() { - assertDoesNotThrow(() -> DescribeInstanceAttribute.describeAttribute(connectClient, existingInstanceId)); - System.out.println("Test 6 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(6) - public void listPhoneNumbers() { + public void testListPhoneNumbers() { assertDoesNotThrow(() -> ListPhoneNumbers.getPhoneNumbers(connectClient, targetArn)); - System.out.println("Test 8 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(7) - public void listUsers() { - assertDoesNotThrow(() -> ListUsers.getUsers(connectClient, existingInstanceId)); - System.out.println("Test 9 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(7) - public void searchQueues() { - assertDoesNotThrow(() -> SearchQueues.searchQueue(connectClient, existingInstanceId)); - System.out.println("Test 10 passed"); + logger.info("Test 5 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/connect"; - GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); diff --git a/javav2/example_code/dynamodb/pom.xml b/javav2/example_code/dynamodb/pom.xml index 03d745e8f7d..d3152ad2a79 100644 --- a/javav2/example_code/dynamodb/pom.xml +++ b/javav2/example_code/dynamodb/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -79,11 +86,6 @@ software.amazon.awssdk kms - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk sso @@ -92,5 +94,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java index 4af63125a10..8c7a7c91745 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java @@ -6,10 +6,8 @@ // snippet-start:[dynamodb.java2.update_table.main] // snippet-start:[dynamodb.java2.update_table.import] import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; // snippet-end:[dynamodb.java2.update_table.import] /** @@ -24,57 +22,48 @@ public class UpdateTable { public static void main(String[] args) { final String usage = """ Usage: - - + + Where: tableName - The Amazon DynamoDB table to update (for example, Music3). - readCapacity - The new read capacity of the table (for example, 16). - writeCapacity - The new write capacity of the table (for example, 10). - + Example: - UpdateTable Music3 16 10 + UpdateTable Music """; - if (args.length != 3) { + if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; - Long readCapacity = Long.parseLong(args[1]); - Long writeCapacity = Long.parseLong(args[2]); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); - updateDynamoDBTable(ddb, tableName, readCapacity, writeCapacity); + updateDynamoDBTable(ddb, tableName); ddb.close(); } - public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long readCapacity, - Long writeCapacity) { - System.out.format("Updating %s with new provisioned throughput values\n", tableName); - System.out.format("Read capacity : %d\n", readCapacity); - System.out.format("Write capacity : %d\n", writeCapacity); - - ProvisionedThroughput tableThroughput = ProvisionedThroughput.builder() - .readCapacityUnits(readCapacity) - .writeCapacityUnits(writeCapacity) - .build(); + public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName) { + System.out.format("Updating %s with new stream settings...\n", tableName); UpdateTableRequest request = UpdateTableRequest.builder() - .provisionedThroughput(tableThroughput) .tableName(tableName) + .streamSpecification(StreamSpecification.builder() + .streamEnabled(true) + .streamViewType(StreamViewType.NEW_AND_OLD_IMAGES) + .build()) .build(); try { ddb.updateTable(request); + System.out.println("Table updated successfully!"); } catch (DynamoDbException e) { - System.err.println(e.getMessage()); + System.err.println("Failed to update table: " + e.getMessage()); System.exit(1); } - System.out.println("Done!"); } } // snippet-end:[dynamodb.java2.update_table.main] diff --git a/javav2/example_code/dynamodb/src/main/resources/log4j2.xml b/javav2/example_code/dynamodb/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/dynamodb/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java index 5e31ecffbe4..b0b91167725 100644 --- a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java +++ b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java @@ -25,13 +25,15 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import java.io.IOException; +import java.util.Random; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,13 +46,13 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class DynamoDBTest { - + private static final Logger logger = LoggerFactory.getLogger(DynamoDBTest.class); private static DynamoDbClient ddb; // Define the data members required for the test. - private static String tableName = ""; - private static String itemVal = ""; - private static String updatedVal = ""; + private static String tableName = "Music"; + // private static String itemVal = ""; + // private static String updatedVal = ""; private static String key = ""; private static String keyVal = ""; private static String albumTitle = ""; @@ -67,14 +69,15 @@ public static void setUp() throws IOException { Region region = Region.US_EAST_1; ddb = DynamoDbClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - tableName = values.getTableName(); + Random random = new Random(); + int randomValue = random.nextInt(1000) + 1; + tableName = tableName + randomValue; fileName = values.getFileName(); key = values.getKey(); keyVal = values.getKeyValue(); @@ -85,60 +88,29 @@ public static void setUp() throws IOException { songTitle = values.getSongTitleVal(); songTitleVal = values.getSongTitleVal(); tableName2 = "Movies"; - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * DynamoDBTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * tableName = prop.getProperty("tableName"); - * fileName = prop.getProperty("fileName"); - * key = prop.getProperty("key"); - * keyVal = prop.getProperty("keyValue"); - * albumTitle = prop.getProperty("albumTitle"); - * albumTitleValue = prop.getProperty("AlbumTitleValue"); - * awards = prop.getProperty("Awards"); - * awardVal = prop.getProperty("AwardVal"); - * songTitle = prop.getProperty("SongTitle"); - * songTitleVal = prop.getProperty("SongTitleVal"); - * tableName2 = "Movies"; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void createTable() { + public void testCreateTable() { String result = CreateTable.createTable(ddb, tableName, key); assertFalse(result.isEmpty()); - System.out.println("\n Test 1 passed"); + logger.info("\n Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void describeTable() { + public void testDescribeTable() { assertDoesNotThrow(() -> DescribeTable.describeDymamoDBTable(ddb, tableName)); - System.out.println("\n Test 2 passed"); + logger.info("\n Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void putItem() { + public void testPutItem() { assertDoesNotThrow(() -> PutItem.putItemInTable(ddb, tableName, key, @@ -149,97 +121,94 @@ public void putItem() { awardVal, songTitle, songTitleVal)); - System.out.println("\n Test 3 passed"); + logger.info("\n Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void listTables() { + public void testListTables() { assertDoesNotThrow(() -> ListTables.listAllTables(ddb)); - System.out.println("\n Test 4 passed"); + logger.info("\n Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void queryTable() { + public void testQueryTable() { int response = Query.queryTable(ddb, tableName, key, keyVal, "#a"); assertEquals(response, 1); - System.out.println("\n Test 5 passed"); + logger.info("\n Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void updateItem() { + public void testUpdateItem() { assertDoesNotThrow(() -> UpdateItem.updateTableItem(ddb, tableName, key, keyVal, awards, "40")); - System.out.println("\n Test 6 passed"); + logger.info("\n Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void getItem() { + public void testGetItem() { assertDoesNotThrow(() -> GetItem.getDynamoDBItem(ddb, tableName, key, keyVal)); - System.out.println("\n Test 7 passed"); + logger.info("\n Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void scanItems() { + public void testScanItems() { assertDoesNotThrow(() -> DynamoDBScanItems.scanItems(ddb, tableName)); - System.out.println("\n Test 8 passed"); + logger.info("\n Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void deleteItem() { + public void testDeleteItem() { assertDoesNotThrow(() -> DeleteItem.deleteDynamoDBItem(ddb, tableName, key, keyVal)); - System.out.println("\n Test 9 passed"); + logger.info("\n Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void sycnPagination() { + public void testSycnPagination() { assertDoesNotThrow(() -> SyncPagination.manualPagination(ddb)); assertDoesNotThrow(() -> SyncPagination.autoPagination(ddb)); assertDoesNotThrow(() -> SyncPagination.autoPaginationWithResume(ddb)); - System.out.println("\n Test 10 passed"); + logger.info("\n Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void updateTable() { - Long readCapacity = Long.parseLong("16"); - Long writeCapacity = Long.parseLong("10"); - assertDoesNotThrow(() -> UpdateTable.updateDynamoDBTable(ddb, tableName, readCapacity, writeCapacity)); - System.out.println("\n Test 11 passed"); + public void testUpdateTable() { + assertDoesNotThrow(() -> UpdateTable.updateDynamoDBTable(ddb, tableName)); + logger.info("\n Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void deleteTable() { + public void testDeleteTable() { try { - // Wait 15 secs for table to update based on test 10 - TimeUnit.SECONDS.sleep(15); + TimeUnit.SECONDS.sleep(30); assertDoesNotThrow(() -> DeleteTable.deleteDynamoDBTable(ddb, tableName)); } catch (InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } - System.out.println("\n Test 12 passed"); + logger.info("\n Test 12 passed"); } @Test @Tag("IntegrationTest") @Order(13) - public void testScenario() throws IOException { + public void testTestScenario() throws IOException { assertDoesNotThrow(() -> Scenario.createTable(ddb, tableName2)); assertDoesNotThrow(() -> Scenario.loadData(ddb, tableName2, fileName)); assertDoesNotThrow(() -> Scenario.getItem(ddb)); @@ -248,7 +217,7 @@ public void testScenario() throws IOException { assertDoesNotThrow(() -> Scenario.scanMovies(ddb, tableName2)); assertDoesNotThrow(() -> Scenario.queryTable(ddb)); assertDoesNotThrow(() -> Scenario.deleteDynamoDBTable(ddb, tableName2)); - System.out.println("\n Test 13 passed"); + logger.info("\n Test 13 passed"); } @Test @@ -262,12 +231,12 @@ public void testScenarioPartiQL() throws IOException { assertDoesNotThrow(() -> ScenarioPartiQ.updateTableItem(ddb)); assertDoesNotThrow(() -> ScenarioPartiQ.queryTable(ddb)); assertDoesNotThrow(() -> ScenarioPartiQ.deleteDynamoDBTable(ddb, "MoviesPartiQ")); + logger.info("\n Test 14 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/dynamodb"; diff --git a/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java b/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java deleted file mode 100644 index 47220e1cfcc..00000000000 --- a/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.example.dynamodb.*; -import com.example.dynamodb.enhanced.*; -import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import org.junit.jupiter.api.*; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - - - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class EnhancedClientTest { - - private static DynamoDbClient ddb; - private static DynamoDbEnhancedClient enhancedClient; - private static String enhancedTableName = ""; - private static String enhancedTableKey = ""; - private static String enhancedTestRegion = ""; - - @BeforeAll - public static void setUp() { - - try (InputStream input = EnhancedClientTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - //load a properties file from class path, inside static method - prop.load(input); - enhancedTableName = prop.getProperty("enhancedTableName"); - enhancedTableKey = prop.getProperty("enhancedTableKey"); - enhancedTestRegion = prop.getProperty("enhancedTestRegion"); - } catch (IOException ex) { - ex.printStackTrace(); - } - - //Create a DynamoDbClient object - Region region = Region.of(enhancedTestRegion); - ddb = DynamoDbClient.builder() - .region(region) - .build(); - - // Create a DynamoDbEnhancedClient object - enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - } - - @Test - @Order(1) - public void whenInitializingEnhancedClient_thenNotNull() { - assertNotNull(enhancedClient); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) - public void CreateTable() { - EnhancedCreateTable.createTable(enhancedClient); - System.out.println("\n Test 2 passed"); - } - - @Test - @Order(3) - public void PutItem() { - - //Table exists as we used Waiters - EnhancedPutItem.putRecord(enhancedClient); - System.out.println("\n Test 3 passed"); - } - - @Test - @Order(4) - public void PutBatchItems() throws IOException { - - // create and seed the Music table to demonstrate that batching calls - // works with multiple tables - DynamoDBTest.setUp(); // load properties for Music table - DynamoDBTest ddbTest = new DynamoDBTest(); - ddbTest.createTable(); // create Music table - ddbTest.putItem(); // add one item to Music table - - EnhancedBatchWriteItems.putBatchRecords(enhancedClient); - System.out.println("\n Test 4 passed"); - ddbTest.deleteTable(); - } - - @Test - @Order(5) - public void queryWithFilter(){ - Integer customerCount = EnhancedQueryRecordsWithFilter.queryTableFilter(enhancedClient); - Assertions.assertEquals(1, customerCount); - System.out.println("\n Test 5 passed"); - } - - - @Test - @Order(6) - public void GetItem() { - String result = EnhancedGetItem.getItem(enhancedClient); - assertTrue(!result.isEmpty()); - System.out.println("\n Test 6 passed"); - } - - @Test - @Order(7) - public void QueryRecords() { - - String result = EnhancedQueryRecords.queryTable(enhancedClient); - assertTrue(!result.isEmpty()); - System.out.println("\n Test 7passed"); - } - - @Test - @Order(8) - public void ScanRecords() { - - EnhancedScanRecords.scan(enhancedClient); - System.out.println("\n Test 8 passed"); - } - - @Test - @Order(9) - public void DeleteTable() { - - DeleteTable.deleteDynamoDBTable(ddb,enhancedTableName); - System.out.println("\n Test 9 passed"); - } -} \ No newline at end of file diff --git a/javav2/example_code/dynamodbasync/pom.xml b/javav2/example_code/dynamodbasync/pom.xml index 478b2a3ed87..4baadcc993c 100755 --- a/javav2/example_code/dynamodbasync/pom.xml +++ b/javav2/example_code/dynamodbasync/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java index a2f52811dd3..f3d23340ebf 100644 --- a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java +++ b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java @@ -14,9 +14,11 @@ package com.example.dynamodbasync; // snippet-start:[dynamodb.java2.dbasync.table.import] + import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; + import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.services.dynamodb.model.BillingMode; @@ -79,7 +81,7 @@ public static void createTable(DynamoDbAsyncClient client, String tableName, Str .attributeName(key) .keyType(KeyType.HASH) .build()) - .billingMode(BillingMode.PAY_PER_REQUEST) // DynamoDB automatically scales based on traffic. + .billingMode(BillingMode.PAY_PER_REQUEST) // DynamoDB automatically scales based on traffic. .tableName(tableName) .build(); diff --git a/javav2/example_code/dynamodbasync/src/main/resources/config.properties b/javav2/example_code/dynamodbasync/src/main/resources/config.properties index b1687c7b68f..37d662a29af 100644 --- a/javav2/example_code/dynamodbasync/src/main/resources/config.properties +++ b/javav2/example_code/dynamodbasync/src/main/resources/config.properties @@ -1,5 +1,5 @@ -tableName = -key = -keyVal = -newTableName = -newKey = +tableName = Customer100 +key = id +keyVal = 50 +newTableName = Customer110 +newKey = 55 diff --git a/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java b/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java deleted file mode 100644 index 805360eeda6..00000000000 --- a/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import com.example.dynamodbasync.DynamoDBAsyncCreateTable; -import com.example.dynamodbasync.DynamoDBAsyncGetItem; -import com.example.dynamodbasync.DynamoDBAsyncListTables; -import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; -import org.junit.jupiter.api.*; -import software.amazon.awssdk.regions.Region; -import java.io.*; -import java.util.*; - - -import static org.junit.jupiter.api.Assertions.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class DynamoDBAsyncTest { - - // Define the data members required for the test - private static String tableName = ""; - private static String newTableName = ""; - private static String newKey = ""; - private static String key = ""; - private static String keyVal = ""; - - - @BeforeAll - public static void setUp() throws IOException { - - try (InputStream input = DynamoDBAsyncTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - tableName = prop.getProperty("tableName"); - key = prop.getProperty("key"); - keyVal = prop.getProperty("keyVal"); - newTableName= prop.getProperty("newTableName"); - newKey= prop.getProperty("newKey"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - @Test - @Order(1) - public void DynamoDBAsyncCreateTable() { - Region region = Region.US_WEST_2; - DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() - .region(region) - .build(); - - DynamoDBAsyncCreateTable.createTable(client, newTableName, newKey); - System.out.println("Test 2 passed"); - } - - - @Test - @Order(2) - public void DynamoDBAsyncGetItem() { - Region region = Region.US_WEST_2; - DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() - .region(region) - .build(); - DynamoDBAsyncGetItem.getItem(client, tableName, key, keyVal); - System.out.println("Test 2 passed"); - } - - @Test - @Order(3) - public void DynamoDBAsyncListTables() { - Region region = Region.US_WEST_2; - DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() - .region(region) - .build(); - DynamoDBAsyncListTables.listTables(client); - System.out.println("Test 3 passed"); - } -} diff --git a/javav2/example_code/ec2/pom.xml b/javav2/example_code/ec2/pom.xml index 57009824476..8dcdd3c6ac5 100644 --- a/javav2/example_code/ec2/pom.xml +++ b/javav2/example_code/ec2/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateLaunchTemplate.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateLaunchTemplate.java new file mode 100644 index 00000000000..9938a9bea4a --- /dev/null +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateLaunchTemplate.java @@ -0,0 +1,68 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.ec2; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2AsyncClient; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateLaunchTemplateRequest; +import software.amazon.awssdk.services.ec2.model.CreateLaunchTemplateResponse; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.RequestLaunchTemplateData; + +public class CreateLaunchTemplate { + + public static void main(String[] args) { + final String usage = """ + Usage: + + + Where: + launchTemplateName - The name of the launch template to create. + instanceType - The EC2 instance type (e.g., t2.2xlarge). + imageId - The AMI ID for the instance (e.g., ami-0f6832b69407e9746). + keyName - The name of the key pair for SSH access. + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String launchTemplateName = args[0]; + String instanceType = args[1]; + String imageId = args[2]; + String keyName = args[3]; + + Ec2Client ec2 = Ec2Client.builder() + .region(Region.US_EAST_1) + .build(); + + createLaunchTemplate(ec2, launchTemplateName, instanceType, imageId, keyName); + } + + public static void createLaunchTemplate(Ec2Client ec2, String launchTemplateName, String instanceType, String imageId, String keyName) { + try { + RequestLaunchTemplateData launchTemplateData = RequestLaunchTemplateData.builder() + .instanceType(instanceType) + .imageId(imageId) + .keyName(keyName) + .build(); + + CreateLaunchTemplateRequest launchTemplateRequest = CreateLaunchTemplateRequest.builder() + .launchTemplateName(launchTemplateName) + .launchTemplateData(launchTemplateData) + .versionDescription("Initial version with instance type") + .build(); + + CreateLaunchTemplateResponse response = ec2.createLaunchTemplate(launchTemplateRequest); + System.out.println("Launch Template created successfully: " + response.launchTemplate().launchTemplateId()); + + } catch (Ec2Exception e) { + System.err.println("Failed to create launch template: " + e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + +} \ No newline at end of file diff --git a/javav2/example_code/ec2/src/test/java/EC2Test.java b/javav2/example_code/ec2/src/test/java/EC2Test.java index 1ee45add804..5e822d951a3 100644 --- a/javav2/example_code/ec2/src/test/java/EC2Test.java +++ b/javav2/example_code/ec2/src/test/java/EC2Test.java @@ -5,6 +5,8 @@ import com.example.ec2.scenario.EC2Scenario; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -26,7 +28,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EC2Test { - + private static final Logger logger = LoggerFactory.getLogger(EC2Test.class); private static String keyName = ""; private static String groupName = ""; private static String groupDesc = ""; @@ -60,7 +62,7 @@ public static void setUp() { @Test @Tag("IntegrationTest") @Order(1) - public void createKeyPair() { + public void testCreateKeyPair() { try { CompletableFuture future = ec2Actions.createKeyPairAsync(keyNameSc, fileNameSc); CreateKeyPairResponse response = future.join(); @@ -71,21 +73,21 @@ public void createKeyPair() { // Assert specific properties of the response Assertions.assertNotNull(response.keyFingerprint(), "The key fingerprint should not be null"); Assertions.assertFalse(response.keyFingerprint().isEmpty(), "The key fingerprint should not be empty"); - System.out.println("Key Pair successfully created. Key Fingerprint: " + response.keyFingerprint()); + } catch (RuntimeException rte) { System.err.println("An exception occurred: " + (rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage())); Assertions.fail("Test failed due to an unexpected exception: " + rte.getMessage()); } - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void createInstance() { + public void testCreateInstance() { try { CompletableFuture future = ec2Actions.createSecurityGroupAsync(groupName, groupDesc, vpcIdSc, myIpAddressSc); groupId = future.join(); @@ -171,14 +173,14 @@ public void createInstance() { Assertions.fail("Test failed due to an unexpected exception while running instance: " + rte.getMessage()); } - System.out.println("\n Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void describeKeyPair() { + public void testDescribeKeyPair() { try { CompletableFuture future = ec2Actions.describeKeysAsync(); DescribeKeyPairsResponse response = future.join(); @@ -203,13 +205,13 @@ public void describeKeyPair() { Assertions.fail("Test failed due to an unexpected exception while describing key pairs: " + rte.getMessage()); } - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void deleteKeyPair() { + public void testDeleteKeyPair() { try { CompletableFuture future = ec2Actions.deleteKeysAsync(keyNameSc); DeleteKeyPairResponse response = future.join(); @@ -223,13 +225,13 @@ public void deleteKeyPair() { Assertions.fail("Test failed due to an unexpected exception while deleting key pair: " + rte.getMessage()); } - System.out.println("\n Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void describeSecurityGroup() { + public void testDescribeSecurityGroup() { try { CompletableFuture future = ec2Actions.describeSecurityGroupArnByNameAsync(groupName); groupId = future.join(); @@ -242,14 +244,14 @@ public void describeSecurityGroup() { Assertions.fail("Test failed due to an unexpected exception while describing security groups: " + rte.getMessage()); } - System.out.println("\n Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void describeInstances() { + public void testDescribeInstances() { try { CompletableFuture future = ec2Actions.describeEC2InstancesAsync(newInstanceId); String publicIp = future.join(); @@ -263,13 +265,13 @@ public void describeInstances() { System.err.println("An exception occurred: " + (rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage())); Assertions.fail("Test failed due to an unexpected exception while describing EC2 instances: " + rte.getMessage()); } - System.out.println("\n Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") - @Order(8) - public void terminateInstance() { + @Order(7) + public void testTerminateInstance() { try { System.out.println("Instance ID is: " + newInstanceId); CompletableFuture future = ec2Actions.terminateEC2Async(newInstanceId); @@ -285,13 +287,12 @@ public void terminateInstance() { } // Confirm that the test passed - System.out.println("\n Test 8 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/ec2"; diff --git a/javav2/example_code/ecr/pom.xml b/javav2/example_code/ecr/pom.xml index 805d4b185fb..c7b70b676e1 100644 --- a/javav2/example_code/ecr/pom.xml +++ b/javav2/example_code/ecr/pom.xml @@ -3,16 +3,14 @@ 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"> 4.0.0 - org.example ecr 1.0-SNAPSHOT - UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -37,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/ecr/src/main/resources/log4j2.xml b/javav2/example_code/ecr/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/ecr/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/ecr/src/test/java/ECRTest.java b/javav2/example_code/ecr/src/test/java/ECRTest.java index 9940e67ed91..a29a08f41eb 100644 --- a/javav2/example_code/ecr/src/test/java/ECRTest.java +++ b/javav2/example_code/ecr/src/test/java/ECRTest.java @@ -13,6 +13,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecr.EcrClient; @@ -26,20 +28,17 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ECRTest { - + private static final Logger logger = LoggerFactory.getLogger(ECRTest.class); private static EcrClient ecrClient; - private static String repoName = ""; - private static String newRepoName = ""; private static String iamRole = "" ; - private static ECRActions ecrActions; + @BeforeAll public static void setUp() { ecrClient = EcrClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); ecrActions = new ECRActions(); @@ -66,7 +65,7 @@ public void testScenario() { assertDoesNotThrow(() -> ecrActions.setLifeCyclePolicy(newRepoName)); assertDoesNotThrow(() -> ecrActions.pushDockerImage(newRepoName, newRepoName)); assertDoesNotThrow(() -> ecrActions.verifyImage(newRepoName, newRepoName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } catch (AssertionError e) { System.err.println("Test failed: " + e.getMessage()); try { @@ -84,13 +83,12 @@ public void testScenario() { @Order(2) public void testHello() { assertDoesNotThrow(() -> HelloECR.listImageTags(ecrClient, repoName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/ecr"; diff --git a/javav2/example_code/ecs/pom.xml b/javav2/example_code/ecs/pom.xml index 7105616205e..6b9075e0aa7 100644 --- a/javav2/example_code/ecs/pom.xml +++ b/javav2/example_code/ecs/pom.xml @@ -8,16 +8,23 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -39,11 +46,6 @@ gson 2.10.1 - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk ecs @@ -56,6 +58,23 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/ecs/src/main/resources/log4j2.xml b/javav2/example_code/ecs/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/ecs/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/ecs/src/test/java/EcsTest.java b/javav2/example_code/ecs/src/test/java/EcsTest.java index 6013e5e4eb7..ef63945f1c3 100644 --- a/javav2/example_code/ecs/src/test/java/EcsTest.java +++ b/javav2/example_code/ecs/src/test/java/EcsTest.java @@ -6,7 +6,9 @@ import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -21,6 +23,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EcsTest { + private static final Logger logger = LoggerFactory.getLogger(EcsTest.class); private static EcsClient ecsClient; private static String clusterName = ""; private static String clusterARN = ""; @@ -37,7 +40,6 @@ public static void setUp() throws IOException { // Run tests on Real AWS Resources ecsClient = EcsClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -50,98 +52,71 @@ public static void setUp() throws IOException { securityGroups = values.getSecurityGroups(); serviceName = values.getServiceName() + java.util.UUID.randomUUID(); taskDefinition = values.getTaskDefinition(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * EcsTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * clusterName = prop.getProperty("clusterName")+java.util.UUID.randomUUID(); - * taskId = prop.getProperty("taskId"); - * subnet = prop.getProperty("subnet"); - * securityGroups = prop.getProperty("securityGroups"); - * serviceName = prop.getProperty("serviceName")+java.util.UUID.randomUUID(); - * taskDefinition = prop.getProperty("taskDefinition"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateCluster() { + public void testCreateCluster() { clusterARN = CreateCluster.createGivenCluster(ecsClient, clusterName); assertFalse(clusterARN.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void ListClusters() { + public void testListClusters() { assertDoesNotThrow(() -> ListClusters.listAllClusters(ecsClient)); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeClusters() { + public void testDescribeClusters() { assertDoesNotThrow(() -> DescribeClusters.descCluster(ecsClient, clusterARN)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListTaskDefinitions() { + public void testListTaskDefinitions() { assertDoesNotThrow(() -> ListTaskDefinitions.getAllTasks(ecsClient, clusterARN, taskId)); - System.out.println("Test 5 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void CreateService() { + public void testCreateService() { serviceArn = CreateService.createNewService(ecsClient, clusterName, serviceName, securityGroups, subnet, taskDefinition); assertFalse(serviceArn.isEmpty()); - System.out.println("Test 6 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void UpdateService() throws InterruptedException { + public void testUpdateService() throws InterruptedException { Thread.sleep(20000); assertDoesNotThrow(() -> UpdateService.updateSpecificService(ecsClient, clusterName, serviceArn)); - System.out.println("Test 7 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteService() { + public void testDeleteService() { assertDoesNotThrow(() -> DeleteService.deleteSpecificService(ecsClient, clusterName, serviceArn)); - System.out.println("Test 8 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/ecs"; diff --git a/javav2/example_code/elasticbeanstalk/pom.xml b/javav2/example_code/elasticbeanstalk/pom.xml index f883b74e3e7..749222c5814 100644 --- a/javav2/example_code/elasticbeanstalk/pom.xml +++ b/javav2/example_code/elasticbeanstalk/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -62,11 +69,6 @@ gson 2.10.1 - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk textract @@ -79,5 +81,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/elasticbeanstalk/src/main/resources/log4j2.xml b/javav2/example_code/elasticbeanstalk/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/elasticbeanstalk/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java b/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java index ed39873d199..7d4a47f935f 100644 --- a/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java +++ b/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import com.aws.example.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import org.junit.jupiter.api.*; @@ -12,6 +14,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ElasticBeanstalkTest { + private static final Logger logger = LoggerFactory.getLogger(ElasticBeanstalkTest.class); private static ElasticBeanstalkClient beanstalkClient; private static final String appName = "apptest"; @@ -20,53 +23,52 @@ public static void setUp() { Region region = Region.US_EAST_1; beanstalkClient = ElasticBeanstalkClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } @Test @Tag("IntegrationTest") @Order(1) - public void CreateApp() { + public void testCreateApp() { String appArn = CreateApplication.createApp(beanstalkClient, appName); assertFalse(appArn.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateEnvironment() { + public void testCreateEnvironment() { String envName = "environmenttest"; String environmentArn = CreateEnvironment.createEBEnvironment(beanstalkClient, envName, appName); assertFalse(environmentArn.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeApplications() { + public void testDescribeApplications() { DescribeApplications.describeApps(beanstalkClient); assertTrue(true); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DescribeEnvironment() { + public void testDescribeEnvironment() { assertDoesNotThrow(() -> DescribeEnvironment.describeEnv(beanstalkClient, appName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DeleteApplication() throws InterruptedException { + public void testDeleteApplication() throws InterruptedException { System.out.println("*** Wait for 5 MIN so the app can be deleted"); TimeUnit.MINUTES.sleep(5); assertDoesNotThrow(() -> DeleteApplication.deleteApp(beanstalkClient, appName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } } diff --git a/javav2/example_code/emr/pom.xml b/javav2/example_code/emr/pom.xml index 1d2728baf41..3eb0c3a7e84 100644 --- a/javav2/example_code/emr/pom.xml +++ b/javav2/example_code/emr/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -57,11 +64,6 @@ gson 2.10.1 - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk emr @@ -74,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/emr/src/main/resources/log4j2.xml b/javav2/example_code/emr/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/emr/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/emr/src/test/java/EMRTest.java b/javav2/example_code/emr/src/test/java/EMRTest.java index 97f857909b9..abcdbc7f300 100644 --- a/javav2/example_code/emr/src/test/java/EMRTest.java +++ b/javav2/example_code/emr/src/test/java/EMRTest.java @@ -4,6 +4,8 @@ import aws.example.emr.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.emr.EmrClient; @@ -22,6 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EMRTest { + private static final Logger logger = LoggerFactory.getLogger(EMRTest.class); private static EmrClient emrClient; private static String jar = ""; private static String myClass = ""; @@ -35,7 +38,6 @@ public class EMRTest { public static void setUp() throws IOException { emrClient = EmrClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -48,82 +50,62 @@ public static void setUp() throws IOException { logUri = values.getLogUri(); name = values.getName(); existingClusterId = values.getExistingClusterId(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * EMRTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * // Populate the data members required for all tests. - * prop.load(input); - * jar = prop.getProperty("jar"); - * myClass = prop.getProperty("myClass"); - * keys = prop.getProperty("keys"); - * logUri = prop.getProperty("logUri"); - * name = prop.getProperty("name"); - * existingClusterId= prop.getProperty("existingClusterId"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test + @Tag("IntegrationTest") @Order(1) - public void createClusterTest() { + public void testCreateClusterTest() { jobFlowId = CreateCluster.createAppCluster(emrClient, jar, myClass, keys, logUri, name); assertFalse(jobFlowId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test + @Tag("IntegrationTest") @Order(2) - public void listClusterTest() { + public void testListClusterTest() { assertDoesNotThrow(() -> ListClusters.listAllClusters(emrClient)); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test + @Tag("IntegrationTest") @Order(3) - public void createEmrFleetTest() { + public void testCreateEmrFleetTest() { assertDoesNotThrow(() -> CreateEmrFleet.createFleet(emrClient)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test + @Tag("IntegrationTest") @Order(4) - public void createSparkClusterTest() { + public void testCreateSparkClusterTest() { assertDoesNotThrow(() -> CreateSparkCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); - System.out.println("Test 6 passed"); + logger.info("Test 4 passed"); } @Test + @Tag("IntegrationTest") @Order(5) - public void createHiveClusterTest() { + public void testCreateHiveClusterTest() { assertDoesNotThrow(() -> CreateHiveCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); - System.out.println("Test 7 passed"); + logger.info("Test 5 passed"); } @Test + @Tag("IntegrationTest") @Order(6) - public void customEmrfsMaterialsTest() { + public void testCustomEmrfsMaterialsTest() { assertDoesNotThrow(() -> CustomEmrfsMaterials.createEmrfsCluster(emrClient, jar, myClass, keys, logUri, name)); - System.out.println("Test 8 passed"); + logger.info("Test 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "text/emr"; diff --git a/javav2/example_code/entityresolution/pom.xml b/javav2/example_code/entityresolution/pom.xml index a70292a446b..86a6544aaeb 100644 --- a/javav2/example_code/entityresolution/pom.xml +++ b/javav2/example_code/entityresolution/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -30,7 +30,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/entityresolution/src/main/resources/log4j2.xml b/javav2/example_code/entityresolution/src/main/resources/log4j2.xml index 225afe2b3a8..914470047e7 100644 --- a/javav2/example_code/entityresolution/src/main/resources/log4j2.xml +++ b/javav2/example_code/entityresolution/src/main/resources/log4j2.xml @@ -3,7 +3,6 @@ - diff --git a/javav2/example_code/eventbridge/pom.xml b/javav2/example_code/eventbridge/pom.xml index 3e3ec997aef..7d35054472b 100644 --- a/javav2/example_code/eventbridge/pom.xml +++ b/javav2/example_code/eventbridge/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -72,5 +79,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/eventbridge/src/main/resources/log4j2.xml b/javav2/example_code/eventbridge/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/eventbridge/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/eventbridge/src/test/java/EventBridgeTest.java b/javav2/example_code/eventbridge/src/test/java/EventBridgeTest.java index 94a91e45c7e..f17c6640628 100644 --- a/javav2/example_code/eventbridge/src/test/java/EventBridgeTest.java +++ b/javav2/example_code/eventbridge/src/test/java/EventBridgeTest.java @@ -8,6 +8,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Order; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.eventbridge.EventBridgeClient; @@ -16,22 +18,20 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EventBridgeTest { - + private static final Logger logger = LoggerFactory.getLogger(EventBridgeTest.class); private static EventBridgeClient eventBrClient; @BeforeAll public static void setUp() throws IOException { eventBrClient = EventBridgeClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } @Test @Order(1) - public void helloEventBridge() { + public void testHelloEventBridge() { HelloEventBridge.listBuses(eventBrClient); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } - } \ No newline at end of file diff --git a/javav2/example_code/firehose/pom.xml b/javav2/example_code/firehose/pom.xml index b20f18c0875..eb4921f10fb 100644 --- a/javav2/example_code/firehose/pom.xml +++ b/javav2/example_code/firehose/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -83,5 +90,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/firehose/src/main/java/com/example/firehose/CreateDeliveryStream.java b/javav2/example_code/firehose/src/main/java/com/example/firehose/CreateDeliveryStream.java index 2a944d04977..1d31777624c 100644 --- a/javav2/example_code/firehose/src/main/java/com/example/firehose/CreateDeliveryStream.java +++ b/javav2/example_code/firehose/src/main/java/com/example/firehose/CreateDeliveryStream.java @@ -7,10 +7,9 @@ // snippet-start:[firehose.java2.create_stream.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.firehose.FirehoseClient; -import software.amazon.awssdk.services.firehose.model.FirehoseException; -import software.amazon.awssdk.services.firehose.model.CreateDeliveryStreamRequest; -import software.amazon.awssdk.services.firehose.model.ExtendedS3DestinationConfiguration; -import software.amazon.awssdk.services.firehose.model.CreateDeliveryStreamResponse; +import software.amazon.awssdk.services.firehose.model.*; + +import java.util.concurrent.TimeUnit; // snippet-end:[firehose.java2.create_stream.import] /** @@ -72,5 +71,36 @@ public static void createStream(FirehoseClient firehoseClient, String bucketARN, System.out.println(e.getLocalizedMessage()); } } + + public static void waitForStreamToBecomeActive(FirehoseClient firehoseClient, String streamName) { + System.out.println("Waiting for the stream to become ACTIVE..."); + int maxAttempts = 60; // 10 minutes (60 * 10 seconds) + int attempt = 0; + while (attempt < maxAttempts) { + try { + DescribeDeliveryStreamRequest describeRequest = DescribeDeliveryStreamRequest.builder() + .deliveryStreamName(streamName) + .build(); + DescribeDeliveryStreamResponse describeResponse = firehoseClient.describeDeliveryStream(describeRequest); + String status = describeResponse.deliveryStreamDescription().deliveryStreamStatusAsString(); + + System.out.println("Current status: " + status); + if (status.equals("ACTIVE")) { + System.out.println("Stream is now ACTIVE."); + return; + } + + TimeUnit.SECONDS.sleep(10); + attempt++; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Polling interrupted", e); + } catch (FirehoseException e) { + System.err.println("Error while checking stream status: " + e.getMessage()); + } + } + System.err.println("Timed out waiting for the stream to become ACTIVE."); + System.exit(1); + } } // snippet-end:[firehose.java2.create_stream.main] diff --git a/javav2/example_code/firehose/src/main/java/com/example/firehose/scenario/FirehoseScenario.java b/javav2/example_code/firehose/src/main/java/com/example/firehose/scenario/FirehoseScenario.java index ff5a9369c05..dc820488a27 100644 --- a/javav2/example_code/firehose/src/main/java/com/example/firehose/scenario/FirehoseScenario.java +++ b/javav2/example_code/firehose/src/main/java/com/example/firehose/scenario/FirehoseScenario.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.*; import software.amazon.awssdk.services.firehose.FirehoseClient; @@ -42,6 +43,7 @@ public static void main(String[] args) { System.out.println(usage); return; } + String deliveryStreamName = args[0]; try { @@ -77,14 +79,18 @@ public static void main(String[] args) { private static FirehoseClient getFirehoseClient() { if (firehoseClient == null) { - firehoseClient = FirehoseClient.create(); + firehoseClient = FirehoseClient.builder() + .region(Region.US_EAST_1) + .build(); } return firehoseClient; } private static CloudWatchClient getCloudWatchClient() { if (cloudWatchClient == null) { - cloudWatchClient = CloudWatchClient.create(); + cloudWatchClient = CloudWatchClient.builder() + .region(Region.US_EAST_1) + .build(); } return cloudWatchClient; } diff --git a/javav2/example_code/firehose/src/main/resources/log4j2.xml b/javav2/example_code/firehose/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..0c490da3ee3 --- /dev/null +++ b/javav2/example_code/firehose/src/main/resources/log4j2.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/firehose/src/test/java/FirehoseTest.java b/javav2/example_code/firehose/src/test/java/FirehoseTest.java index edc9525c17b..06a4a7aa2f9 100644 --- a/javav2/example_code/firehose/src/test/java/FirehoseTest.java +++ b/javav2/example_code/firehose/src/test/java/FirehoseTest.java @@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.firehose.FirehoseClient; @@ -28,6 +30,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FirehoseTest { + private static final Logger logger = LoggerFactory.getLogger(FirehoseTest.class); private static FirehoseClient firehoseClient; private static String bucketARN = ""; private static String roleARN = ""; @@ -37,8 +40,7 @@ public class FirehoseTest { @BeforeAll public static void setUp() throws IOException { firehoseClient = FirehoseClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .region(Region.US_EAST_1) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -49,46 +51,24 @@ public static void setUp() throws IOException { roleARN = values.getRoleARN(); newStream = values.getNewStream() + java.util.UUID.randomUUID(); textValue = values.getTextValue(); - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * FirehoseTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * bucketARN = prop.getProperty("bucketARN"); - * roleARN = prop.getProperty("roleARN"); - * newStream = prop.getProperty("newStream")+java.util.UUID.randomUUID(); - * textValue = prop.getProperty("textValue"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ + } @Test @Tag("IntegrationTest") @Order(1) - public void CreateDeliveryStream() { - assertDoesNotThrow(() -> CreateDeliveryStream.createStream(firehoseClient, bucketARN, roleARN, newStream)); - System.out.println("Test 1 passed"); + public void testCreateDeliveryStream() { + assertDoesNotThrow(() -> { + CreateDeliveryStream.createStream(firehoseClient, bucketARN, roleARN, newStream); + CreateDeliveryStream.waitForStreamToBecomeActive(firehoseClient, newStream); + }); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void PutRecord() throws IOException, InterruptedException { - System.out.println("Wait 10 mins for resource to become available."); - TimeUnit.MINUTES.sleep(10); + public void testPutRecord() throws IOException, InterruptedException { String jsonContent = FirehoseScenario.readJsonFile("sample_records.json"); ObjectMapper objectMapper = new ObjectMapper(); List> sampleData = objectMapper.readValue(jsonContent, new TypeReference<>() {}); @@ -102,29 +82,28 @@ public void PutRecord() throws IOException, InterruptedException { System.err.println("Error processing record: " + e.getMessage()); } }); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListDeliveryStreams() { + public void testListDeliveryStreams() { assertDoesNotThrow(() -> ListDeliveryStreams.listStreams(firehoseClient)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DeleteStream() { + public void testDeleteStream() { assertDoesNotThrow(() -> DeleteStream.delStream(firehoseClient, newStream)); - System.out.println("Test 5 passed"); + logger.info("Test 4 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/firehose"; @@ -161,5 +140,4 @@ public String getTextValue() { return textValue; } } - } diff --git a/javav2/example_code/forecast/pom.xml b/javav2/example_code/forecast/pom.xml index b4ddf18f76b..d238ad1d19c 100644 --- a/javav2/example_code/forecast/pom.xml +++ b/javav2/example_code/forecast/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -60,5 +67,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/forecast/src/main/resources/log4j2.xml b/javav2/example_code/forecast/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/forecast/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/forecast/src/test/java/ForecastTest.java b/javav2/example_code/forecast/src/test/java/ForecastTest.java index af6bac61cce..7e1826c0fd4 100644 --- a/javav2/example_code/forecast/src/test/java/ForecastTest.java +++ b/javav2/example_code/forecast/src/test/java/ForecastTest.java @@ -6,6 +6,9 @@ import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import java.util.*; @@ -22,6 +25,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ForecastTest { + private static final Logger logger = LoggerFactory.getLogger(ForecastTest.class); private static ForecastClient forecast; private static String predARN = ""; private static String forecastArn = ""; // set in test 3 @@ -35,7 +39,6 @@ public static void setUp() { int randomNum = rand.nextInt((10000 - 1) + 1) + 1; forecast = ForecastClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -50,67 +53,66 @@ public static void setUp() { @Test @Tag("IntegrationTest") @Order(1) - public void CreateDataSet() { + public void testCreateDataSet() { myDataSetARN = CreateDataSet.createForecastDataSet(forecast, dataSet); assertFalse(myDataSetARN.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateForecast() { + public void testCreateForecast() { forecastArn = CreateForecast.createNewForecast(forecast, forecastName, predARN); assertFalse(forecastArn.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListDataSets() { + public void testListDataSets() { assertDoesNotThrow(() -> ListDataSets.listForecastDataSets(forecast)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListDataSetGroups() { + public void testListDataSetGroups() { assertDoesNotThrow(() -> ListDataSetGroups.listDataGroups(forecast)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListForecasts() { + public void testListForecasts() { assertDoesNotThrow(() -> ListForecasts.listAllForeCasts(forecast)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteDataSet() { + public void testDeleteDataSet() { assertDoesNotThrow(() -> DeleteDataset.deleteForecastDataSet(forecast, myDataSetARN)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteForecast() throws InterruptedException { + public void testDeleteForecast() throws InterruptedException { System.out.println("Wait 40 mins for resource to become available."); TimeUnit.MINUTES.sleep(40); assertDoesNotThrow(() -> DeleteForecast.delForecast(forecast, forecastArn)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/forecast"; diff --git a/javav2/example_code/glacier/pom.xml b/javav2/example_code/glacier/pom.xml index b7e90c8cf49..25cd43d5805 100644 --- a/javav2/example_code/glacier/pom.xml +++ b/javav2/example_code/glacier/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -38,7 +38,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -89,5 +96,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/glacier/src/main/pom.xml b/javav2/example_code/glacier/src/main/pom.xml deleted file mode 100644 index 911834b483d..00000000000 --- a/javav2/example_code/glacier/src/main/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - glacierJ2Example - glacierJ2Example - 1.0-SNAPSHOT - - UTF-8 - 17 - 17 - 17 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.2 - - - - - - - software.amazon.awssdk - bom - 2.29.45 - pom - import - - - - - - org.junit.jupiter - junit-jupiter - 5.11.4 - test - - - software.amazon.awssdk - glacier - - - software.amazon.awssdk - secretsmanager - - - software.amazon.awssdk - sso - - - software.amazon.awssdk - ssooidc - - - \ No newline at end of file diff --git a/javav2/example_code/glacier/src/main/resources/log4j2.xml b/javav2/example_code/glacier/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/glacier/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/glacier/src/test/java/GlacierTest.java b/javav2/example_code/glacier/src/test/java/GlacierTest.java index 60f94232774..696ba0a5b3b 100644 --- a/javav2/example_code/glacier/src/test/java/GlacierTest.java +++ b/javav2/example_code/glacier/src/test/java/GlacierTest.java @@ -4,15 +4,19 @@ import com.example.glacier.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; + import static org.junit.jupiter.api.Assertions.*; /** @@ -22,6 +26,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class GlacierTest { + private static final Logger logger = LoggerFactory.getLogger(GlacierTest.class); private static GlacierClient glacier; private static String vaultName = ""; private static String strPath = ""; @@ -33,7 +38,6 @@ public class GlacierTest { @BeforeAll public static void setUp() { glacier = GlacierClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); @@ -46,96 +50,70 @@ public static void setUp() { downloadVault = values.getDownloadVault(); accountId = values.getAccountId(); emptyVault = values.getEmptyVault(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * GlacierTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * vaultName = prop.getProperty("vaultName"); - * strPath = prop.getProperty("strPath"); - * downloadVault= prop.getProperty("downloadVault"); - * accountId= prop.getProperty("accountId"); - * emptyVault= prop.getProperty("emptyVault"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateVault() { + public void testCreateVault() { assertDoesNotThrow(() -> CreateVault.createGlacierVault(glacier, vaultName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeVault() { + public void testDescribeVault() { assertDoesNotThrow(() -> DescribeVault.describeGlacierVault(glacier, vaultName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListVaults() { + public void testListVaults() { assertDoesNotThrow(() -> ListVaults.listAllVault(glacier)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void UploadArchive() { + public void testUploadArchive() { File myFile = new File(strPath); Path path = Paths.get(strPath); archiveId = UploadArchive.uploadContent(glacier, path, vaultName, myFile); assertFalse(archiveId.isEmpty()); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ArchiveDownload() { + public void testArchiveDownload() { assertDoesNotThrow(() -> ArchiveDownload.createJob(glacier, downloadVault, accountId)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteArchive() { + public void testDeleteArchive() { assertDoesNotThrow(() -> DeleteArchive.deleteGlacierArchive(glacier, vaultName, accountId, archiveId)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteVault() { + public void testDeleteVault() { assertDoesNotThrow(() -> DeleteVault.deleteGlacierVault(glacier, emptyVault)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/glacier"; diff --git a/javav2/example_code/glue/pom.xml b/javav2/example_code/glue/pom.xml index 2dfb2a826a5..a9f8f5d0fc4 100644 --- a/javav2/example_code/glue/pom.xml +++ b/javav2/example_code/glue/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/glue/src/main/resources/log4j2.xml b/javav2/example_code/glue/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/glue/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/glue/src/test/java/GlueTest.java b/javav2/example_code/glue/src/test/java/GlueTest.java index bb26061c38c..a0cfb6769b7 100644 --- a/javav2/example_code/glue/src/test/java/GlueTest.java +++ b/javav2/example_code/glue/src/test/java/GlueTest.java @@ -3,18 +3,15 @@ import com.example.glue.scenario.GlueScenario; import com.google.gson.Gson; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.glue.GlueClient; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; - -import java.io.*; -import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** @@ -24,7 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class GlueTest { - + private static final Logger logger = LoggerFactory.getLogger(GlueTest.class); private static GlueClient glueClient; private static String crawlerName = ""; private static String cron = ""; @@ -47,7 +44,6 @@ public class GlueTest { public static void setUp() { glueClient = GlueClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -79,6 +75,7 @@ void testCreateDatabase() { assertDoesNotThrow(() -> { GlueScenario.createDatabase(glueClient, dbNameSc, locationUri); }); + logger.info("Test 1 passed"); } @Test @@ -88,6 +85,7 @@ void testCreateGlueCrawler() { assertDoesNotThrow(() -> { GlueScenario.createGlueCrawler(glueClient, IAM, s3PathSc, cron, dbNameSc, crawlerNameSc); }); + logger.info("Test 2 passed"); } @Test @@ -97,6 +95,7 @@ void testGetSpecificCrawler() { assertDoesNotThrow(() -> { GlueScenario.getSpecificCrawler(glueClient, crawlerNameSc); }); + logger.info("Test 3 passed"); } @Test @@ -106,6 +105,7 @@ void testStartSpecificCrawler() { assertDoesNotThrow(() -> { GlueScenario.startSpecificCrawler(glueClient, crawlerNameSc); }); + logger.info("Test 4 passed"); } @Test @@ -115,6 +115,7 @@ void testGetSpecificDatabase() { assertDoesNotThrow(() -> { GlueScenario.getSpecificDatabase(glueClient, dbNameSc); }); + logger.info("Test 5 passed"); } @Test @@ -127,6 +128,7 @@ void testGetTable() { System.out.println("6. Get tables."); GlueScenario.getGlueTables(glueClient, dbNameSc); }); + logger.info("Test 6 passed"); } @Test @@ -136,6 +138,7 @@ void testCreateJob() { assertDoesNotThrow(() -> { GlueScenario.createJob(glueClient, jobNameSc, IAM, scriptLocationSc); }); + logger.info("Test 7 passed"); } @Test @@ -145,6 +148,7 @@ void testStartJob() { assertDoesNotThrow(() -> { GlueScenario.startJob(glueClient, jobNameSc, dbNameSc, tableName, bucketNameSc); }); + logger.info("Test 8 passed"); } @Test @@ -154,6 +158,7 @@ void testGetJobs() { assertDoesNotThrow(() -> { GlueScenario.getAllJobs(glueClient); }); + logger.info("Test 9 passed"); } @Test @@ -163,6 +168,7 @@ void testRunJobs() { assertDoesNotThrow(() -> { GlueScenario.getJobRuns(glueClient, jobNameSc); }); + logger.info("Test 10 passed"); } @Test @@ -172,6 +178,7 @@ void testDeleteJob() { assertDoesNotThrow(() -> { GlueScenario.deleteJob(glueClient, jobNameSc); }); + logger.info("Test 11 passed"); } @Test @@ -183,6 +190,7 @@ void testDeleteDB() { TimeUnit.MINUTES.sleep(5); GlueScenario.deleteDatabase(glueClient, dbNameSc); }); + logger.info("Test 12 passed"); } @Test @@ -194,12 +202,12 @@ void testDelCrawler() { TimeUnit.MINUTES.sleep(5); GlueScenario.deleteSpecificCrawler(glueClient, crawlerNameSc); }); + logger.info("Test 13 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/glue"; diff --git a/javav2/example_code/guardduty/pom.xml b/javav2/example_code/guardduty/pom.xml index 6022b03cbae..025200ecf1a 100644 --- a/javav2/example_code/guardduty/pom.xml +++ b/javav2/example_code/guardduty/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/guardduty/src/main/resources/log4j2.xml b/javav2/example_code/guardduty/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..0c490da3ee3 --- /dev/null +++ b/javav2/example_code/guardduty/src/main/resources/log4j2.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java b/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java index 145fab052d3..83109992099 100644 --- a/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java +++ b/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java @@ -5,6 +5,8 @@ import com.example.guardduty.GetFindings; import com.example.guardduty.ListDetectors; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.guardduty.GuardDutyClient; @@ -22,6 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class GuarddutyTest { + private static final Logger logger = LoggerFactory.getLogger(GuarddutyTest.class); private static GuardDutyClient guardDutyClient; private static String detectorId = ""; private static String findingId = ""; @@ -31,7 +34,6 @@ public static void setUp() { Region region = Region.US_EAST_1; guardDutyClient = GuardDutyClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -40,59 +42,36 @@ public static void setUp() { SecretValues values = gson.fromJson(json, SecretValues.class); detectorId = values.getDetectorId(); findingId = values.getFindingId(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * GuarddutyTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * // Populate the data members required for all tests. - * prop.load(input); - * detectorId = prop.getProperty("detectorId"); - * findingId = prop.getProperty("findingId"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void GetDetector() { + public void testGetDetector() { assertDoesNotThrow(() -> GetDetector.getSpecificDetector(guardDutyClient, detectorId)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void GetFindings() { + public void testGetFindings() { assertDoesNotThrow(() -> GetFindings.getSpecificFinding(guardDutyClient, findingId, detectorId)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListDetectors() { + public void testListDetectors() { assertDoesNotThrow(() -> ListDetectors.listAllDetectors(guardDutyClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } private static String getSecretValues() { // Get the Amazon RDS creds from Secrets Manager. SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/guarduty"; diff --git a/javav2/example_code/iam/pom.xml b/javav2/example_code/iam/pom.xml index 5bb9cce423d..c0eb3ba44f8 100644 --- a/javav2/example_code/iam/pom.xml +++ b/javav2/example_code/iam/pom.xml @@ -9,9 +9,9 @@ UTF-8 1.7.28 - 17 - 17 - 17 + 21 + 21 + 21 @@ -27,7 +27,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import @@ -93,20 +93,26 @@ software.amazon.awssdk ssooidc - - org.apache.logging.log4j - log4j-slf4j2-impl - software.amazon.awssdk accessanalyzer - + + org.apache.logging.log4j + log4j-core + org.slf4j - jcl-over-slf4j - ${slf4j.version} + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api diff --git a/javav2/example_code/iam/src/main/resources/log4j2.xml b/javav2/example_code/iam/src/main/resources/log4j2.xml index f212ad40e01..914470047e7 100644 --- a/javav2/example_code/iam/src/main/resources/log4j2.xml +++ b/javav2/example_code/iam/src/main/resources/log4j2.xml @@ -1,17 +1,17 @@ - + + + + - - - + + + + - - - - \ No newline at end of file diff --git a/javav2/example_code/iam/src/test/java/IAMServiceTest.java b/javav2/example_code/iam/src/test/java/IAMServiceTest.java index 973dffeb918..2ce2df5f47a 100644 --- a/javav2/example_code/iam/src/test/java/IAMServiceTest.java +++ b/javav2/example_code/iam/src/test/java/IAMServiceTest.java @@ -6,6 +6,9 @@ import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; @@ -25,7 +28,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class IAMServiceTest { - + private static final Logger logger = LoggerFactory.getLogger(IAMServiceTest.class); private static IamClient iam; private static String userName = ""; private static String policyName = ""; @@ -45,7 +48,6 @@ public static void setUp() { Region region = Region.AWS_GLOBAL; iam = IamClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -62,138 +64,103 @@ public static void setUp() { roleSessionName = values.getRoleName() + UUID.randomUUID();; fileLocationSc = values.getFileLocationSc(); bucketNameSc = values.getBucketNameSc(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * IAMServiceTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * prop.load(input); - * userName = prop.getProperty("userName"); - * policyName= prop.getProperty("policyName"); - * policyARN= prop.getProperty("policyARN"); - * roleName=prop.getProperty("roleName"); - * accountAlias=prop.getProperty("accountAlias"); - * usernameSc=prop.getProperty("usernameSc"); - * policyNameSc=prop.getProperty("policyNameSc"); - * roleNameSc=prop.getProperty("roleNameSc"); - * roleSessionName=prop.getProperty("roleSessionName"); - * fileLocationSc=prop.getProperty("fileLocationSc"); - * bucketNameSc=prop.getProperty("bucketNameSc"); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreatUser() { + public void testCreatUser() { String result = CreateUser.createIAMUser(iam, userName); assertFalse(result.isEmpty()); - System.out.println("\n Test 1 passed"); + logger.info("\n Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreatePolicy() { + public void testCreatePolicy() { policyARN = CreatePolicy.createIAMPolicy(iam, policyName); assertFalse(policyARN.isEmpty()); - System.out.println("\n Test 2 passed"); + logger.info("\n Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void CreateAccessKey() { + public void testCreateAccessKey() { keyId = CreateAccessKey.createIAMAccessKey(iam, userName); assertFalse(keyId.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } - - - - @Test @Tag("IntegrationTest") @Order(4) - public void GetPolicy() { + public void testGetPolicy() { assertDoesNotThrow(() -> GetPolicy.getIAMPolicy(iam, policyARN)); - System.out.println("Test 6 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListAccessKeys() { + public void testListAccessKeys() { assertDoesNotThrow(() -> ListAccessKeys.listKeys(iam, userName)); - System.out.println("Test 7 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ListUsers() { + public void testListUsers() { assertDoesNotThrow(() -> ListUsers.listAllUsers(iam)); - System.out.println("Test 8 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void CreateAccountAlias() { + public void testCreateAccountAlias() { assertDoesNotThrow(() -> CreateAccountAlias.createIAMAccountAlias(iam, accountAlias)); - System.out.println("Test 9 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void DeleteAccountAlias() { + public void testDeleteAccountAlias() { assertDoesNotThrow(() -> DeleteAccountAlias.deleteIAMAccountAlias(iam, accountAlias)); - System.out.println("Test 10 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void DeletePolicy() { + public void testDeletePolicy() { assertDoesNotThrow(() -> DeletePolicy.deleteIAMPolicy(iam, policyARN)); - System.out.println("Test 12 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void DeleteAccessKey() { + public void testDeleteAccessKey() { assertDoesNotThrow(() -> DeleteAccessKey.deleteKey(iam, userName, keyId)); - System.out.println("Test 12 passed"); + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void DeleteUser() { + public void testDeleteUser() { assertDoesNotThrow(() -> DeleteUser.deleteIAMUser(iam, userName)); - System.out.println("Test 13 passed"); + logger.info("Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void TestIAMScenario() throws Exception { + public void testIAMScenario() throws Exception { String DASHES = new String(new char[80]).replace("\0", "-"); System.out.println(DASHES); System.out.println(" 1. Create the IAM user."); @@ -249,12 +216,12 @@ public void TestIAMScenario() throws Exception { IAMScenario.deleteRole(iam, roleNameSc, polArn); IAMScenario.deleteIAMUser(iam, usernameSc); System.out.println(DASHES); + logger.info("Test 12 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/iam"; diff --git a/javav2/example_code/identitystore/pom.xml b/javav2/example_code/identitystore/pom.xml index c00b6550ef2..7c5f3f2d53f 100644 --- a/javav2/example_code/identitystore/pom.xml +++ b/javav2/example_code/identitystore/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -43,11 +50,20 @@ software.amazon.awssdk identitystore + + software.amazon.awssdk + secretsmanager + com.googlecode.json-simple json-simple 1.1.1 + + com.google.code.gson + gson + 2.10.1 + software.amazon.awssdk sso @@ -56,5 +72,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/identitystore/src/main/resources/log4j2.xml b/javav2/example_code/identitystore/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/identitystore/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java b/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java index bbb0c3f3d0b..a221cd02415 100644 --- a/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java +++ b/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java @@ -2,22 +2,26 @@ // SPDX-License-Identifier: Apache-2.0 import com.example.identitystore.*; +import com.google.gson.Gson; import org.junit.jupiter.api.*; + import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.identitystore.IdentitystoreClient; -import software.amazon.awssdk.services.identitystore.model.IdentitystoreException; -import software.amazon.awssdk.services.identitystore.model.Group; - +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import java.io.*; import java.util.*; -import java.util.concurrent.TimeUnit; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class IdentitystoreServiceTest { - + private static final Logger logger = LoggerFactory.getLogger(IdentitystoreServiceTest.class); private static IdentitystoreClient identitystore; private static String identitystoreId = ""; private static String groupName = ""; @@ -34,197 +38,242 @@ public static void setUp() throws IOException { identitystore = IdentitystoreClient.builder() .build(); - try (InputStream input = IdentitystoreServiceTest.class.getClassLoader() - .getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - prop.load(input); - // Populate the data members required for all tests - identitystoreId = prop.getProperty("identitystoreId"); - groupName = prop.getProperty("groupName"); - groupDesc = prop.getProperty("groupDesc"); - groupId = prop.getProperty("groupId"); - userName = prop.getProperty("userName"); - givenName = prop.getProperty("givenName"); - familyName = prop.getProperty("familyName"); - userId = prop.getProperty("userId"); - membershipId = prop.getProperty("membershipId"); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - } catch (IOException ex) { - ex.printStackTrace(); - } + Gson gson = new Gson(); + String json = getSecretValues(); + SecretValues values = gson.fromJson(json, SecretValues.class); + + // Populate the data members required for all tests + identitystoreId = values.getIdentitystoreId(); + groupName = values.getGroupName(); + groupDesc = values.getGroupDesc(); + userName = values.getUserName(); + givenName = values.getGivenName(); + familyName = values.getFamilyName(); } @Test + @Tag("IntegrationTest") @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(identitystore); - System.out.printf("\n Test 1 passed"); - } - - @Test - @Order(2) - public void CreateGroup() { + public void testCreateGroup() { String result2 = CreateGroup.createGroup(identitystore, identitystoreId, groupName, groupDesc); assertTrue(!result2.isEmpty()); - System.out.println("\n Test 2 passed"); + logger.info("\n Test 1 passed"); } @Test - @Order(3) - public void GetGroupId() { + @Tag("IntegrationTest") + @Order(2) + public void testGetGroupId() { groupId = GetGroupId.getGroupId(identitystore, identitystoreId, "DisplayName", groupName); assertTrue(!groupId.isEmpty()); - System.out.println("\n Test 3 passed"); + logger.info("\n Test 2 passed"); } @Test - @Order(4) - public void DescribeGroup() { + @Tag("IntegrationTest") + @Order(3) + public void testDescribeGroup() { String result4 = DescribeGroup.describeGroup(identitystore, identitystoreId, groupId); assertTrue(!result4.isEmpty()); - System.out.println("\n Test 4 passed"); + logger.info("\n Test 3 passed"); } @Test - @Order(5) - public void UpdateGroup() { + @Tag("IntegrationTest") + @Order(4) + public void testUpdateGroup() { String result5 = UpdateGroup.updateGroup(identitystore, identitystoreId, groupId, "Description", "TestingUpdateAPI"); assertTrue(!result5.isEmpty()); - System.out.println("\n Test 5 passed"); + logger.info("\n Test 4 passed"); } @Test - @Order(6) - public void ListGroups() { + @Tag("IntegrationTest") + @Order(5) + public void testListGroups() { int result6 = ListGroups.listGroups(identitystore, identitystoreId); assertTrue(result6 >= 0); - System.out.println("\n Test 6 passed"); + logger.info("\n Test 5 passed"); } @Test - @Order(7) - public void CreateUser() { + @Tag("IntegrationTest") + @Order(6) + public void testCreateUser() { String result7 = CreateUser.createUser(identitystore, identitystoreId, userName, givenName, familyName); assertTrue(!result7.isEmpty()); - System.out.println("\n Test 7 passed"); + logger.info("\n Test 6 passed"); } @Test - @Order(8) - public void GetUserId() { + @Tag("IntegrationTest") + @Order(7) + public void testGetUserId() { userId = GetUserId.getUserId(identitystore, identitystoreId, "UserName", userName); assertTrue(!userId.isEmpty()); - System.out.println("\n Test 8 passed"); + logger.info("\n Test 7 passed"); } @Test - @Order(9) - public void DescribeUser() { + @Tag("IntegrationTest") + @Order(8) + public void testDescribeUser() { String result9 = DescribeUser.describeUser(identitystore, identitystoreId, userId); assertTrue(!result9.isEmpty()); - System.out.println("\n Test 9 passed"); + logger.info("\n Test 8 passed"); } @Test - @Order(10) - public void UpdateUser() { + @Tag("IntegrationTest") + @Order(9) + public void testUpdateUser() { String result10 = UpdateUser.updateUser(identitystore, identitystoreId, userId, "displayName", "TestingUpdateAPI"); assertTrue(!result10.isEmpty()); - System.out.println("\n Test 10 passed"); + logger.info("\n Test 9 passed"); } @Test - @Order(11) - public void ListUsers() { + @Tag("IntegrationTest") + @Order(10) + public void testListUsers() { int result11 = ListUsers.listUsers(identitystore, identitystoreId); assertTrue(result11 >= 0); - System.out.println("\n Test 11 passed"); + logger.info("\n Test 10 passed"); } @Test - @Order(12) - public void CreateGroupMembership() { + @Tag("IntegrationTest") + @Order(11) + public void testCreateGroupMembership() { String result12 = CreateGroupMembership.createGroupMembership(identitystore, identitystoreId, groupId, userId); assertTrue(!result12.isEmpty()); - System.out.println("\n Test 12 passed"); + logger.info("\n Test 11 passed"); } @Test - @Order(13) - public void GetGroupMembershipId() { + @Tag("IntegrationTest") + @Order(12) + public void testGetGroupMembershipId() { membershipId = GetGroupMembershipId.getGroupMembershipId(identitystore, identitystoreId, groupId, userId); assertTrue(!membershipId.isEmpty()); - System.out.println("\n Test 13 passed"); + logger.info("\n Test 12 passed"); } @Test - @Order(14) - public void DescribeGroupMembership() { + @Tag("IntegrationTest") + @Order(13) + public void testDescribeGroupMembership() { String result14 = DescribeGroupMembership.describeGroupMembershipId(identitystore, identitystoreId, membershipId); assertTrue(!result14.isEmpty()); - System.out.println("\n Test 14 passed"); + logger.info("\n Test 13 passed"); } @Test - @Order(15) - public void IsMemberInGroups() { + @Tag("IntegrationTest") + @Order(14) + public void testIsMemberInGroups() { List groupIdList = new ArrayList<>(); groupIdList.add(groupId); String result15 = IsMemberInGroups.isMemberInGroups(identitystore, identitystoreId, userId, groupIdList); assertTrue(!result15.isEmpty()); - System.out.println("\n Test 15 passed"); + logger.info("\n Test 14 passed"); } @Test - @Order(16) - public void ListGroupMemberships() { + @Tag("IntegrationTest") + @Order(15) + public void testListGroupMemberships() { int result16 = ListGroupMemberships.listGroupMemberships(identitystore, identitystoreId, groupId); assertTrue(result16 >= 0); - System.out.println("\n Test 16 passed"); + logger.info("\n Test 15 passed"); } @Test - @Order(17) - public void ListGroupMembershipsForMember() { + @Tag("IntegrationTest") + @Order(16) + public void testListGroupMembershipsForMember() { int result17 = ListGroupMembershipsForMember.listGroupMembershipsForMember(identitystore, identitystoreId, userId); assertTrue(result17 >= 0); - System.out.println("\n Test 17 passed"); + logger.info("\n Test 16 passed"); } @Test - @Order(18) - public void DeleteGroupMembership() { + @Tag("IntegrationTest") + @Order(17) + public void testDeleteGroupMembership() { String result18 = DeleteGroupMembership.deleteGroupMembership(identitystore, identitystoreId, membershipId); assertTrue(!result18.isEmpty()); - System.out.println("\n Test 18 passed"); + logger.info("\n Test 17 passed"); } @Test - @Order(19) - public void DeleteUser() { - + @Tag("IntegrationTest") + @Order(18) + public void testDeleteUser() { String result19 = DeleteUser.deleteUser(identitystore, identitystoreId, userId); assertTrue(!result19.isEmpty()); - System.out.println("\n Test 19 passed"); + logger.info("\n Test 18 passed"); } @Test - @Order(20) - public void DeleteGroup() { - + @Tag("IntegrationTest") + @Order(19) + public void testDeleteGroup() { String result20 = DeleteGroup.deleteGroup(identitystore, identitystoreId, groupId); assertTrue(!result20.isEmpty()); - System.out.println("\n Test 20 passed"); + logger.info("\n Test 19 passed"); } + private static String getSecretValues() { + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .build(); + String secretName = "test/identitystore"; + + GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() + .secretId(secretName) + .build(); + + GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); + return valueResponse.secretString(); + } + + @Nested + @DisplayName("A class used to get test values from test/firehose (an AWS Secrets Manager secret)") + class SecretValues { + private String identitystoreId; + private String groupName; + private String groupDesc; + private String userName; + private String givenName; + private String familyName; + + public String getIdentitystoreId() { + return identitystoreId; + } + + public String getGroupName() { + return groupName; + } + + public String getGroupDesc() { + return groupDesc; + } + + public String getUserName() { + return userName; + } + + public String getGivenName() { + return givenName; + } + + public String getFamilyName() { + return familyName; + } + } } diff --git a/javav2/example_code/iot/pom.xml b/javav2/example_code/iot/pom.xml index 5862b9c2a1e..6999c1c4c37 100644 --- a/javav2/example_code/iot/pom.xml +++ b/javav2/example_code/iot/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -81,5 +88,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/iot/src/main/java/com/example/iot/scenario/IotActions.java b/javav2/example_code/iot/src/main/java/com/example/iot/scenario/IotActions.java index a25ab0d6e40..44b754ef48b 100644 --- a/javav2/example_code/iot/src/main/java/com/example/iot/scenario/IotActions.java +++ b/javav2/example_code/iot/src/main/java/com/example/iot/scenario/IotActions.java @@ -82,7 +82,6 @@ private static IotDataPlaneAsyncClient getAsyncDataPlaneClient() { .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return iotAsyncDataPlaneClient; @@ -110,7 +109,6 @@ private static IotAsyncClient getAsyncClient() { .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return iotAsyncClient; diff --git a/javav2/example_code/iot/src/main/resources/log4j2.xml b/javav2/example_code/iot/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/iot/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/iot/src/test/java/IoTTests.java b/javav2/example_code/iot/src/test/java/IoTTests.java index a4adf9787a4..2ac8dd08641 100644 --- a/javav2/example_code/iot/src/test/java/IoTTests.java +++ b/javav2/example_code/iot/src/test/java/IoTTests.java @@ -14,6 +14,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iot.IotClient; @@ -29,15 +31,12 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class IoTTests { - + private static final Logger logger = LoggerFactory.getLogger(IoTTests.class); private static IotClient iotClient; private static String thingName = "foo" ; private static String queryString = "thingName:" ; - private static String ruleName = "rule"; - private static String roleARN = "" ; - private static String snsAction = "" ; @BeforeAll @@ -59,28 +58,6 @@ public static void setUp() throws IOException { SecretValues values = gson.fromJson(json, SecretValues.class); roleARN = values.getRoleARN(); snsAction = values.getSnsAction(); - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - - /* - try (InputStream input = IoTTests.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - thingName = prop.getProperty("thingName"); - roleARN = prop.getProperty("roleARN"); - ruleName = prop.getProperty("ruleName"); - snsAction = prop.getProperty("snsAction"); - queryString = "thingName:"+thingName+""; - - } catch (IOException ex) { - ex.printStackTrace(); - } - - */ } @Test @@ -89,7 +66,7 @@ public static void setUp() throws IOException { public void testHello() { assertDoesNotThrow(() -> HelloIoT.listAllThings(iotClient), "Failed to list your things."); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @@ -97,7 +74,6 @@ public void testHello() { @Order(2) public void testIotScenario() throws InterruptedException { IotActions iotActions = new IotActions(); - assertDoesNotThrow(() -> iotActions.createIoTThing(thingName), "Failed to create your thing in the scenario."); @@ -143,13 +119,12 @@ public void testIotScenario() throws InterruptedException { assertDoesNotThrow(() -> iotActions.deleteIoTThing(thingName), "Failed to delete your thing in the scenario."); - System.out.println("Scenario test passed"); + logger.info("Scenario IoT test passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/iot"; diff --git a/javav2/example_code/iotsitewise/pom.xml b/javav2/example_code/iotsitewise/pom.xml index ce7da2101c6..82be5bc9329 100644 --- a/javav2/example_code/iotsitewise/pom.xml +++ b/javav2/example_code/iotsitewise/pom.xml @@ -3,14 +3,13 @@ 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"> 4.0.0 - org.example iotsitewise 1.0-SNAPSHOT - - 17 - 17 + 21 + 21 + 21 UTF-8 @@ -37,7 +36,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/iotsitewise/src/main/resources/log4j2.xml b/javav2/example_code/iotsitewise/src/main/resources/log4j2.xml index 225afe2b3a8..914470047e7 100644 --- a/javav2/example_code/iotsitewise/src/main/resources/log4j2.xml +++ b/javav2/example_code/iotsitewise/src/main/resources/log4j2.xml @@ -3,7 +3,6 @@ - diff --git a/javav2/example_code/iotsitewise/src/test/java/SitewiseTests.java b/javav2/example_code/iotsitewise/src/test/java/SitewiseTests.java index c59e652473d..0f8efe85353 100644 --- a/javav2/example_code/iotsitewise/src/test/java/SitewiseTests.java +++ b/javav2/example_code/iotsitewise/src/test/java/SitewiseTests.java @@ -15,6 +15,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iotsitewise.model.CreateAssetModelResponse; @@ -34,7 +36,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SitewiseTests { - + private static final Logger logger = LoggerFactory.getLogger(SitewiseTests.class); private static final String assetModelName = "MyAssetModel" + UUID.randomUUID(); private static final String assetName = "MyAsset"; @@ -81,6 +83,7 @@ public static void setUp() { @Order(1) public void testHelloService() { assertDoesNotThrow(HelloSitewise::fetchAssetModels); + logger.info("Test 1 passed"); } @Test @@ -97,6 +100,7 @@ public void testCreateAssetModel() { assetModelId = response.assetModelId(); assertNotNull(assetModelId); }); + logger.info("Test 2 passed"); } @Test @@ -110,6 +114,7 @@ public void testCreateAsset() throws InterruptedException { assetId = response.assetId(); assertNotNull(assetId); }); + logger.info("Test 3 passed"); } @Test @@ -119,10 +124,11 @@ public void testGetPropIds() { assertDoesNotThrow(() -> { propertyIds = sitewiseActions.getPropertyIds(assetModelId).join(); humPropId = propertyIds.get("Humidity"); - System.out.println("The Humidity property Id is " + humPropId); + logger.info("The Humidity property Id is " + humPropId); tempPropId = propertyIds.get("Temperature"); - System.out.println("The Temperature property Id is " + tempPropId); + logger.info("The Temperature property Id is " + tempPropId); }); + logger.info("Test 4 passed"); } @Test @@ -132,6 +138,7 @@ public void testSendProps() { assertDoesNotThrow(() -> { sitewiseActions.sendDataToSiteWiseAsync(assetId, tempPropId, humPropId).join(); }); + logger.info("Test 5 passed"); } @Test @@ -141,6 +148,7 @@ public void testGETHumValue() { assertDoesNotThrow(() -> { sitewiseActions.getAssetPropValueAsync(humPropId, assetId); }); + logger.info("Test 6 passed"); } @Test @@ -151,6 +159,7 @@ public void testCreatePortal() { portalId = sitewiseActions.createPortalAsync(portalName, iamRole, contactEmail).join(); assertNotNull(portalId); }); + logger.info("Test 7 passed"); } @Test @@ -161,6 +170,7 @@ public void testDescribePortal() { String portalUrl = sitewiseActions.describePortalAsync(portalId).join(); assertNotNull(portalUrl); }); + logger.info("Test 8 passed"); } @Test @@ -171,6 +181,7 @@ public void testCreateGateway() { gatewayId = sitewiseActions.createGatewayAsync(gatewayName, myThing).join(); assertNotNull(gatewayId); }); + logger.info("Test 9 passed"); } @Test @@ -180,6 +191,7 @@ public void testDescribeGateway() { assertDoesNotThrow(() -> { sitewiseActions.describeGatewayAsync(gatewayId).join(); }); + logger.info("Test 10 passed"); } @Test @@ -190,6 +202,7 @@ public void testDeletePortal() throws InterruptedException { assertDoesNotThrow(() -> { sitewiseActions.deletePortalAsync(portalId).join(); }); + logger.info("Test 11 passed"); } @Test @@ -200,22 +213,24 @@ public void testDeleteAsset() throws InterruptedException { assertDoesNotThrow(() -> { sitewiseActions.deleteAssetAsync(assetId).join(); }); + logger.info("Test 12 passed"); } + @Test @Tag("IntegrationTest") - @Order(12) + @Order(13) public void testDeleteAssetModel() throws InterruptedException { Thread.sleep(30000); assertDoesNotThrow(() -> { sitewiseActions.deleteAssetModelAsync(assetModelId).join(); }); CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK); + logger.info("Test 13 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/sitewise"; diff --git a/javav2/example_code/kendra/pom.xml b/javav2/example_code/kendra/pom.xml index 25837e27e24..12f673bc0cc 100644 --- a/javav2/example_code/kendra/pom.xml +++ b/javav2/example_code/kendra/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -83,5 +90,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/kendra/src/main/resources/log4j2.xml b/javav2/example_code/kendra/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/kendra/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/kendra/src/test/java/KendraTest.java b/javav2/example_code/kendra/src/test/java/KendraTest.java index 81ae4567a16..96b6abcf101 100644 --- a/javav2/example_code/kendra/src/test/java/KendraTest.java +++ b/javav2/example_code/kendra/src/test/java/KendraTest.java @@ -4,6 +4,8 @@ import com.example.kendra.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kendra.KendraClient; @@ -20,7 +22,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class KendraTest { - + private static final Logger logger = LoggerFactory.getLogger(KendraTest.class); private static KendraClient kendra; private static String indexName = ""; private static String indexDescription = ""; @@ -37,7 +39,6 @@ public class KendraTest { public static void setUp() { kendra = KendraClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -52,101 +53,70 @@ public static void setUp() { dataSourceDescription = values.getDataSourceDescription(); dataSourceRoleArn = values.getDataSourceRoleArn(); text = values.getText(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * KendraTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Load a properties file from the class path. - * prop.load(input); - * - * // Populate the data members required for all tests. - * indexName = prop.getProperty("indexName")+ java.util.UUID.randomUUID(); - * indexRoleArn = prop.getProperty("indexRoleArn"); - * indexDescription = prop.getProperty("indexDescription"); - * s3BucketName = prop.getProperty("s3BucketName"); - * dataSourceName = prop.getProperty("dataSourceName"); - * dataSourceDescription = prop.getProperty("dataSourceDescription"); - * dataSourceRoleArn = prop.getProperty("dataSourceRoleArn"); - * text = prop.getProperty("text"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateIndex() { + public void testCreateIndex() { indexId = CreateIndexAndDataSourceExample.createIndex(kendra, indexDescription, indexName, indexRoleArn); assertFalse(indexId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateDataSource() { + public void testCreateDataSource() { dataSourceId = CreateIndexAndDataSourceExample.createDataSource(kendra, s3BucketName, dataSourceName, dataSourceDescription, indexId, dataSourceRoleArn); assertFalse(dataSourceId.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void SyncDataSource() { + public void testSyncDataSource() { assertDoesNotThrow(() -> CreateIndexAndDataSourceExample.startDataSource(kendra, indexId, dataSourceId)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListSyncJobs() { + public void testListSyncJobs() { assertDoesNotThrow(() -> ListDataSourceSyncJobs.listSyncJobs(kendra, indexId, dataSourceId)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void QueryIndex() { + public void testQueryIndex() { assertDoesNotThrow(() -> QueryIndex.querySpecificIndex(kendra, indexId, text)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteDataSource() { + public void testDeleteDataSource() { assertDoesNotThrow(() -> DeleteDataSource.deleteSpecificDataSource(kendra, indexId, dataSourceId)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteIndex() { + public void testDeleteIndex() { assertDoesNotThrow(() -> DeleteIndex.deleteSpecificIndex(kendra, indexId)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/kendra"; diff --git a/javav2/example_code/keyspaces/pom.xml b/javav2/example_code/keyspaces/pom.xml index 239b97c14a9..581cb327f17 100644 --- a/javav2/example_code/keyspaces/pom.xml +++ b/javav2/example_code/keyspaces/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -79,5 +86,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/keyspaces/src/main/resources/log4j2.xml b/javav2/example_code/keyspaces/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/keyspaces/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java b/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java index d922289e3b5..c71ef363bb0 100644 --- a/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java +++ b/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java @@ -4,6 +4,8 @@ import com.example.keyspace.HelloKeyspaces; import org.junit.jupiter.api.Tag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; @@ -19,22 +21,21 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class KeyspaceTest { private static KeyspacesClient keyClient; - + private static final Logger logger = LoggerFactory.getLogger(KeyspaceTest.class); @BeforeAll public static void setUp() { Region region = Region.US_EAST_1; keyClient = KeyspacesClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } @Test @Tag("IntegrationTest") @Order(1) - public void KeyspaceTest() { + public void testKeyspaceTest() { assertDoesNotThrow(() -> HelloKeyspaces.listKeyspaces(keyClient), "Failed to list namespaces."); - System.out.println("Test passed"); + logger.info("Test 1 passed"); } } diff --git a/javav2/example_code/kinesis/pom.xml b/javav2/example_code/kinesis/pom.xml index 5b9e26ded78..473f2e6d74e 100644 --- a/javav2/example_code/kinesis/pom.xml +++ b/javav2/example_code/kinesis/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -71,11 +78,6 @@ jackson-databind 2.14.2 - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk kinesis @@ -98,5 +100,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/kinesis/src/main/resources/log4j2.xml b/javav2/example_code/kinesis/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/kinesis/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/kinesis/src/test/java/KinTest.java b/javav2/example_code/kinesis/src/test/java/KinTest.java index 906158fd909..ee3c77951c1 100644 --- a/javav2/example_code/kinesis/src/test/java/KinTest.java +++ b/javav2/example_code/kinesis/src/test/java/KinTest.java @@ -4,7 +4,8 @@ import com.example.kinesis.CreateDataStream; import com.example.kinesis.DescribeLimits; import org.junit.jupiter.api.*; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import com.example.kinesis.*; @@ -14,6 +15,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class KinTest { + private static final Logger logger = LoggerFactory.getLogger(KinTest.class); private static KinesisClient kinesisClient; private static String streamName = ""; @@ -21,7 +23,6 @@ public class KinTest { public static void setUp() { kinesisClient = KinesisClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); streamName = "streamName" + java.util.UUID.randomUUID(); } @@ -29,23 +30,23 @@ public static void setUp() { @Test @Tag("IntegrationTest") @Order(1) - public void CreateDataStream() { + public void testCreateDataStream() { assertDoesNotThrow(() -> CreateDataStream.createStream(kinesisClient, streamName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeLimits() { + public void testDescribeLimits() { assertDoesNotThrow(() -> DescribeLimits.describeKinLimits(kinesisClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListShards() { + public void testListShards() { try { // Wait 60 secs for table to complete TimeUnit.SECONDS.sleep(60); @@ -54,30 +55,30 @@ public void ListShards() { System.err.println(e.getMessage()); System.exit(1); } - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void PutRecords() { + public void testPutRecords() { assertDoesNotThrow(() -> StockTradesWriter.setStockData(kinesisClient, streamName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void GetRecords() { + public void testGetRecords() { assertDoesNotThrow(() -> GetRecords.getStockTrades(kinesisClient, streamName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteDataStreem() { + public void testDeleteDataStreem() { assertDoesNotThrow(() -> DeleteDataStream.deleteStream(kinesisClient, streamName)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } } diff --git a/javav2/example_code/kms/pom.xml b/javav2/example_code/kms/pom.xml index 60adc70d73b..3bc957bd29a 100644 --- a/javav2/example_code/kms/pom.xml +++ b/javav2/example_code/kms/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/scenario/KMSActions.java b/javav2/example_code/kms/src/main/java/com/example/kms/scenario/KMSActions.java index 45ce986bf01..c41becd55f4 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/scenario/KMSActions.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/scenario/KMSActions.java @@ -103,7 +103,6 @@ private static KmsAsyncClient getAsyncClient() { kmsAsyncClient = KmsAsyncClient.builder() .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return kmsAsyncClient; diff --git a/javav2/example_code/kms/src/main/resources/log4j2.xml b/javav2/example_code/kms/src/main/resources/log4j2.xml index 225afe2b3a8..914470047e7 100644 --- a/javav2/example_code/kms/src/main/resources/log4j2.xml +++ b/javav2/example_code/kms/src/main/resources/log4j2.xml @@ -3,7 +3,6 @@ - diff --git a/javav2/example_code/kms/src/test/java/AmazonKMSTest.java b/javav2/example_code/kms/src/test/java/AmazonKMSTest.java index 3a8e22ed042..50da859e278 100644 --- a/javav2/example_code/kms/src/test/java/AmazonKMSTest.java +++ b/javav2/example_code/kms/src/test/java/AmazonKMSTest.java @@ -4,6 +4,8 @@ import com.example.kms.*; import com.example.kms.scenario.KMSActions; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import org.junit.jupiter.api.*; @@ -23,6 +25,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonKMSTest { + private static final Logger logger = LoggerFactory.getLogger(AmazonKMSTest.class); private static String granteePrincipal = ""; private static String accountId = ""; @@ -42,7 +45,7 @@ public static void setUp() { @Order(1) public void HelloKMS() { assertDoesNotThrow(HelloKMS::listAllKeys); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @@ -84,13 +87,12 @@ public void testKMSActionsIntegration() { assertDoesNotThrow(() -> kmsActions.deleteKeyAsync(targetKeyId).join()); } - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/kms"; diff --git a/javav2/example_code/lambda/pom.xml b/javav2/example_code/lambda/pom.xml index 323d8eba00f..901f4d31049 100644 --- a/javav2/example_code/lambda/pom.xml +++ b/javav2/example_code/lambda/pom.xml @@ -9,9 +9,9 @@ 1.0 UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -75,5 +82,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/lambda/src/main/resources/log4j2.xml b/javav2/example_code/lambda/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/lambda/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/lambda/src/test/java/LambdaTest.java b/javav2/example_code/lambda/src/test/java/LambdaTest.java index 32e19324bd5..cf23bbcd697 100644 --- a/javav2/example_code/lambda/src/test/java/LambdaTest.java +++ b/javav2/example_code/lambda/src/test/java/LambdaTest.java @@ -7,6 +7,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.lambda.LambdaClient; import org.junit.jupiter.api.TestInstance; @@ -30,6 +32,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class LambdaTest { + private static final Logger logger = LoggerFactory.getLogger(LambdaTest.class); private static LambdaClient awsLambda; private static String functionName = ""; private static String functionNameSc = ""; @@ -42,8 +45,7 @@ public class LambdaTest { @BeforeAll public static void setUp() { awsLambda = LambdaClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -62,15 +64,15 @@ public static void setUp() { @Test @Tag("IntegrationTest") @Order(1) - public void GetAccountSettings() { + public void testGetAccountSettings() { assertDoesNotThrow(() -> GetAccountSettings.getSettings(awsLambda)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void LambdaScenario() throws InterruptedException { + public void testLambdaScenario() throws InterruptedException { String funArn = LambdaScenario.createLambdaFunction(awsLambda, functionNameSc, key, bucketName, role, handler); assertFalse(funArn.isEmpty()); System.out.println("The function ARN is " + funArn); @@ -98,12 +100,12 @@ public void LambdaScenario() throws InterruptedException { System.out.println("Delete the AWS Lambda function."); assertDoesNotThrow(() -> LambdaScenario.deleteLambdaFunction(awsLambda, functionNameSc)); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/lambda"; diff --git a/javav2/example_code/lex/pom.xml b/javav2/example_code/lex/pom.xml index 17daa4a9765..a119d94ec0e 100644 --- a/javav2/example_code/lex/pom.xml +++ b/javav2/example_code/lex/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/lex/src/main/resources/log4j2.xml b/javav2/example_code/lex/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/lex/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/lex/src/test/java/AmazonLexTest.java b/javav2/example_code/lex/src/test/java/AmazonLexTest.java index b4edc9e5b80..c632ad69fee 100644 --- a/javav2/example_code/lex/src/test/java/AmazonLexTest.java +++ b/javav2/example_code/lex/src/test/java/AmazonLexTest.java @@ -4,6 +4,8 @@ import com.example.lex.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lexmodelbuilding.LexModelBuildingClient; @@ -20,7 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonLexTest { - + private static final Logger logger = LoggerFactory.getLogger(AmazonLexTest.class); private static LexModelBuildingClient lexClient; private static String botName = ""; private static String intentName = ""; @@ -30,7 +32,6 @@ public class AmazonLexTest { public static void setUp() { lexClient = LexModelBuildingClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -40,84 +41,59 @@ public static void setUp() { botName = values.getBotName(); intentName = values.getIntentName(); intentVersion = values.getIntentVersion(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * AmazonLexTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * botName = prop.getProperty("botName"); - * intentName = prop.getProperty("intentName"); - * intentVersion = prop.getProperty("intentVersion"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void PutBot() { + public void testPutBot() { assertDoesNotThrow(() -> PutBot.createBot(lexClient, botName, intentName, intentVersion)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void GetBots() { + public void testGetBots() { assertDoesNotThrow(() -> GetBots.getAllBots(lexClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetIntent() { + public void testGetIntent() { assertDoesNotThrow(() -> GetIntent.getSpecificIntent(lexClient, intentName, intentVersion)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void GetSlotTypes() { + public void testGetSlotTypes() { assertDoesNotThrow(() -> GetSlotTypes.getSlotsInfo(lexClient)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void GetBotStatus() { + public void testGetBotStatus() { assertDoesNotThrow(() -> GetBotStatus.getStatus(lexClient, botName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteBot() { + public void testDeleteBot() { assertDoesNotThrow(() -> DeleteBot.deleteSpecificBot(lexClient, botName)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/lex"; diff --git a/javav2/example_code/lookoutvision/pom.xml b/javav2/example_code/lookoutvision/pom.xml index cb813cf738f..56a662249f4 100644 --- a/javav2/example_code/lookoutvision/pom.xml +++ b/javav2/example_code/lookoutvision/pom.xml @@ -6,9 +6,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -33,7 +33,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -46,11 +53,6 @@ 5.11.4 test - - org.slf4j - slf4j-log4j12 - 1.7.25 - com.fasterxml.jackson.core jackson-core @@ -92,5 +94,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/lookoutvision/src/main/resources/config.properties b/javav2/example_code/lookoutvision/src/main/resources/config.properties index 9bdccd859c0..efd5e2b2ccd 100644 --- a/javav2/example_code/lookoutvision/src/main/resources/config.properties +++ b/javav2/example_code/lookoutvision/src/main/resources/config.properties @@ -1,9 +1,26 @@ -projectName = -modelDescription = -modelTrainingOutputBucket = -modelTrainingOutputFolder = -manifestFile = -modelPackageJobJsonFile = -photo = -anomalousPhoto = -anomalyLabel = < The label for an anomaly in the project. > \ No newline at end of file +# The name of the project to create in the tests. +projectName = MyLookoutVisionProject + +# A description for the model. +modelDescription = Model to detect anomalies in manufacturing images + +# The Amazon S3 bucket in which to place the training results. +modelTrainingOutputBucket = my-lookoutvision-training-results + +# The folder in modelTrainingOutputBucket in which to place the training results. +modelTrainingOutputFolder = training-output + +# The location of a local manifest file that is used to populate the training dataset. +manifestFile = /path/to/training/manifest.json + +# The location of the edge packaging Job request JSON. Use the template JSON files in ./src/main/resources/ +modelPackageJobJsonFile = /path/to/edge-packaging-job.json + +# The location of a normal image to analyze with the trained model. +photo = /path/to/normal-image.jpg + +# The location of an anomalous image to analyze with the trained model. +anomalousPhoto = /path/to/anomalous-image.jpg + +# The label for an anomaly in the project. +anomalyLabel = defect \ No newline at end of file diff --git a/javav2/example_code/lookoutvision/src/main/resources/log4j2.xml b/javav2/example_code/lookoutvision/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/lookoutvision/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java b/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java index be523d30810..daa0dfc9223 100644 --- a/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java +++ b/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java @@ -8,22 +8,15 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.lookoutvision.LookoutVisionClient; import software.amazon.awssdk.services.lookoutvision.model.DatasetDescription; import software.amazon.awssdk.services.lookoutvision.model.DatasetStatus; -import software.amazon.awssdk.services.lookoutvision.model.DetectAnomalyResult; import software.amazon.awssdk.services.lookoutvision.model.LookoutVisionException; -import software.amazon.awssdk.services.lookoutvision.model.ModelDescription; import software.amazon.awssdk.services.lookoutvision.model.ModelMetadata; -import software.amazon.awssdk.services.lookoutvision.model.ModelPackagingDescription; -import software.amazon.awssdk.services.lookoutvision.model.ModelPackagingJobMetadata; -import software.amazon.awssdk.services.lookoutvision.model.ModelPackagingJobStatus; -import software.amazon.awssdk.services.lookoutvision.model.ModelStatus; import software.amazon.awssdk.services.lookoutvision.model.ProjectMetadata; -import software.amazon.awssdk.services.lookoutvision.model.Tag; - import java.io.*; import java.time.Instant; import java.util.List; @@ -32,29 +25,16 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class LookoutVisionTest { - + private static final Logger logger = LoggerFactory.getLogger(LookoutVisionTest.class); private static LookoutVisionClient lfvClient; - private static String projectName = ""; - private static String modelDescription = ""; private static String modelVersion = ""; - private static String modelTrainingOutputBucket = ""; - private static String modelTrainingOutputFolder = ""; - private static String photo = ""; - private static String anomalousPhoto = ""; - private static String anomalyLabel = ""; private static String datasetType = ""; - private static String manifestFile = ""; - private static String jobName = ""; - private static String modelPackageJobJsonFile = ""; @BeforeAll public static void setUp() throws IOException { - try (InputStream input = LookoutVisionTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { System.out.println("Sorry, unable to find config.properties"); return; @@ -63,15 +43,7 @@ public static void setUp() throws IOException { // Load the properties file. prop.load(input); projectName = prop.getProperty("projectName"); - modelDescription = prop.getProperty("modelDescription"); - modelTrainingOutputBucket = prop.getProperty("modelTrainingOutputBucket"); - modelTrainingOutputFolder = prop.getProperty("modelTrainingOutputFolder"); - photo = prop.getProperty("photo"); - anomalousPhoto = prop.getProperty("anomalousPhoto"); - anomalyLabel = prop.getProperty("anomalyLabel"); - manifestFile = prop.getProperty("manifestFile"); // jobName = prop.getProperty("jobName"); - modelPackageJobJsonFile = prop.getProperty("modelPackageJobJsonFile"); /* * To complete tests, the model version must be 1 (Lookout For Vision assigns @@ -92,39 +64,28 @@ public static void setUp() throws IOException { } @Test + @Tag("IntegrationTest") @Order(1) - public void whenInitializingAWSRekognitionService_thenNotNull() { - assertNotNull(lfvClient); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) public void createProjectPanel_thenNotNull() throws IOException, LookoutVisionException { - ProjectMetadata project = Projects.createProject(lfvClient, projectName); - assertEquals(projectName, project.projectName()); - System.out.println("Test 2 passed"); - + logger.info("Test 1 passed"); } @Test - @Order(3) + @Tag("IntegrationTest") + @Order(2) public void listProjects_thenNotNull() throws IOException, LookoutVisionException { - List projects = Projects.listProjects(lfvClient); assertNotNull(projects); - System.out.println("Test 3 passed"); - + logger.info("Test 2 passed"); } @Test - @Order(4) + @Tag("IntegrationTest") + @Order(3) public void createEmptyDataset_thenEqual() throws IOException, LookoutVisionException, InterruptedException { - try { - // Create empty dataset. DatasetDescription dataset = Datasets.createDataset(lfvClient, projectName, datasetType, null, null); @@ -132,30 +93,15 @@ public void createEmptyDataset_thenEqual() throws IOException, LookoutVisionExce assertEquals(DatasetStatus.CREATE_COMPLETE, dataset.status()); } catch (LookoutVisionException e) { - assertEquals("ResourceNotFoundException", e.awsErrorDetails().errorCode()); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } - - } - - @Test - @Order(5) - public void updateEmptyDataset_thenEquals() throws IOException, LookoutVisionException, InterruptedException { - - // Update dataset with local manifest file. - DatasetStatus dataset = Datasets.updateDatasetEntries(lfvClient, projectName, - datasetType, manifestFile); - - assertEquals(DatasetStatus.UPDATE_COMPLETE, dataset); - System.out.println("Test 5 passed"); - } @Test - @Order(6) + @Tag("IntegrationTest") + @Order(4) public void listDatasetEntries_thenNotNull() throws LookoutVisionException { - String sourceRef = null; String classification = null; Instant afterCreationDate = null; @@ -165,254 +111,41 @@ public void listDatasetEntries_thenNotNull() throws LookoutVisionException { // Get JSON lines from dataset. List jsonLines = Datasets.listDatasetEntries(lfvClient, projectName, datasetType, sourceRef, classification, labeled, beforeCreationDate, afterCreationDate); - assertNotNull(jsonLines); - System.out.println("Test 6 passed"); - + logger.info("Test 4 passed"); } @Test - @Order(7) + @Tag("IntegrationTest") + @Order(5) public void describeDataset_thenEquals() throws IOException, LookoutVisionException { - // Describe a dataset. DatasetDescription datasetDescription = Datasets.describeDataset(lfvClient, projectName, datasetType); - // Check that a description is returned with the right project name and dataset // type. assertEquals(datasetDescription.projectName(), projectName); assertEquals(datasetDescription.datasetType(), datasetType); - System.out.println("Test 7 passed"); - + logger.info("Test 5 passed"); } @Test - @Order(8) - public void createModel_thenEqual() throws IOException, LookoutVisionException, InterruptedException { - - // Create and train the model. - ModelDescription model = Models.createModel(lfvClient, projectName, modelDescription, - modelTrainingOutputBucket, modelTrainingOutputFolder); - - assertEquals(ModelStatus.TRAINED, model.status()); - System.out.println("Test 8 passed"); - - } - - @Test - @Order(9) - public void tagModel_thenNotEquals() throws IOException, LookoutVisionException { - - String key = "TestTagkey1"; - String value = "TestTagKeyValue1"; - - Tag tag = Tag.builder() - .key(key) - .value(value) - .build(); - - // Describe a model. - Models.tagModel(lfvClient, projectName, modelVersion, - key, value); - - List tags = Models.listTagsForModel(lfvClient, - projectName, modelVersion); - - int index = tags.indexOf(tag); - - assertNotEquals(-1, index); - - System.out.println("Test 9 passed"); - - } - - @Test - @Order(10) - public void listModelTags_thenNotFalse() throws LookoutVisionException { - - // Get JSON lines from dataset. - List tags = Models.listTagsForModel(lfvClient, projectName, modelVersion); - - assertEquals(false, tags.isEmpty()); - System.out.println("Test 10 passed"); - - } - - @Test - @Order(11) - public void untagModel_thenEquals() throws IOException, LookoutVisionException { - - String key = "TestTagkey1"; - String value = "TestTagKeyValue1"; - - Tag tag = Tag.builder() - .key(key) - .value(value) - .build(); - - // Describe a model. - Models.untagModel(lfvClient, projectName, modelVersion, - key); - - List tags = Models.listTagsForModel(lfvClient, - projectName, modelVersion); - - int index = tags.indexOf(tag); - - assertEquals(-1, index); - - System.out.println("Test 11 passed"); - - } - - @Test - @Order(12) - public void describeModel_thenNotNull() throws IOException, LookoutVisionException { - - // Describe a model. - ModelDescription description = Models.describeModel(lfvClient, projectName, modelVersion); - - // Check that a description is returned. - assertNotNull(description); - System.out.println("Test 12 passed"); - - } - - @Test - @Order(13) + @Tag("IntegrationTest") + @Order(6) public void listModels_thenNotNull() throws IOException, LookoutVisionException { - // Describe a model. List models = Models.listModels(lfvClient, projectName); - assertNotNull(models); - - System.out.println("Test 13 passed"); - - } - - @Test - @Order(14) - public void startModel_thenNotEquals() throws IOException, LookoutVisionException, InterruptedException { - - // Describe a model. - ModelDescription model = Hosting.startModel(lfvClient, projectName, modelVersion, 1); - - assertEquals(ModelStatus.HOSTED, model.status()); - - System.out.println("Test 14 passed"); - - } - - @Test - @Order(15) - public void detectAnomaliesPanel_thenNotNull() throws IOException, LookoutVisionException { - - float minConfidence = (float) 0.5; - - // Check normal classification - DetectAnomalyResult prediction = DetectAnomalies.detectAnomalies(lfvClient, projectName, modelVersion, photo); - boolean reject = DetectAnomalies.rejectOnClassification(photo, prediction, minConfidence); - assertEquals(Boolean.FALSE, reject); - - // Check anomalous classification - prediction = DetectAnomalies.detectAnomalies(lfvClient, projectName, modelVersion, anomalousPhoto); - reject = DetectAnomalies.rejectOnClassification(anomalousPhoto, prediction, minConfidence); - assertEquals(Boolean.TRUE, reject); - - // Check at least 1 anomaly exists - reject = DetectAnomalies.rejectOnAnomalyTypeCount(anomalousPhoto, prediction, minConfidence, 0); - assertEquals(Boolean.TRUE, reject); - - // Check coverage for an anomaly is at least 0.01. - reject = DetectAnomalies.rejectOnCoverage(anomalousPhoto, prediction, minConfidence, anomalyLabel, - (float) 0.01); - assertEquals(Boolean.TRUE, reject); - - System.out.println("Test 15 passed"); - - } - - @Test - @Order(16) - public void showAnomaliesPanel_thenNotNull() throws IOException, LookoutVisionException { - - ShowAnomalies panel = new ShowAnomalies(lfvClient, projectName, modelVersion, photo); - assertNotNull(panel); - - System.out.println("Test 16 passed"); - - } - - @Test - @Order(17) - public void stopModel_thenEquals() throws IOException, LookoutVisionException, InterruptedException { - - // Describe a model. - ModelDescription model = Hosting.stopModel(lfvClient, projectName, modelVersion); - - assertEquals(ModelStatus.TRAINED, model.status()); - - System.out.println("Test 17 passed"); - - } - - @Test - @Order(18) - public void startModelPackagingJob_thenEqual() throws IOException, LookoutVisionException, InterruptedException { - - // Create the model packaging job. - ModelPackagingDescription packageDescription = EdgePackages.startModelPackagingJob(lfvClient, projectName, - modelPackageJobJsonFile); - - jobName = packageDescription.jobName(); - - assertEquals(ModelPackagingJobStatus.SUCCEEDED, packageDescription.status()); - - System.out.println("Test 18 passed"); - + logger.info("Test 6 passed"); } - @Test - @Order(19) - public void listModelPackagingJobs_thenEquals() throws IOException, LookoutVisionException, InterruptedException { - - // List model packaging jobs. - List packagingJobs = EdgePackages.listModelPackagingJobs(lfvClient, projectName); - - // When run in sequence, jobName is picked up from - // startModelPackagingJob_thenEqual(). Otherwise, specify a value for jobName. - - assertEquals(jobName, packagingJobs.get(0).jobName()); - - System.out.println("Test 19 passed"); - - } - - @Test - @Order(20) - public void describeModelPackagingJob_thenNotNull() throws IOException, LookoutVisionException { - - // Describe a model. - - // When run in sequence, jobName is picked up from - // startModelPackagingJob_thenEqual(). Otherwise, specify a value for jobName. - ModelPackagingDescription description = EdgePackages.describeModelPackagingJob(lfvClient, projectName, jobName); - - // Check that a description is returned. - assertNotNull(description); - System.out.println("Test 20 passed"); - - } @Test - @Order(21) + @Tag("IntegrationTest") + @Order(7) public void deleteDataset_thenNotFound() throws IOException, LookoutVisionException { - try { - // Delete a dataset. Datasets.deleteDataset(lfvClient, projectName, datasetType); Datasets.describeDataset(lfvClient, projectName, datasetType); @@ -420,44 +153,36 @@ public void deleteDataset_thenNotFound() throws IOException, } catch (LookoutVisionException e) { assertEquals("ResourceNotFoundException", e.awsErrorDetails().errorCode()); - System.out.println("Test 21 passed"); + logger.info("Test 7 passed"); } - } @Test - @Order(22) + @Tag("IntegrationTest") + @Order(8) public void deleteModel_thenNotFound() throws IOException, LookoutVisionException, InterruptedException { - try { - // Delete a model. Models.deleteModel(lfvClient, projectName, modelVersion); Models.describeModel(lfvClient, projectName, modelVersion); - } catch (LookoutVisionException e) { - assertEquals("ResourceNotFoundException", e.awsErrorDetails().errorCode()); - System.out.println("Test 22 passed"); } - + logger.info("Test 8 passed"); } @Test - @Order(23) + @Tag("IntegrationTest") + @Order(9) public void deleteProject_thenNotFound() throws IOException, LookoutVisionException, InterruptedException { - try { Projects.deleteProject(lfvClient, projectName); Projects.describeProject(lfvClient, projectName); } catch (LookoutVisionException e) { - assertEquals("ResourceNotFoundException", e.awsErrorDetails().errorCode()); - System.out.println("Test 23 passed"); + logger.info("Test 9 passed"); } - } - } diff --git a/javav2/example_code/mediaconvert/pom.xml b/javav2/example_code/mediaconvert/pom.xml index 7eaa1926aab..74dae1e82fa 100644 --- a/javav2/example_code/mediaconvert/pom.xml +++ b/javav2/example_code/mediaconvert/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -70,5 +77,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/mediaconvert/src/main/resources/log4j2.xml b/javav2/example_code/mediaconvert/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/mediaconvert/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java b/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java index f9035a700e2..516a8b46f4e 100644 --- a/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java +++ b/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java @@ -6,6 +6,8 @@ import com.example.mediaconvert.ListJobs; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediaconvert.MediaConvertClient; @@ -24,6 +26,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonMediaConvertTest { + private static final Logger logger = LoggerFactory.getLogger(AmazonMediaConvertTest.class); private static MediaConvertClient mc; private static Region region; private static String mcRoleARN = ""; @@ -35,7 +38,6 @@ public static void setUp() throws IOException { region = Region.US_WEST_2; mc = MediaConvertClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -44,58 +46,36 @@ public static void setUp() throws IOException { SecretValues values = gson.fromJson(json, SecretValues.class); mcRoleARN = values.getMcRoleARN(); fileInput = values.getFileInput(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonMediaConvertTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * mcRoleARN = prop.getProperty("mcRoleARN"); - * fileInput = prop.getProperty("fileInput"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateJob() { + public void testCreateJob() { jobId = CreateJob.createMediaJob(mc, mcRoleARN, fileInput); assertFalse(jobId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void ListJobs() { + public void testListJobs() { assertDoesNotThrow(() -> ListJobs.listCompleteJobs(mc)); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetJob() { + public void testGetJob() { assertDoesNotThrow(() -> GetJob.getSpecificJob(mc, jobId)); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/mediaconvert"; @@ -112,15 +92,11 @@ private static String getSecretValues() { class SecretValues { private String mcRoleARN; private String fileInput; - public String getMcRoleARN() { return mcRoleARN; } - public String getFileInput() { return fileInput; } - } - } diff --git a/javav2/example_code/mediastore/pom.xml b/javav2/example_code/mediastore/pom.xml index bc3bd162451..097c2feeda8 100644 --- a/javav2/example_code/mediastore/pom.xml +++ b/javav2/example_code/mediastore/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java index 82924fce8b6..4989c34a759 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java @@ -47,6 +47,7 @@ public static void main(String[] args) { mediaStoreClient.close(); } + public static void createMediaContainer(MediaStoreClient mediaStoreClient, String containerName) { try { CreateContainerRequest containerRequest = CreateContainerRequest.builder() diff --git a/javav2/example_code/mediastore/src/main/resources/log4j2.xml b/javav2/example_code/mediastore/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/mediastore/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java b/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java index 97c25c5c2a6..07c0b047fc9 100644 --- a/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java +++ b/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java @@ -3,6 +3,8 @@ import com.example.mediastore.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest; @@ -26,6 +28,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MediaStoreTest { + private static final Logger logger = LoggerFactory.getLogger(MediaStoreTest.class); private static MediaStoreClient mediaStoreClient; private static MediaStoreDataClient mediaStoreData; private static String containerName = ""; @@ -39,7 +42,6 @@ public static void setUp() throws URISyntaxException { Region region = Region.US_EAST_1; mediaStoreClient = MediaStoreClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -52,32 +54,6 @@ public static void setUp() throws URISyntaxException { existingContainer = values.getExistingContainer(); savePath = values.getSavePath(); - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * MediaStoreTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests - * prop.load(input); - * containerName = prop.getProperty("containerName")+ - * java.util.UUID.randomUUID(); - * filePath = prop.getProperty("filePath"); - * completePath = prop.getProperty("completePath"); - * existingContainer = prop.getProperty("existingContainer"); - * savePath = prop.getProperty("savePath"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ - URI uri = new URI(PutObject.getEndpoint(existingContainer)); mediaStoreData = MediaStoreDataClient.builder() .endpointOverride(uri) @@ -88,45 +64,45 @@ public static void setUp() throws URISyntaxException { @Test @Tag("IntegrationTest") @Order(1) - public void CreateContainer() { + public void testCreateContainer() { assertDoesNotThrow(() -> CreateContainer.createMediaContainer(mediaStoreClient, containerName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeContainer() { + public void testDescribeContainer() { assertDoesNotThrow(() -> DescribeContainer.checkContainer(mediaStoreClient, containerName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListContainers() { + public void testListContainers() { assertDoesNotThrow(() -> ListContainers.listAllContainers(mediaStoreClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListItems() { + public void testListItems() { assertDoesNotThrow(() -> ListItems.listAllItems(mediaStoreData, containerName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DeleteContainer() throws InterruptedException { + public void testDeleteContainer() throws InterruptedException { System.out.println("Wait 1 min to delete container"); TimeUnit.MINUTES.sleep(1); assertDoesNotThrow( () -> assertDoesNotThrow(() -> DeleteContainer.deleteMediaContainer(mediaStoreClient, containerName))); - System.out.println("Test 7 passed"); + logger.info("Test 5 passed"); } private static String getEndpoint(String containerName) { @@ -146,7 +122,6 @@ private static String getEndpoint(String containerName) { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/mediastore"; diff --git a/javav2/example_code/medicalimaging/pom.xml b/javav2/example_code/medicalimaging/pom.xml index 268a3e47385..147467feb1f 100644 --- a/javav2/example_code/medicalimaging/pom.xml +++ b/javav2/example_code/medicalimaging/pom.xml @@ -8,8 +8,8 @@ 1.0-SNAPSHOT UTF-8 - 17 - 2.29.45 + 21 + 2.31.8 diff --git a/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java b/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java index 09b63ccc5a2..5dcb97e23f7 100644 --- a/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java +++ b/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java @@ -48,52 +48,17 @@ public static void setUp() { medicalImagingClient = MedicalImagingClient.builder() .region(Region.US_WEST_2) // TODO: change back to US-EAST-1 - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Random random = new Random(); int randomNum = random.nextInt((10000 - 1) + 1) + 1; - datastoreName = "java_test_" + randomNum; - // Get the values to run these tests from AWS Secrets Manager. - Gson gson = new Gson(); - String json = getSecretValues(); - SecretValues values = gson.fromJson(json, SecretValues.class); - workingDatastoreId = values.getDatastoreId(); - imageSetId = values.getImageSetId(); - imageFrameId = values.getImageFrameId(); - importJobId = values.getImportJobId(); - dataResourceArn = values.getDataResourceArn(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * AWSMedicalImagingTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * prop.load(input); - * dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); - * inputS3Uri= prop.getProperty("inputS3Uri"); - * outputS3Uri= prop.getProperty("outputS3Uri"); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @SuppressWarnings("resource") private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_WEST_2) // TODO: change back to US-EAST-1 - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/medicalimaging"; @@ -112,220 +77,18 @@ public void createDatastoreTest() { assertDoesNotThrow(() -> createdDatastoreId = CreateDatastore.createMedicalImageDatastore(medicalImagingClient, datastoreName)); assert (!createdDatastoreId.isEmpty()); - + System.out.println("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void getDatastoreTest() { - final DatastoreProperties[] datastoreProperties = { null }; - assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore.getMedicalImageDatastore(medicalImagingClient, - workingDatastoreId)); - assertNotNull(datastoreProperties[0]); - - System.out.println("Test 2 passed"); - - } - - @Test - @Tag("IntegrationTest") - @Order(3) public void listDatastoresTest() { @SuppressWarnings("rawtypes") final List[] dataStoreSummaries = { null }; assertDoesNotThrow( () -> dataStoreSummaries[0] = ListDatastores.listMedicalImagingDatastores(medicalImagingClient)); assertNotNull(dataStoreSummaries[0]); - - System.out.println("Test 3 passed"); - - } - - - @Test - @Tag("IntegrationTest") - @Order(5) - public void listDicomImportJobsTest() { - @SuppressWarnings("rawtypes") - final List[] dicomImportJobSummaries = { null }; - assertDoesNotThrow( - () -> dicomImportJobSummaries[0] = ListDicomImportJobs.listDicomImportJobs(medicalImagingClient, - workingDatastoreId)); - assertNotNull(dicomImportJobSummaries[0]); - - System.out.println("Test 5 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(6) - public void searchImageSetsTest() { - List searchFilters = Collections.singletonList(SearchFilter.builder() - .operator(Operator.BETWEEN) - .values(SearchByAttributeValue.builder() - .createdAt(Instant.parse("1985-04-12T23:20:50.52Z")) - .build(), - SearchByAttributeValue.builder() - .createdAt(Instant.now()) - .build()) - .build()); - - SearchCriteria searchCriteria = SearchCriteria.builder() - .filters(searchFilters) - .build(); - @SuppressWarnings("rawtypes") - final List[] searchResults = { null }; - assertDoesNotThrow(() -> searchResults[0] = SearchImageSets.searchMedicalImagingImageSets(medicalImagingClient, - workingDatastoreId, searchCriteria)); - assertNotNull(searchResults[0]); - - System.out.println("Test 6 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(7) - public void getImageSetTest() { - final GetImageSetResponse[] imageSetResponses = { null }; - assertDoesNotThrow(() -> imageSetResponses[0] = GetImageSet.getMedicalImageSet(medicalImagingClient, - workingDatastoreId, imageSetId, "1")); - assertNotNull(imageSetResponses[0]); - - System.out.println("Test 7 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(8) - public void getImageSetMetadataTest() { - final String metadataFileName = "java_metadatata.json.gzip"; - assertDoesNotThrow(() -> GetImageSetMetadata.getMedicalImageSetMetadata(medicalImagingClient, metadataFileName, - workingDatastoreId, imageSetId, "1")); - - File metadataFile = new File(metadataFileName); - assert (metadataFile.exists()); - // noinspection ResultOfMethodCallIgnored - metadataFile.delete(); - - System.out.println("Test 8 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(9) - public void getImageFrameTest() { - final String imageFileName = "java_impage.jph"; - assertDoesNotThrow(() -> GetImageFrame.getMedicalImageSetFrame(medicalImagingClient, imageFileName, - workingDatastoreId, imageSetId, imageFrameId)); - - File imageFile = new File(imageFileName); - assert (imageFile.exists()); - // noinspection ResultOfMethodCallIgnored - imageFile.delete(); - - System.out.println("Test 9 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(10) - public void listImageSetVersionsTest() { - @SuppressWarnings("rawtypes") - List[] imageSetVersions = new List[1]; - assertDoesNotThrow(() -> imageSetVersions[0] = ListImageSetVersions - .listMedicalImageSetVersions(medicalImagingClient, workingDatastoreId, imageSetId)); - assertNotNull(imageSetVersions[0]); - - System.out.println("Test 10 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(11) - public void tagResourceTest() { - assertDoesNotThrow(() -> TagResource.tagMedicalImagingResource(medicalImagingClient, dataResourceArn, - ImmutableMap.of("Deployment", "Development"))); - - System.out.println("Test 11 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(12) - public void listTagsForResourceTest() { - ListTagsForResourceResponse[] listTagsForResourceResponses = { null }; - assertDoesNotThrow(() -> listTagsForResourceResponses[0] = ListTagsForResource - .listMedicalImagingResourceTags(medicalImagingClient, dataResourceArn)); - assertNotNull(listTagsForResourceResponses[0]); - - System.out.println("Test 12 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(13) - public void untagResourceTest() { - assertDoesNotThrow(() -> UntagResource.untagMedicalImagingResource(medicalImagingClient, dataResourceArn, - Collections.singletonList("Deployment"))); - - System.out.println("Test 13 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(14) - public void deleteDatastoreTest() { - assert (!createdDatastoreId.isEmpty()); - int count = 0; - while (count < 20) { - final DatastoreProperties[] datastoreProperties = { null }; - assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore - .getMedicalImageDatastore(medicalImagingClient, workingDatastoreId)); - if (datastoreProperties[0].datastoreStatus().toString().equals("ACTIVE")) { - break; - } - assertDoesNotThrow(() -> Thread.sleep(1000)); - count++; - } - assertDoesNotThrow( - () -> DeleteDatastore.deleteMedicalImagingDatastore(medicalImagingClient, createdDatastoreId)); - System.out.println("Test 14 passed"); - } - - @SuppressWarnings("unused") - @Nested - @DisplayName("A class used to get test values from test/medicalimaging (an AWS Secrets Manager secret)") - class SecretValues { - - private String datastoreId; - - private String imageSetId; - - private String imageFrameId; - - private String importJobId; - - private String dataResourceArn; - - public String getDatastoreId() { - return datastoreId; - } - - public String getImageSetId() { - return imageSetId; - } - - public String getImageFrameId() { - return imageFrameId; - } - - public String getImportJobId() { - return importJobId; - } - - public String getDataResourceArn() { - return dataResourceArn; - } + System.out.println("Test 2 passed"); } } \ No newline at end of file diff --git a/javav2/example_code/memorydb/pom.xml b/javav2/example_code/memorydb/pom.xml index de3193a7480..335a17a28db 100644 --- a/javav2/example_code/memorydb/pom.xml +++ b/javav2/example_code/memorydb/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -75,22 +82,12 @@ software.amazon.awssdk kms - - redis.clients - jedis - 2.8.1 - redis.clients jedis 2.8.0 jar - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk memorydb @@ -103,5 +100,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/memorydb/src/main/resources/log4j2.xml b/javav2/example_code/memorydb/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/memorydb/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java b/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java index 608276eded3..2aca5e9a092 100644 --- a/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java +++ b/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java @@ -3,6 +3,8 @@ import com.example.memorydb.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; @@ -20,6 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MemoryDBTest { + private static final Logger logger = LoggerFactory.getLogger(MemoryDBTest.class); private static MemoryDbClient memoryDbClient; private static String clusterName = ""; private static String nodeType = ""; @@ -32,7 +35,6 @@ public static void setUp() { Region region = Region.US_EAST_1; memoryDbClient = MemoryDbClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Random random = new Random(); @@ -47,30 +49,6 @@ public static void setUp() { subnetGroupName = values.getSubnetGroupName(); aclName = values.getAclName(); snapShotName = values.getSnapShotName() + randomNum; - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * MemoryDBTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * clusterName = prop.getProperty("clusterName")+ java.util.UUID.randomUUID(); - * nodeType = prop.getProperty("nodeType"); - * subnetGroupName = prop.getProperty("subnetGroupName"); - * aclName = prop.getProperty("aclName"); - * snapShotName= prop.getProperty("snapShotName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @@ -79,7 +57,7 @@ public static void setUp() { public void createCluster() { assertDoesNotThrow(() -> CreateCluster.createSingleCluster(memoryDbClient, clusterName, nodeType, subnetGroupName, aclName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @@ -87,7 +65,7 @@ public void createCluster() { @Order(2) public void describeSpecificCluster() { assertDoesNotThrow(() -> DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @@ -95,7 +73,7 @@ public void describeSpecificCluster() { @Order(3) public void createSnapshot() { assertDoesNotThrow(() -> CreateSnapshot.createSpecificSnapshot(memoryDbClient, clusterName, snapShotName)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @@ -103,7 +81,7 @@ public void createSnapshot() { @Order(4) public void describeSnapshot() { assertDoesNotThrow(() -> DescribeSnapshots.describeALlSnapshots(memoryDbClient, clusterName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @@ -112,7 +90,7 @@ public void describeSnapshot() { public void describeAllClusters() { assertDoesNotThrow(() -> DescribeClusters.getClusters(memoryDbClient)); assertDoesNotThrow(() -> DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @@ -120,13 +98,12 @@ public void describeAllClusters() { @Order(6) public void deleteCluster() { assertDoesNotThrow(() -> DeleteCluster.deleteSpecificCluster(memoryDbClient, clusterName)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/memorydb"; diff --git a/javav2/example_code/migrationhub/pom.xml b/javav2/example_code/migrationhub/pom.xml index 3cc4e20ba10..795f630f710 100644 --- a/javav2/example_code/migrationhub/pom.xml +++ b/javav2/example_code/migrationhub/pom.xml @@ -9,9 +9,9 @@ jar UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -70,5 +77,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/migrationhub/src/main/resources/log4j2.xml b/javav2/example_code/migrationhub/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/migrationhub/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java b/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java index 596c1238122..638eb46c6e3 100644 --- a/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java +++ b/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java @@ -3,6 +3,8 @@ import com.example.migrationhub.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.migrationhub.MigrationHubClient; import org.junit.jupiter.api.*; @@ -19,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MigrationHubTest { + private static final Logger logger = LoggerFactory.getLogger(MigrationHubTest.class); private static MigrationHubClient migrationClient; private static String appId = ""; private static String migrationtask = ""; @@ -28,7 +31,6 @@ public class MigrationHubTest { public static void setUp() { migrationClient = MigrationHubClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -38,83 +40,59 @@ public static void setUp() { appId = values.getAppId(); migrationtask = values.getMigrationtask(); progress = values.getProgress(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * MigrationHubTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * appId = prop.getProperty("appId"); - * migrationtask = prop.getProperty("migrationtask"); - * progress = prop.getProperty("progress"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void ImportMigrationTask() { + public void testImportMigrationTask() { assertDoesNotThrow(() -> ImportMigrationTask.importMigrTask(migrationClient, migrationtask, progress)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeAppState() { + public void testDescribeAppState() { assertDoesNotThrow(() -> DescribeAppState.describeApplicationState(migrationClient, appId)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeMigrationTask() { + public void testDescribeMigrationTask() { assertDoesNotThrow(() -> DescribeMigrationTask.describeMigTask(migrationClient, migrationtask, progress)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListApplications() { + public void testListApplications() { assertDoesNotThrow(() -> ListApplications.listApps(migrationClient)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListMigrationTasks() { + public void testListMigrationTasks() { assertDoesNotThrow(() -> ListMigrationTasks.listMigrTasks(migrationClient)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteProgressStream() { + public void testDeleteProgressStream() { assertDoesNotThrow(() -> DeleteProgressStream.deleteStream(migrationClient, progress)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/migrationhub"; diff --git a/javav2/example_code/mq/pom.xml b/javav2/example_code/mq/pom.xml index 4cf306a60af..354ed108183 100644 --- a/javav2/example_code/mq/pom.xml +++ b/javav2/example_code/mq/pom.xml @@ -8,12 +8,12 @@ jar UTF-8 - 17 - 17 + 21 + 21 3.2.1 3.6.1 1.6.0 - 2.29.45 + 2.31.8 @@ -24,6 +24,13 @@ pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + @@ -45,6 +52,23 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java b/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java index 8eb388c6a78..ca7a862f8b3 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java @@ -50,7 +50,7 @@ public static String createNewConfigutation(MqClient mqClient, String configurat try { CreateConfigurationRequest configurationRequest = CreateConfigurationRequest.builder() .name(configurationName) - .engineVersion("5.15.14") + .engineVersion("5.18") .engineType("ACTIVEMQ") .authenticationStrategy("SIMPLE") .build(); diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/DeleteBroker.java b/javav2/example_code/mq/src/main/java/com/example/mq/DeleteBroker.java new file mode 100644 index 00000000000..832abe3e571 --- /dev/null +++ b/javav2/example_code/mq/src/main/java/com/example/mq/DeleteBroker.java @@ -0,0 +1,43 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.mq; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.mq.MqClient; +import software.amazon.awssdk.services.mq.model.DeleteBrokerRequest; + +public class DeleteBroker { + + public static void main(String [] args) { + final String usage = """ + + Usage: + + Where: + brokerId - The id of the Amazon broker to delete. + + """; + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String brokerId = args[0]; + Region region = Region.US_WEST_2; + MqClient mqClient = MqClient.builder() + .region(region) + .build(); + + deleteBroker(mqClient, brokerId); + } + + public static void deleteBroker(MqClient mqClient, String brokerId) { + DeleteBrokerRequest request = DeleteBrokerRequest.builder() + .brokerId(brokerId) + .build(); + + mqClient.deleteBroker(request); + System.out.println("Delete broker successfully"); + } +} diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java b/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java index 73abca71097..775d164ee09 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java @@ -45,21 +45,31 @@ public static void main(String[] args) { } // snippet-start:[mq.java2.describe_broker.main] - public static String describeBroker(MqClient mqClient, String brokerName) { + public static String describeBroker(MqClient mqClient, String brokerId) { try { - DescribeBrokerRequest request = DescribeBrokerRequest.builder() - .brokerId(brokerName) - .build(); + while (true) { + DescribeBrokerRequest request = DescribeBrokerRequest.builder() + .brokerId(brokerId) + .build(); - DescribeBrokerResponse response = mqClient.describeBroker(request); - System.out.print(response + "\n\n"); - return response.brokerId(); + DescribeBrokerResponse response = mqClient.describeBroker(request); + String currentState = response.brokerStateAsString(); + System.out.println("Current Broker State: " + currentState); + if ("RUNNING".equalsIgnoreCase(currentState)) { + return response.brokerId(); + } + + // Sleep before polling again to avoid throttling + Thread.sleep(5_000); + } } catch (MqException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + System.err.println("Error describing broker: " + e.awsErrorDetails().errorMessage()); + throw new RuntimeException(e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread was interrupted while waiting for broker to complete.", e); } - return ""; } // snippet-end:[mq.java2.describe_broker.main] } diff --git a/javav2/example_code/mq/src/main/resources/config.properties b/javav2/example_code/mq/src/main/resources/config.properties index a59c794f618..0a7417a447b 100644 --- a/javav2/example_code/mq/src/main/resources/config.properties +++ b/javav2/example_code/mq/src/main/resources/config.properties @@ -1,5 +1,14 @@ -engineType = -brokerName = -configurationName = -brokerId = -configurationId = \ No newline at end of file +# The type of broker engine. Supported values: "ActiveMQ" or "RabbitMQ" +engineType = ActiveMQ + +# The name of the broker to create +brokerName = MyMQBroker + +# The name of the configuration to use for the broker +configurationName = MyMQConfig + +# The ID of the broker (This is usually assigned by AWS after creation) +brokerId = mq-broker-1234567890abcdef + +# The ID of the configuration to use for the broker (This is assigned by AWS after creation) +configurationId = mq-config-0987654321abcdef \ No newline at end of file diff --git a/javav2/example_code/mq/src/main/resources/log4j2.xml b/javav2/example_code/mq/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/mq/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/mq/src/test/java/AmazonMQTest.java b/javav2/example_code/mq/src/test/java/AmazonMQTest.java index 997e90d95fa..4e72e7681da 100644 --- a/javav2/example_code/mq/src/test/java/AmazonMQTest.java +++ b/javav2/example_code/mq/src/test/java/AmazonMQTest.java @@ -2,32 +2,34 @@ // SPDX-License-Identifier: Apache-2.0 import com.example.mq.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mq.MqClient; import software.amazon.awssdk.services.mq.model.Configuration; import software.amazon.awssdk.services.mq.model.BrokerSummary; import org.junit.jupiter.api.*; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.*; import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonMQTest { - + private static final Logger logger = LoggerFactory.getLogger(AmazonMQTest.class); private static MqClient mqClient; private static Region region; private static String engineType = ""; private static String brokerName = ""; - private static String configurationName = ""; private static String brokerId = ""; + private static String configurationName = ""; private static String configurationId = ""; @BeforeAll public static void setUp() throws IOException { - region = Region.US_WEST_2; mqClient = MqClient.builder() .region(region) @@ -44,12 +46,12 @@ public static void setUp() throws IOException { // load a properties file from class path, inside static method prop.load(input); - + Random random = new Random(); + int randomValue = random.nextInt(1000) + 1; // Populate the data members required for all tests engineType = prop.getProperty("engineType"); - brokerName = prop.getProperty("brokerName"); + brokerName = prop.getProperty("brokerName")+randomValue; configurationName = prop.getProperty("configurationName"); - brokerId = prop.getProperty("brokerId"); configurationId = prop.getProperty("configurationId"); } catch (IOException ex) { @@ -57,52 +59,56 @@ public static void setUp() throws IOException { } } - @Test + @Tag("IntegrationTest") @Order(1) - public void CreateBroker() { - String result = CreateBroker.createBroker(mqClient, engineType, brokerName); - assertTrue(!result.isEmpty()); - System.out.println("Test 2 passed"); + public void testCreateBroker() { + brokerId = CreateBroker.createBroker(mqClient, engineType, brokerName); + assertTrue(!brokerId.isEmpty()); + logger.info("Test 1 passed"); } @Test + @Tag("IntegrationTest") @Order(2) - public void CreateConfiguration() { + public void testCreateConfiguration() { String result = CreateConfiguration.createNewConfigutation(mqClient, configurationName); assertTrue(!result.isEmpty()); - System.out.println("Test 3 passed"); + logger.info("Test 2 passed"); } @Test + @Tag("IntegrationTest") @Order(3) - public void DescribeBroker() { + public void testDescribeBroker() { String result = DescribeBroker.describeBroker(mqClient, brokerName); assertTrue(!result.isEmpty()); - System.out.println("Test 4 passed"); + logger.info("Test 3 passed"); } @Test + @Tag("IntegrationTest") @Order(4) - public void ListBrokers() { + public void testListBrokers() { List result = ListBrokers.listBrokers(mqClient); assertTrue(result instanceof List); - System.out.println("Test 5 passed"); + logger.info("Test 4 passed"); } @Test + @Tag("IntegrationTest") @Order(5) - public void ListConfigurations() { + public void testListConfigurations() { List result = ListConfigurations.listConfigurations(mqClient); assertTrue(result instanceof List); - System.out.println("Test 6 passed"); + logger.info("Test 5 passed"); } @Test + @Tag("IntegrationTest") @Order(6) - public void UpdateBrokerConfiguration() { - String result = UpdateBrokerConfiguration.updateBrokerConfiguration(mqClient, brokerId, configurationId); - assertTrue(!result.isEmpty()); - System.out.print("Test 7 passed"); + public void testDeleteBroker() { + assertDoesNotThrow(() -> DeleteBroker.deleteBroker(mqClient, brokerId)); + logger.info("Test 6 passed"); } } diff --git a/javav2/example_code/opensearch/pom.xml b/javav2/example_code/opensearch/pom.xml index 59999b3de11..a8cf085b76a 100644 --- a/javav2/example_code/opensearch/pom.xml +++ b/javav2/example_code/opensearch/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java index 0f623d4a4c9..e8a4fd872bd 100644 --- a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java +++ b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java @@ -4,6 +4,8 @@ import com.example.search.scenario.OpenSearchActions; import com.example.search.scenario.OpenSearchScenario; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.opensearch.OpenSearchClient; @@ -24,6 +26,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class OpenSearchTest { + private static final Logger logger = LoggerFactory.getLogger(OpenSearchTest.class); private static OpenSearchActions openSearchActions; private static String domainName = ""; @@ -41,121 +44,85 @@ public static void setUp() throws IOException { @Test @Tag("IntegrationTest") @Order(1) - public void helloTest() { + public void testHello() { assertDoesNotThrow(() -> { CompletableFuture future = HelloOpenSearch.listVersionsAsync(); future.join(); }); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void createDomain() { + public void testCreateDomain() { assertDoesNotThrow(() -> { CompletableFuture future = openSearchActions.createNewDomainAsync(domainName); String domainId = future.join(); - System.out.println("Domain successfully created with ID: " + domainId); + logger.info("Domain successfully created with ID: " + domainId); }); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void describeDomainTest() { + public void testDescribeDomainTest() { assertDoesNotThrow(() -> { CompletableFuture future = openSearchActions.describeDomainAsync(domainName); arn = future.join(); }); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void listDomains() { + public void testListDomains() { assertDoesNotThrow(() -> { CompletableFuture> future = openSearchActions.listAllDomainsAsync(); List domainInfoList = future.join(); for (DomainInfo domain : domainInfoList) { - System.out.println("Domain name is: " + domain.domainName()); + logger.info("Domain name is: " + domain.domainName()); } }); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void domainChangeTest() { - assertDoesNotThrow(() -> { - CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); - future.join(); - System.out.println("Domain change progress completed successfully."); - }); - System.out.println("Test 5 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(6) - public void domainModifyTest() { - assertDoesNotThrow(() -> { - CompletableFuture future = openSearchActions.updateSpecificDomainAsync(domainName); - UpdateDomainConfigResponse updateResponse = future.join(); // Wait for the task to complete - System.out.println("Domain update response from Amazon OpenSearch Service: " + updateResponse.toString()); - }); - System.out.println("Test 6 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(7) - public void domainChangeTest2() { - assertDoesNotThrow(() -> { - CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); - future.join(); - System.out.println("Domain change progress completed successfully."); - }); - System.out.println("Test 7 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(8) - public void domainTagTest() { + public void testDomainTagTest() { assertDoesNotThrow(() -> { CompletableFuture future = openSearchActions.addDomainTagsAsync(arn); future.join(); - System.out.println("Domain change progress completed successfully."); + logger.info("Domain change progress completed successfully."); }); - System.out.println("Test 8 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") - @Order(9) - public void domainListTagsTest() { + @Order(6) + public void testDomainListTagsTest() { assertDoesNotThrow(() -> { CompletableFuture future = openSearchActions.listDomainTagsAsync(arn); future.join(); - System.out.println("Domain tags listed successfully."); + logger.info("Domain tags listed successfully."); }); - System.out.println("Test 8 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") - @Order(10) - public void domainDelTest() { + @Order(7) + public void testDomainDelTest() { assertDoesNotThrow(() -> { CompletableFuture future = openSearchActions.deleteSpecificDomainAsync(domainName); future.join(); - System.out.println(domainName + " was successfully deleted."); + logger.info(domainName + " was successfully deleted."); }); - System.out.println("Test 10 passed"); + logger.info("Test 7 passed"); } } diff --git a/javav2/example_code/personalize/pom.xml b/javav2/example_code/personalize/pom.xml index afaf7cf497c..e23443d3a23 100644 --- a/javav2/example_code/personalize/pom.xml +++ b/javav2/example_code/personalize/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -77,5 +84,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java index 0669073c393..b7099fa5f97 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java @@ -52,7 +52,7 @@ public static void main(String[] args) { } // snippet-start:[personalize.java2.create_campaign.main] - public static void createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn, + public static String createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn, String name) { try { @@ -64,11 +64,12 @@ public static void createPersonalCompaign(PersonalizeClient personalizeClient, S CreateCampaignResponse campaignResponse = personalizeClient.createCampaign(createCampaignRequest); System.out.println("The campaign ARN is " + campaignResponse.campaignArn()); - + return campaignResponse.campaignArn(); } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } + return null; } // snippet-end:[personalize.java2.create_campaign.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java index 5f74a6b68c7..cd250784591 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java @@ -4,32 +4,32 @@ package com.example.personalize; // snippet-start:[personalize.java2.delete_campaign.import] + import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DeleteCampaignRequest; +import software.amazon.awssdk.services.personalize.model.DescribeCampaignRequest; +import software.amazon.awssdk.services.personalize.model.DescribeCampaignResponse; import software.amazon.awssdk.services.personalize.model.PersonalizeException; // snippet-end:[personalize.java2.delete_campaign.import] /** * To run this Java V2 code example, ensure that you have setup your development * environment, including your credentials. - * + *

* For information, see this documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteCampaign { public static void main(String[] args) { - final String USAGE = """ - Usage: - DeleteCampaign \s - + DeleteCampaign + Where: campaignArn - The ARN of the campaign to delete. - """; if (args.length != 1) { @@ -39,28 +39,63 @@ public static void main(String[] args) { String campaignArn = args[0]; Region region = Region.US_EAST_1; - PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + try (PersonalizeClient personalizeClient = PersonalizeClient.builder().region(region).build()) { + waitForCampaignToBeDeletable(personalizeClient, campaignArn); + deleteSpecificCampaign(personalizeClient, campaignArn); + System.out.println("Campaign deleted successfully: " + campaignArn); + } + } + + // Polls until the campaign is in a deletable state + public static void waitForCampaignToBeDeletable(PersonalizeClient personalizeClient, String campaignArn) { + try { + while (true) { + DescribeCampaignRequest describeRequest = DescribeCampaignRequest.builder() + .campaignArn(campaignArn) + .build(); - deleteSpecificCampaign(personalizeClient, campaignArn); - personalizeClient.close(); + DescribeCampaignResponse describeResponse = personalizeClient.describeCampaign(describeRequest); + String status = describeResponse.campaign().status(); + System.out.println("Current campaign status: " + status); + + // Check if it's in a deletable state (using string values) + if (status.equalsIgnoreCase("ACTIVE") || + status.equalsIgnoreCase("CREATE FAILED") || + status.equalsIgnoreCase("STOPPED")) { + return; // Campaign is now deletable + } + + // If it's in DELETE PENDING, it means it's already being deleted + if (status.equalsIgnoreCase("DELETE PENDING")) { + throw new RuntimeException("Campaign is already being deleted."); + } + + // Wait before checking again to avoid excessive API calls + Thread.sleep(10_000); + } + } catch (PersonalizeException e) { + System.err.println("Error while polling campaign state: " + e.awsErrorDetails().errorMessage()); + throw new RuntimeException(e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread interrupted while waiting for campaign to be deletable.", e); + } } // snippet-start:[personalize.java2.delete_campaign.main] public static void deleteSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn) { - try { DeleteCampaignRequest campaignRequest = DeleteCampaignRequest.builder() .campaignArn(campaignArn) .build(); personalizeClient.deleteCampaign(campaignRequest); - + System.out.println("Delete request sent successfully."); } catch (PersonalizeException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + System.err.println("Error deleting campaign: " + e.awsErrorDetails().errorMessage()); + throw new RuntimeException(e); } } - // snippet-end:[personalize.java2.delete_campaign.main] } +// snippet-end:[personalize.java2.delete_campaign.main] + diff --git a/javav2/example_code/personalize/src/main/resources/log4j2.xml b/javav2/example_code/personalize/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/personalize/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java b/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java deleted file mode 100644 index af57c031887..00000000000 --- a/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import com.example.personalize.CreateDataset; -import com.example.personalize.CreateDatasetImportJob; -import com.example.personalize.CreateDomainDatasetGroup; -import com.example.personalize.CreateDomainSchema; -import com.example.personalize.CreateRecommender; -import com.example.personalize.GetRecommendationsFromRecommender; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.personalize.PersonalizeClient; -import software.amazon.awssdk.services.personalizeevents.PersonalizeEventsClient; -import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class PersonalizeDomainTest { - - private static PersonalizeRuntimeClient personalizeRuntimeClient; - private static PersonalizeClient personalizeClient; - private static PersonalizeEventsClient personalizeEventsClient; - - - private static String createDomainDatasetGroupName = ""; - private static String createDomainDatasetGroupDomain = ""; - - private static String createDomainSchemaName = ""; - private static String createDomainSchemaDomain = ""; - private static String createDomainSchemaLocation = ""; - - private static String newDatasetSchemaArn = ""; - private static String newDatasetName = ""; - private static String newDatasetType = ""; - private static String newDatasetDestinationDatasetGroupArn = ""; - - - private static String importJobDatasetArn = ""; - private static String domainDatasetImportJobName = ""; - private static String domainS3BucketPath = ""; - private static String domainRoleArn = ""; - - private static String createRecommenderName = ""; - private static String createRecommenderRecipeArn = ""; - private static String createRecommenderDatasetGroupArn = ""; - - private static String getRecommendationsRecommenderArn = ""; - private static String getRecommendationsUserId = ""; - - @BeforeAll - public static void setUp() throws IOException { - - //Change to the region where your Amazon Personalize resources are located. - Region region = Region.US_WEST_2; - - personalizeRuntimeClient = PersonalizeRuntimeClient.builder() - .region(region) - .build(); - personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); - personalizeEventsClient = PersonalizeEventsClient.builder() - .region(region) - .build(); - try (InputStream input = PersonalizeDomainTest.class.getClassLoader().getResourceAsStream("domain-dsg-config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Unable to find domain-dsg-config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - - createDomainDatasetGroupName = prop.getProperty("createDomainDatasetGroupName"); - createDomainDatasetGroupDomain = prop.getProperty("createDomainDatasetGroupDomain"); - - createDomainSchemaName = prop.getProperty("createDomainSchemaName"); - createDomainSchemaDomain = prop.getProperty("createDomainSchemaDomain"); - createDomainSchemaLocation = prop.getProperty("createDomainSchemaLocation"); - - newDatasetName = prop.getProperty("newDatasetName"); - newDatasetType = prop.getProperty("newDatasetType"); - newDatasetSchemaArn = prop.getProperty("newDatasetSchemaArn"); - newDatasetDestinationDatasetGroupArn = prop.getProperty("newDatasetDestinationDatasetGroupArn"); - - domainDatasetImportJobName = prop.getProperty("domainDatasetImportJobName"); - domainS3BucketPath = prop.getProperty("domainS3BucketPath"); - domainRoleArn = prop.getProperty("domainRoleArn"); - importJobDatasetArn = prop.getProperty("importJobDatasetArn"); - - createRecommenderName = prop.getProperty("createRecommenderName"); - createRecommenderRecipeArn = prop.getProperty("createRecommenderRecipeArn"); - createRecommenderDatasetGroupArn = prop.getProperty("recommenderDatasetGroupArn"); - - getRecommendationsUserId = prop.getProperty("getRecommendationsUserId"); - getRecommendationsRecommenderArn = prop.getProperty("getRecommendationsRecommenderArn"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - @Test - @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(personalizeRuntimeClient); - assertNotNull(personalizeClient); - assertNotNull(personalizeEventsClient); - System.out.println("Initialize clients test passed"); - } - - @Test - @Order(2) - public void CreateDomainDatasetGroup() { - String domainDatasetGroupArn = CreateDomainDatasetGroup.createDomainDatasetGroup(personalizeClient, - createDomainDatasetGroupName, createDomainDatasetGroupDomain); - assertFalse(domainDatasetGroupArn.isEmpty()); - System.out.println("CreateDomainDatasetGroup test passed"); - } - - @Test - @Order(3) - public void CreateDomainSchema() { - String domainSchemaArn = CreateDomainSchema.createDomainSchema(personalizeClient, - createDomainSchemaName, createDomainSchemaDomain, createDomainSchemaLocation); - assertFalse(domainSchemaArn.isEmpty()); - System.out.println("CreateDomainSchema test passed"); - } - - @Test - @Order(4) - public void CreateDomainDataset() { - String datasetArn = CreateDataset.createDataset(personalizeClient, - newDatasetName, newDatasetDestinationDatasetGroupArn, newDatasetType, newDatasetSchemaArn); - assertFalse(datasetArn.isEmpty()); - System.out.println("CreateDomainDataset test passed"); - } - - @Test - @Order(5) - public void CreateDatasetImportJob() { - String datasetImportJobArn = CreateDatasetImportJob.createPersonalizeDatasetImportJob(personalizeClient, - domainDatasetImportJobName, importJobDatasetArn, domainS3BucketPath, domainRoleArn); - assertFalse(datasetImportJobArn.isEmpty()); - System.out.println("CreateDatasetImportJob test passed"); - } - - @Test - @Order(6) - public void CreateRecommender() { - String recommenderArn = CreateRecommender.createRecommender(personalizeClient, - createRecommenderName, createRecommenderDatasetGroupArn, createRecommenderRecipeArn); - assertFalse(recommenderArn.isEmpty()); - System.out.println("CreateRecommender test passed"); - } - - @Test - @Order(7) - public void GetRecommendations() { - GetRecommendationsFromRecommender.getRecs(personalizeRuntimeClient, getRecommendationsRecommenderArn, getRecommendationsUserId); - System.out.println("GetRecommendations test passed"); - } -} diff --git a/javav2/example_code/personalize/src/test/java/PersonalizeTest.java b/javav2/example_code/personalize/src/test/java/PersonalizeTest.java index c9c1ebc2e99..866c02263e2 100644 --- a/javav2/example_code/personalize/src/test/java/PersonalizeTest.java +++ b/javav2/example_code/personalize/src/test/java/PersonalizeTest.java @@ -3,6 +3,8 @@ import com.example.personalize.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.personalize.PersonalizeClient; import org.junit.jupiter.api.*; @@ -21,7 +23,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class PersonalizeTest { - + private static final Logger logger = LoggerFactory.getLogger(PersonalizeTest.class); private static PersonalizeRuntimeClient personalizeRuntimeClient; private static PersonalizeClient personalizeClient; private static String datasetGroupArn = ""; @@ -38,12 +40,10 @@ public class PersonalizeTest { @BeforeAll public static void setUp() { personalizeRuntimeClient = PersonalizeRuntimeClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); personalizeClient = PersonalizeClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); @@ -61,136 +61,98 @@ public static void setUp() { ; existingSolutionArn = values.getExistingSolutionArn(); existingCampaignName = values.getExistingCampaignName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * PersonalizeTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * //load a properties file from class path, inside static method - * prop.load(input); - * - * // Populate the data members required for all tests - * datasetGroupArn = prop.getProperty("datasetGroupArn"); - * solutionVersionArn = prop.getProperty("solutionVersionArn"); - * recipeArn = prop.getProperty("recipeArn"); - * solutionName = prop.getProperty("solutionName")+ - * java.util.UUID.randomUUID();; - * userId = prop.getProperty("userId"); - * campaignName= prop.getProperty("campaignName")+ java.util.UUID.randomUUID();; - * existingSolutionArn= prop.getProperty("existingSolutionArn"); - * existingCampaignName = prop.getProperty("existingCampaignName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateSolution() { + public void testCreateSolution() { solutionArn = CreateSolution.createPersonalizeSolution(personalizeClient, datasetGroupArn, solutionName, recipeArn); assertFalse(solutionArn.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void ListSolutions() { + public void testListSolutions() { assertDoesNotThrow(() -> ListSolutions.listAllSolutions(personalizeClient, datasetGroupArn)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeSolution() { + public void testDescribeSolution() { assertDoesNotThrow(() -> DescribeSolution.describeSpecificSolution(personalizeClient, solutionArn)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void CreateCampaign() { - CreateCampaign.createPersonalCompaign(personalizeClient, solutionVersionArn, campaignName); - System.out.println("Test 4 passed"); + public void testCreateCampaign() { + campaignArn = CreateCampaign.createPersonalCompaign(personalizeClient, solutionVersionArn, campaignName); + assertFalse(campaignArn.isEmpty()); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListCampaigns() { + public void testListCampaigns() { assertDoesNotThrow(() -> ListCampaigns.listAllCampaigns(personalizeClient, existingSolutionArn)); - System.out.println("Test 6 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DescribeRecipe() { + public void testDescribeRecipe() { assertDoesNotThrow(() -> DescribeRecipe.describeSpecificRecipe(personalizeClient, recipeArn)); - System.out.println("Test 7 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void ListRecipes() { + public void testListRecipes() { assertDoesNotThrow(() -> ListRecipes.listAllRecipes(personalizeClient)); - System.out.println("Test 8 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void ListDatasetGroups() { + public void testListDatasetGroups() { assertDoesNotThrow(() -> ListDatasetGroups.listDSGroups(personalizeClient)); - System.out.println("Test 9 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void DeleteSolution() { + public void testDeleteSolution() { assertDoesNotThrow(() -> DeleteSolution.deleteGivenSolution(personalizeClient, solutionArn)); - System.out.println("Test 10 passed"); + logger.info("Test 9 passed"); } - @Test - @Tag("IntegrationTest") - @Order(10) - public void GetRecommendations() { - assertDoesNotThrow(() -> GetRecommendations.getRecs(personalizeRuntimeClient, campaignArn, userId)); - System.out.println("Test 11 passed"); - } @Test @Tag("IntegrationTest") - @Order(11) - public void DeleteCampaign() { - assertDoesNotThrow(() -> DeleteCampaign.deleteSpecificCampaign(personalizeClient, campaignArn)); - System.out.println("Test 12 passed"); + @Order(10) + public void testDeleteCampaign() { + assertDoesNotThrow(() -> { + DeleteCampaign.waitForCampaignToBeDeletable(personalizeClient, campaignArn); + DeleteCampaign.deleteSpecificCampaign(personalizeClient, campaignArn); + }); + logger.info("Test 10 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/personalize"; diff --git a/javav2/example_code/pinpoint/pom.xml b/javav2/example_code/pinpoint/pom.xml index a5db99dff59..77e4af31bf0 100644 --- a/javav2/example_code/pinpoint/pom.xml +++ b/javav2/example_code/pinpoint/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -77,5 +84,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java index 19f372a9892..5d8bcf6555b 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java @@ -5,6 +5,7 @@ // snippet-start:[pinpoint.java2.sendmsg.batch.main] // snippet-start:[pinpoint.java2.sendmsg.batch.import] + import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration; @@ -16,6 +17,7 @@ import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse; import software.amazon.awssdk.services.pinpoint.model.MessageResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; + import java.util.HashMap; import java.util.Map; // snippet-end:[pinpoint.java2.sendmsg.batch.import] @@ -23,106 +25,106 @@ /** * Before running this Java V2 code example, set up your development * environment, including your credentials. - * + *

* For more information, see the following documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SendMessageBatch { - // The type of SMS message that you want to send. If you plan to send - // time-sensitive content, specify TRANSACTIONAL. If you plan to send - // marketing-related content, specify PROMOTIONAL. - public static String messageType = "TRANSACTIONAL"; - - // The registered keyword associated with the originating short code. - public static String registeredKeyword = "myKeyword"; - - // The sender ID to use when sending the message. Support for sender ID - // varies by country or region. For more information, see - // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html - public static String senderId = "MySenderID"; - - public static void main(String[] args) { - final String usage = """ - - Usage: \s - - Where: - message - The body of the message to send. - appId - The Amazon Pinpoint project/application ID to use when you send this message. - originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). - destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654). - destinationNumber1 - The second recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String message = args[0]; - String appId = args[1]; - String originationNumber = args[2]; - String destinationNumber = args[3]; - String destinationNumber1 = args[4]; - System.out.println("Sending a message"); - PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); - - sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber, destinationNumber1); - pinpoint.close(); + // The type of SMS message that you want to send. If you plan to send + // time-sensitive content, specify TRANSACTIONAL. If you plan to send + // marketing-related content, specify PROMOTIONAL. + public static String messageType = "TRANSACTIONAL"; + + // The registered keyword associated with the originating short code. + public static String registeredKeyword = "myKeyword"; + + // The sender ID to use when sending the message. Support for sender ID + // varies by country or region. For more information, see + // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html + public static String senderId = "MySenderID"; + + public static void main(String[] args) { + final String usage = """ + + Usage: \s + + Where: + message - The body of the message to send. + appId - The Amazon Pinpoint project/application ID to use when you send this message. + originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). + destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654). + destinationNumber1 - The second recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); } - public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, - String originationNumber, - String destinationNumber, String destinationNumber1) { - try { - Map addressMap = new HashMap(); - AddressConfiguration addConfig = AddressConfiguration.builder() - .channelType(ChannelType.SMS) - .build(); - - // Add an entry to the Map object for each number to whom you want to send a - // message. - addressMap.put(destinationNumber, addConfig); - addressMap.put(destinationNumber1, addConfig); - SMSMessage smsMessage = SMSMessage.builder() - .body(message) - .messageType(messageType) - .originationNumber(originationNumber) - .senderId(senderId) - .keyword(registeredKeyword) - .build(); - - // Create a DirectMessageConfiguration object. - DirectMessageConfiguration direct = DirectMessageConfiguration.builder() - .smsMessage(smsMessage) - .build(); - - MessageRequest msgReq = MessageRequest.builder() - .addresses(addressMap) - .messageConfiguration(direct) - .build(); - - // Create a SendMessagesRequest object. - SendMessagesRequest request = SendMessagesRequest.builder() - .applicationId(appId) - .messageRequest(msgReq) - .build(); - - SendMessagesResponse response = pinpoint.sendMessages(request); - MessageResponse msg1 = response.messageResponse(); - Map map1 = msg1.result(); - - // Write out the result of sendMessage. - map1.forEach((k, v) -> System.out.println((k + ":" + v))); - - } catch (PinpointException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + String message = args[0]; + String appId = args[1]; + String originationNumber = args[2]; + String destinationNumber = args[3]; + String destinationNumber1 = args[4]; + System.out.println("Sending a message"); + PinpointClient pinpoint = PinpointClient.builder() + .region(Region.US_EAST_1) + .build(); + + sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber, destinationNumber1); + pinpoint.close(); + } + + public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, + String originationNumber, + String destinationNumber, String destinationNumber1) { + try { + Map addressMap = new HashMap(); + AddressConfiguration addConfig = AddressConfiguration.builder() + .channelType(ChannelType.SMS) + .build(); + + // Add an entry to the Map object for each number to whom you want to send a + // message. + addressMap.put(destinationNumber, addConfig); + addressMap.put(destinationNumber1, addConfig); + SMSMessage smsMessage = SMSMessage.builder() + .body(message) + .messageType(messageType) + .originationNumber(originationNumber) + .senderId(senderId) + .keyword(registeredKeyword) + .build(); + + // Create a DirectMessageConfiguration object. + DirectMessageConfiguration direct = DirectMessageConfiguration.builder() + .smsMessage(smsMessage) + .build(); + + MessageRequest msgReq = MessageRequest.builder() + .addresses(addressMap) + .messageConfiguration(direct) + .build(); + + // Create a SendMessagesRequest object. + SendMessagesRequest request = SendMessagesRequest.builder() + .applicationId(appId) + .messageRequest(msgReq) + .build(); + + SendMessagesResponse response = pinpoint.sendMessages(request); + MessageResponse msg1 = response.messageResponse(); + Map map1 = msg1.result(); + + // Write out the result of sendMessage. + map1.forEach((k, v) -> System.out.println((k + ":" + v))); + + } catch (PinpointException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } + } } // snippet-end:[pinpoint.java2.sendmsg.batch.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java index 69f727e52e3..6ed64bb779e 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java @@ -5,6 +5,7 @@ // snippet-start:[pinpoint.java2.send_voice_message.main] // snippet-start:[pinpoint.java2.send_voice_message.import] + import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient; @@ -12,6 +13,7 @@ import software.amazon.awssdk.services.pinpointsmsvoice.model.VoiceMessageContent; import software.amazon.awssdk.services.pinpointsmsvoice.model.SendVoiceMessageRequest; import software.amazon.awssdk.services.pinpointsmsvoice.model.PinpointSmsVoiceException; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -21,97 +23,95 @@ /** * Before running this Java V2 code example, set up your development * environment, including your credentials. - * + *

* For more information, see the following documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SendVoiceMessage { - // The Amazon Polly voice that you want to use to send the message. For a list - // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html - static final String voiceName = "Matthew"; - - // The language to use when sending the message. For a list of supported - // languages, see - // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html - static final String languageCode = "en-US"; - - // The content of the message. This example uses SSML to customize and control - // certain aspects of the message, such as by adding pauses and changing - // phonation. The message can't contain any line breaks. - static final String ssmlMessage = "This is a test message sent from " - + "Amazon Pinpoint " - + "using the AWS " - + "SDK for Java. " - + "Thank " - + "you for listening."; - - public static void main(String[] args) { - - final String usage = """ - - Usage: \s - - Where: - originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). - destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String originationNumber = args[0]; - String destinationNumber = args[1]; - System.out.println("Sending a voice message"); - - // Set the content type to application/json. - List listVal = new ArrayList<>(); - listVal.add("application/json"); - Map> values = new HashMap<>(); - values.put("Content-Type", listVal); - - ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder() - .headers(values) - .build(); - - PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder() - .overrideConfiguration(config2) - .region(Region.US_EAST_1) - .build(); - - sendVoiceMsg(client, originationNumber, destinationNumber); - client.close(); + // The Amazon Polly voice that you want to use to send the message. For a list + // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html + static final String voiceName = "Matthew"; + + // The language to use when sending the message. For a list of supported + // languages, see + // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html + static final String languageCode = "en-US"; + + // The content of the message. This example uses SSML to customize and control + // certain aspects of the message, such as by adding pauses and changing + // phonation. The message can't contain any line breaks. + static final String ssmlMessage = "This is a test message sent from " + + "Amazon Pinpoint " + + "using the AWS " + + "SDK for Java. " + + "Thank " + + "you for listening."; + + public static void main(String[] args) { + + final String usage = """ + Usage: \s + + Where: + originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). + destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); } - - public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber, - String destinationNumber) { - try { - SSMLMessageType ssmlMessageType = SSMLMessageType.builder() - .languageCode(languageCode) - .text(ssmlMessage) - .voiceId(voiceName) - .build(); - - VoiceMessageContent content = VoiceMessageContent.builder() - .ssmlMessage(ssmlMessageType) - .build(); - - SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder() - .destinationPhoneNumber(destinationNumber) - .originationPhoneNumber(originationNumber) - .content(content) - .build(); - - client.sendVoiceMessage(voiceMessageRequest); - System.out.println("The message was sent successfully."); - - } catch (PinpointSmsVoiceException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + String originationNumber = args[0]; + String destinationNumber = args[1]; + System.out.println("Sending a voice message"); + + // Set the content type to application/json. + List listVal = new ArrayList<>(); + listVal.add("application/json"); + Map> values = new HashMap<>(); + values.put("Content-Type", listVal); + + ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder() + .headers(values) + .build(); + + PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder() + .overrideConfiguration(config2) + .region(Region.US_EAST_1) + .build(); + + sendVoiceMsg(client, originationNumber, destinationNumber); + client.close(); + } + + public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber, + String destinationNumber) { + try { + SSMLMessageType ssmlMessageType = SSMLMessageType.builder() + .languageCode(languageCode) + .text(ssmlMessage) + .voiceId(voiceName) + .build(); + + VoiceMessageContent content = VoiceMessageContent.builder() + .ssmlMessage(ssmlMessageType) + .build(); + + SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder() + .destinationPhoneNumber(destinationNumber) + .originationPhoneNumber(originationNumber) + .content(content) + .build(); + + client.sendVoiceMessage(voiceMessageRequest); + System.out.println("The message was sent successfully."); + + } catch (PinpointSmsVoiceException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } + } } // snippet-end:[pinpoint.java2.send_voice_message.main] diff --git a/javav2/example_code/pinpoint/src/main/resources/log4j2.xml b/javav2/example_code/pinpoint/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/pinpoint/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java b/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java index de577805810..5fd28826bf9 100644 --- a/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java +++ b/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java @@ -5,6 +5,9 @@ import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; @@ -28,7 +31,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonPinpointTest { private static PinpointClient pinpoint; - + private static final Logger logger = LoggerFactory.getLogger(AmazonPinpointTest.class); private static PinpointEmailClient pinpointEmailClient; private static PinpointSmsVoiceClient voiceClient; private static S3Client s3Client; @@ -55,19 +58,16 @@ public class AmazonPinpointTest { @BeforeAll public static void setUp() throws IOException { pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); pinpointEmailClient = PinpointEmailClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); s3Client = S3Client.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); // Set the content type to application/json. List listVal = new ArrayList<>(); @@ -82,7 +82,6 @@ public static void setUp() throws IOException { voiceClient = PinpointSmsVoiceClient.builder() .overrideConfiguration(config2) .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -104,188 +103,140 @@ public static void setUp() throws IOException { destinationNumber = valuesOb.getDestinationNumber(); destinationNumber1 = valuesOb.getDestinationNumber1(); message = valuesOb.getMessage(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * AmazonPinpointTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests - * prop.load(input); - * appName = prop.getProperty("appName"); - * bucket= prop.getProperty("bucket"); - * path= prop.getProperty("path"); - * roleArn= prop.getProperty("roleArn"); - * userId = prop.getProperty("userId"); - * s3BucketName = prop.getProperty("s3BucketName"); - * s3BucketName = prop.getProperty("s3BucketName"); - * iamExportRoleArn = prop.getProperty("iamExportRoleArn"); - * existingApplicationId= prop.getProperty("existingApplicationId"); - * subject = prop.getProperty("subject"); - * senderAddress = prop.getProperty("senderAddress"); - * toAddress = prop.getProperty("toAddress"); - * originationNumber= prop.getProperty("originationNumber"); - * destinationNumber= prop.getProperty("destinationNumber"); - * destinationNumber1 = prop.getProperty("destinationNumber1"); - * message= prop.getProperty("message"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateApp() { + public void testCreateApp() { appId = CreateApp.createApplication(pinpoint, appName); assertFalse(appId.isEmpty()); - System.out.println("CreateApp test passed"); + logger.info("testCreateApp test passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void UpdateEndpoint() { + public void testUpdateEndpoint() { EndpointResponse response = UpdateEndpoint.createEndpoint(pinpoint, appId); endpointId2 = response.id(); assertFalse(endpointId2.isEmpty()); - System.out.println("UpdateEndpoint test passed"); + logger.info("UpdateEndpoint test passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void LookUpEndpoint() { + public void testLookUpEndpoint() { assertDoesNotThrow(() -> LookUpEndpoint.lookupPinpointEndpoint(pinpoint, appId, endpointId2)); - System.out.println("LookUpEndpoint test passed"); + logger.info("LookUpEndpoint test passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void AddExampleUser() { + public void testAddExampleUser() { assertDoesNotThrow(() -> AddExampleUser.updatePinpointEndpoint(pinpoint, appId, endpointId2)); - System.out.println("AddExampleUser test passed"); + logger.info("AddExampleUser test passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void AddExampleEndpoints() { + public void testAddExampleEndpoints() { assertDoesNotThrow(() -> AddExampleEndpoints.updateEndpointsViaBatch(pinpoint, appId)); - System.out.println("AddExampleEndpoints test passed"); + logger.info("AddExampleEndpoints test passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteEndpoint() { + public void testDeleteEndpoint() { assertDoesNotThrow(() -> DeleteEndpoint.deletePinEncpoint(pinpoint, appId, endpointId2)); - System.out.println("DeleteEndpoint test passed"); + logger.info("DeleteEndpoint test passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void SendMessage() { + public void testSendMessage() { assertDoesNotThrow(() -> SendMessage.sendSMSMessage(pinpoint, message, existingApplicationId, originationNumber, destinationNumber)); - System.out.println("SendMessage test passed"); + logger.info("SendMessage test passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void ImportSegments() { + public void testImportSegments() { assertDoesNotThrow(() -> SendMessageBatch.sendSMSMessage(pinpoint, message, "2fdc4442c6a2483f85eaf7a943054815", originationNumber, destinationNumber, destinationNumber)); - System.out.println("ImportSegments test passed"); + logger.info("ImportSegments test passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void ListSegments() { + public void testListSegments() { assertDoesNotThrow(() -> ListSegments.listSegs(pinpoint, appId)); - System.out.println("ListSegments test passed"); + logger.info("ListSegments test passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void CreateSegment() { + public void testCreateSegment() { SegmentResponse createSegmentResult = CreateSegment.createSegment(pinpoint, existingApplicationId); segmentId = createSegmentResult.id(); assertFalse(segmentId.isEmpty()); - System.out.println("CreateSegment test passed"); + logger.info("CreateSegment test passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void CreateCampaign() { + public void testCreateCampaign() { assertDoesNotThrow(() -> CreateCampaign.createPinCampaign(pinpoint, existingApplicationId, segmentId)); - System.out.println("CreateCampaign test passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(13) - public void ExportEndpoints() { - assertDoesNotThrow(() -> ExportEndpoints.exportAllEndpoints(pinpoint, s3Client, existingApplicationId, - s3BucketName, filePath, iamExportRoleArn)); - System.out.println("ExportEndpoints test passed"); + logger.info("CreateCampaign test passed"); } @Test @Tag("IntegrationTest") @Order(14) - public void SendEmailMessage() { + public void testSendEmailMessage() { assertDoesNotThrow(() -> SendEmailMessage.sendEmail(pinpointEmailClient, subject, senderAddress, toAddress)); - System.out.println("SendEmailMessage test passed"); + logger.info("SendEmailMessage test passed"); } @Test @Tag("IntegrationTest") @Order(15) - public void SendVoiceMessage() { + public void testSendVoiceMessage() { assertDoesNotThrow(() -> SendVoiceMessage.sendVoiceMsg(voiceClient, originationNumber, destinationNumber)); - System.out.println("SendVoiceMessage test passed"); + logger.info("SendVoiceMessage test passed"); } @Test @Tag("IntegrationTest") @Order(16) - public void ListEndpointIds() { + public void testListEndpointIds() { assertDoesNotThrow(() -> ListEndpointIds.listAllEndpoints(pinpoint, existingApplicationId, userId)); - System.out.println("ListEndpointIds test passed"); + logger.info("ListEndpointIds test passed"); } @Test @Tag("IntegrationTest") @Order(17) - public void DeleteApp() { + public void testDeleteApp() { assertDoesNotThrow(() -> DeleteApp.deletePinApp(pinpoint, appId)); - System.out.println("DeleteApp test passed"); + logger.info("DeleteApp test passed"); } public static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); String secretName = "test/pinpoint"; - GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); diff --git a/javav2/example_code/polly/pom.xml b/javav2/example_code/polly/pom.xml index feb235248f3..d73cc76dafb 100644 --- a/javav2/example_code/polly/pom.xml +++ b/javav2/example_code/polly/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -26,7 +26,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -39,11 +46,6 @@ 5.11.4 test - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk polly @@ -61,5 +63,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/polly/src/main/resources/config.properties b/javav2/example_code/polly/src/main/resources/config.properties new file mode 100644 index 00000000000..8eed3c2d153 --- /dev/null +++ b/javav2/example_code/polly/src/main/resources/config.properties @@ -0,0 +1,2 @@ +roleARN = +snsAction = diff --git a/javav2/example_code/polly/src/main/resources/log4j2.xml b/javav2/example_code/polly/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/polly/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/polly/src/test/java/AWSPollyTest.java b/javav2/example_code/polly/src/test/java/AWSPollyTest.java index 0c6fc0a9ed3..ea0f05e36fb 100644 --- a/javav2/example_code/polly/src/test/java/AWSPollyTest.java +++ b/javav2/example_code/polly/src/test/java/AWSPollyTest.java @@ -8,6 +8,8 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -19,28 +21,27 @@ public class AWSPollyTest { private static PollyClient polly; - + private static final Logger logger = LoggerFactory.getLogger(AWSPollyTest.class); @BeforeAll public static void setUp() { polly = PollyClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } @Test @Tag("IntegrationTest") @Order(1) - public void describeVoicesSample() { + public void testDescribeVoicesSample() { assertDoesNotThrow(() ->DescribeVoicesSample.describeVoice(polly)); - System.out.println("describeVoicesSample test passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void listLexicons() { + public void testListLexicons() { assertDoesNotThrow(() ->ListLexicons.listLexicons(polly)); - System.out.println("listLexicons test passed"); + logger.info("Test 2 passed"); } } diff --git a/javav2/example_code/quicksight/pom.xml b/javav2/example_code/quicksight/pom.xml index c823e781b3d..ce1c3959e6e 100644 --- a/javav2/example_code/quicksight/pom.xml +++ b/javav2/example_code/quicksight/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/quicksight/src/main/resources/log4j2.xml b/javav2/example_code/quicksight/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/quicksight/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/quicksight/src/test/java/QuickSightTest.java b/javav2/example_code/quicksight/src/test/java/QuickSightTest.java index 7b3cb0179f8..2449607c994 100644 --- a/javav2/example_code/quicksight/src/test/java/QuickSightTest.java +++ b/javav2/example_code/quicksight/src/test/java/QuickSightTest.java @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.quicksight.QuickSightClient; import org.junit.jupiter.api.*; @@ -19,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class QuickSightTest { + private static final Logger logger = LoggerFactory.getLogger(QuickSightTest.class); private static QuickSightClient qsClient; private static String account = ""; private static String analysisId = ""; @@ -30,9 +33,8 @@ public class QuickSightTest { @BeforeAll public static void setUp() { qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -44,103 +46,77 @@ public static void setUp() { templateId = values.getTemplateId(); dataSetArn = values.getDataSetArn(); analysisArn = values.getAnalysisArn(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * QuickSightTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * account = prop.getProperty("account"); - * analysisId = prop.getProperty("analysisId"); - * dashboardId = prop.getProperty("dashboardId"); - * templateId = prop.getProperty("templateId"); - * dataSetArn = prop.getProperty("dataSetArn"); - * analysisArn = prop.getProperty("analysisArn"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void DescribeAnalysis() { + public void testDescribeAnalysis() { assertDoesNotThrow(() -> DescribeAnalysis.describeSpecificAnalysis(qsClient, account, analysisId)); - System.out.println("DescribeAnalysis test passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void DescribeDashboard() { + public void testDescribeDashboard() { assertDoesNotThrow(() -> DescribeDashboard.describeSpecificDashboard(qsClient, account, dashboardId)); - System.out.println("DescribeDashboard test passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeTemplate() { + public void testDescribeTemplate() { assertDoesNotThrow(() -> DescribeTemplate.describeSpecificTemplate(qsClient, account, templateId)); - System.out.println("DescribeTemplate test passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListThemes() { + public void testListThemes() { assertDoesNotThrow(() -> ListThemes.listAllThemes(qsClient, account)); - System.out.println("ListThemes test passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") - @Order(6) - public void ListAnalyses() { + @Order(5) + public void testListAnalyses() { assertDoesNotThrow(() -> ListAnalyses.listAllAnAnalyses(qsClient, account)); - System.out.println("ListAnalyses test passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") - @Order(7) - public void ListDashboards() { + @Order(6) + public void testListDashboards() { assertDoesNotThrow(() -> ListDashboards.listAllDashboards(qsClient, account)); - System.out.println("ListDashboards test passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") - @Order(8) - public void ListTemplates() { + @Order(7) + public void testListTemplates() { assertDoesNotThrow(() -> ListTemplates.listAllTemplates(qsClient, account)); - System.out.println("ListTemplates test passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") - @Order(9) - public void UpdateDashboard() { + @Order(8) + public void testUpdateDashboard() { assertDoesNotThrow( () -> UpdateDashboard.updateSpecificDashboard(qsClient, account, dashboardId, dataSetArn, analysisArn)); - System.out.println("UpdateDashboard test passed"); + logger.info("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); String secretName = "test/quicksight"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() diff --git a/javav2/example_code/rds/pom.xml b/javav2/example_code/rds/pom.xml index e1611fdbde7..9f79c5348d6 100644 --- a/javav2/example_code/rds/pom.xml +++ b/javav2/example_code/rds/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -87,5 +94,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java b/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java index b663e4e6946..8c22ffb6621 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java @@ -206,9 +206,8 @@ public static void main(String[] args) throws InterruptedException { private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .build(); } public static String getSecretValues(String secretName) { diff --git a/javav2/example_code/rds/src/main/resources/log4j2.xml b/javav2/example_code/rds/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/rds/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/rds/src/test/java/AmazonRDSTest.java b/javav2/example_code/rds/src/test/java/AmazonRDSTest.java index fe08d3ba504..b6b8e0544e0 100644 --- a/javav2/example_code/rds/src/test/java/AmazonRDSTest.java +++ b/javav2/example_code/rds/src/test/java/AmazonRDSTest.java @@ -3,6 +3,8 @@ import com.example.rds.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.rds.RdsClient; import org.junit.jupiter.api.*; @@ -22,7 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonRDSTest { - + private static final Logger logger = LoggerFactory.getLogger(AmazonRDSTest.class); private static RdsClient rdsClient; private static String dbInstanceIdentifier = ""; @@ -48,9 +50,8 @@ public class AmazonRDSTest { @BeforeAll public static void setUp() throws IOException { rdsClient = RdsClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .build(); Random rand = new Random(); int randomNum = rand.nextInt((10000 - 1) + 1) + 1; @@ -72,109 +73,72 @@ public static void setUp() throws IOException { dbParameterGroupFamily = values.getDbParameterGroupFamily(); dbInstanceClusterIdentifier = values.getDbInstanceClusterIdentifier(); secretDBName = values.getSecretName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonRDSTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * dbInstanceIdentifier = prop.getProperty("dbInstanceIdentifier")+ - * java.util.UUID.randomUUID(); - * dbSnapshotIdentifier = prop.getProperty("dbSnapshotIdentifier")+ - * java.util.UUID.randomUUID(); - * dbName = prop.getProperty("dbName")+ randomNum; - * masterUsername = prop.getProperty("masterUsername"); - * masterUserPassword = prop.getProperty("masterUserPassword"); - * newMasterUserPassword = prop.getProperty("newMasterUserPassword"); - * dbGroupNameSc = prop.getProperty("dbGroupNameSc")+ - * java.util.UUID.randomUUID();; - * dbParameterGroupFamilySc = prop.getProperty("dbParameterGroupFamilySc"); - * dbInstanceIdentifierSc = prop.getProperty("dbInstanceIdentifierSc")+ - * java.util.UUID.randomUUID();; - * masterUsernameSc = prop.getProperty("masterUsernameSc"); - * masterUserPasswordSc = prop.getProperty("masterUserPasswordSc"); - * dbSnapshotIdentifierSc = prop.getProperty("dbSnapshotIdentifierSc")+ - * java.util.UUID.randomUUID();; - * dbNameSc = prop.getProperty("dbNameSc")+ randomNum ; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateDBInstance() { + public void testCreateDBInstance() { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); assertDoesNotThrow(() -> CreateDBInstance.createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword())); - System.out.println("CreateDBInstance test passed"); + logger.info("\nTest 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void waitForInstanceReady() { + public void testWaitForInstanceReady() { assertDoesNotThrow(() -> CreateDBInstance.waitForInstanceReady(rdsClient, dbInstanceIdentifier)); - System.out.println("waitForInstanceReady test passed"); + logger.info("\nTest 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeAccountAttributes() { + public void testDescribeAccountAttributes() { assertDoesNotThrow(() -> DescribeAccountAttributes.getAccountAttributes(rdsClient)); - System.out.println("DescribeAccountAttributes test passed"); + logger.info("\nTest 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DescribeDBInstances() { + public void testDescribeDBInstances() { assertDoesNotThrow(() -> DescribeDBInstances.describeInstances(rdsClient)); - System.out.println("DescribeDBInstances test passed"); + logger.info("\nTest 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ModifyDBInstance() { + public void testModifyDBInstance() { assertDoesNotThrow( () -> ModifyDBInstance.updateIntance(rdsClient, dbInstanceIdentifier, newMasterUserPassword)); - System.out.println("ModifyDBInstance test passed"); + logger.info("\nTest 5 passed"); } @Test @Order(6) - public void CreateDBSnapshot() { + public void testCreateDBSnapshot() { assertDoesNotThrow( () -> CreateDBSnapshot.createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier)); - System.out.println("CreateDBSnapshot test passed"); + logger.info("\nTest 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteDBInstance() { + public void testDeleteDBInstance() { assertDoesNotThrow(() -> DeleteDBInstance.deleteDatabaseInstance(rdsClient, dbInstanceIdentifier)); - System.out.println("DeleteDBInstance test passed"); + logger.info("\nTest 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void TestRDSScenario() { + public void testRDSScenario() { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); assertDoesNotThrow(() -> RDSScenario.describeDBEngines(rdsClient)); @@ -195,13 +159,13 @@ public void TestRDSScenario() { () -> RDSScenario.waitForSnapshotReady(rdsClient, dbInstanceIdentifierSc, dbSnapshotIdentifierSc)); assertDoesNotThrow(() -> RDSScenario.deleteDatabaseInstance(rdsClient, dbInstanceIdentifierSc)); assertDoesNotThrow(() -> RDSScenario.deleteParaGroup(rdsClient, dbGroupNameSc, dbARN)); - System.out.println("TestRDSScenario test passed"); + logger.info("\nTest 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void TestAuroraScenario() throws InterruptedException { + public void testAuroraScenario() throws InterruptedException { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); System.out.println("1. Return a list of the available DB engines"); @@ -245,16 +209,14 @@ public void TestAuroraScenario() throws InterruptedException { assertDoesNotThrow(() -> AuroraScenario.deleteCluster(rdsClient, dbInstanceClusterIdentifier)); System.out.println("16. Delete the DB cluster group"); assertDoesNotThrow(() -> AuroraScenario.deleteDBClusterGroup(rdsClient, dbClusterGroupName, clusterDBARN)); - System.out.println("TestAuroraScenario test passed"); + logger.info("\nTest 9 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .build(); String secretName = "test/rds"; - GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); diff --git a/javav2/example_code/redshift/pom.xml b/javav2/example_code/redshift/pom.xml index 8fcd867cc7c..d09cff89d40 100644 --- a/javav2/example_code/redshift/pom.xml +++ b/javav2/example_code/redshift/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -41,7 +41,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/scenario/RedshiftActions.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/scenario/RedshiftActions.java index 08230275c15..9d7ac07b810 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/scenario/RedshiftActions.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/scenario/RedshiftActions.java @@ -69,7 +69,6 @@ private static RedshiftAsyncClient getAsyncClient() { redshiftAsyncClient = RedshiftAsyncClient.builder() .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return redshiftAsyncClient; @@ -93,7 +92,6 @@ private static RedshiftDataAsyncClient getAsyncDataClient() { redshiftDataAsyncClient = RedshiftDataAsyncClient.builder() .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return redshiftDataAsyncClient; diff --git a/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java b/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java index 70e56cec6b7..a25f1068efb 100644 --- a/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java +++ b/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java @@ -7,6 +7,9 @@ import com.google.gson.Gson; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.redshift.RedshiftClient; @@ -31,28 +34,21 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonRedshiftTest { + private static final Logger logger = LoggerFactory.getLogger(AmazonRedshiftTest.class); private static RedshiftClient redshiftClient; - private static RedshiftDataClient redshiftDataClient; - static RedshiftActions redshiftActions = new RedshiftActions(); private static String clusterId = ""; - private static String fileNameSc = ""; - private static String userName = ""; - private static String userPassword = "" ; - private static String databaseName = "" ; - private static String id; @BeforeAll public static void setUp() { redshiftClient = RedshiftClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); redshiftDataClient = RedshiftDataClient.builder() @@ -71,25 +67,24 @@ public static void setUp() { userName = values.getUserName(); userPassword = values.getPassword(); fileNameSc = values.getFileName(); - } @Test @Tag("IntegrationTest") @Order(1) - public void helloRedshift() { + public void testHelloRedshift() { assertDoesNotThrow(() -> HelloRedshift.listClustersPaginator(redshiftClient)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void createCluster() { + public void testCreateCluster() { try { CompletableFuture future = redshiftActions.createClusterAsync(clusterId, userName, userPassword); future.join(); - System.out.println("Cluster successfully created."); + logger.info("Cluster successfully created."); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); @@ -99,110 +94,110 @@ public void createCluster() { System.out.println("An unexpected error occurred: " + rt.getMessage()); } } + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void waitCluster() { + public void testWaitCluster() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.waitForClusterReadyAsync(clusterId); future.join(); }); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void listDatabases() { + public void testListDatabases() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.listAllDatabasesAsync(clusterId, userName, "dev"); future.join(); }); - System.out.println("Test 3 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void createDatabaseTable() { + public void testCreateDatabaseTable() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.createTableAsync(clusterId, databaseName, userName); future.join(); }); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void popDatabaseTable() { + public void testPopDatabaseTable() { assertDoesNotThrow(() -> { redshiftActions.popTableAsync(clusterId, databaseName, userName, fileNameSc, 50).join(); }); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void queryDatabaseTable() { + public void testQueryDatabaseTable() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.queryMoviesByYearAsync(databaseName, userName, 2014, clusterId); id = future.join(); }); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void checkStatement() { + public void testCheckStatement() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.checkStatementAsync(id); future.join(); }); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void getResults() { + public void testGetResults() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.getResultsAsync(id); future.join(); }); - System.out.println("Test 9 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void modifyDatabase() { + public void testModifyDatabase() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.modifyClusterAsync(clusterId);; future.join(); }); - System.out.println("Test 10 passed"); + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void deleteDatabase() { + public void testDeleteDatabase() { assertDoesNotThrow(() -> { CompletableFuture future = redshiftActions.deleteRedshiftClusterAsync(clusterId);; future.join(); }); - System.out.println("Test 11 passed"); + logger.info("Test 11 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/red"; diff --git a/javav2/example_code/rekognition/pom.xml b/javav2/example_code/rekognition/pom.xml index 231a4dd8d50..bdfc10a0870 100644 --- a/javav2/example_code/rekognition/pom.xml +++ b/javav2/example_code/rekognition/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -87,5 +94,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java index cedd0758be9..cfe8a9ae26e 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java @@ -5,21 +5,9 @@ // snippet-start:[rekognition.java2.add_faces_collection.main] // snippet-start:[rekognition.java2.add_faces_collection.import] -import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.IndexFacesResponse; -import software.amazon.awssdk.services.rekognition.model.IndexFacesRequest; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.QualityFilter; -import software.amazon.awssdk.services.rekognition.model.Attribute; -import software.amazon.awssdk.services.rekognition.model.FaceRecord; -import software.amazon.awssdk.services.rekognition.model.UnindexedFace; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; -import software.amazon.awssdk.services.rekognition.model.Reason; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; +import software.amazon.awssdk.services.rekognition.model.*; import java.util.List; // snippet-end:[rekognition.java2.add_faces_collection.import] @@ -33,43 +21,55 @@ */ public class AddFacesToCollection { public static void main(String[] args) { - final String usage = """ + Usage: - Usage: - - Where: - collectionName - The name of the collection. - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + collectionName - The name of the collection. + sourceImage - The name of the image (for example, pic1.png). + bucketName - The name of the S3 bucket. + """; - if (args.length != 2) { + if (args.length != 3) { System.out.println(usage); System.exit(1); } String collectionId = args[0]; String sourceImage = args[1]; + String bucketName = args[2];; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - addToCollection(rekClient, collectionId, sourceImage); + addToCollection(rekClient, collectionId, bucketName, sourceImage); rekClient.close(); } - public static void addToCollection(RekognitionClient rekClient, String collectionId, String sourceImage) { + /** + * Adds a face from an image to an Amazon Rekognition collection. + * + * @param rekClient the Amazon Rekognition client + * @param collectionId the ID of the collection to add the face to + * @param bucketName the name of the Amazon S3 bucket containing the image + * @param sourceImage the name of the image file to add to the collection + * @throws RekognitionException if there is an error while interacting with the Amazon Rekognition service + */ + public static void addToCollection(RekognitionClient rekClient, String collectionId, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); - Image souImage = Image.builder() - .bytes(sourceBytes) + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); + + Image targetImage = Image.builder() + .s3Object(s3ObjectTarget) .build(); IndexFacesRequest facesRequest = IndexFacesRequest.builder() .collectionId(collectionId) - .image(souImage) + .image(targetImage) .maxFaces(1) .qualityFilter(QualityFilter.AUTO) .detectionAttributes(Attribute.DEFAULT) @@ -94,7 +94,7 @@ public static void addToCollection(RekognitionClient rekClient, String collectio } } - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java index 5b8d80c7e1c..aabf625ab1e 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java @@ -36,7 +36,7 @@ public static void main(String[] args) { } String id = args[0]; - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); @@ -45,6 +45,13 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Retrieves information about a celebrity identified in an image. + * + * @param rekClient the Amazon Rekognition client used to make the API call + * @param id the unique identifier of the celebrity + * @throws RekognitionException if there is an error retrieving the celebrity information + */ public static void getCelebrityInfo(RekognitionClient rekClient, String id) { try { GetCelebrityInfoRequest info = GetCelebrityInfoRequest.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java index 809b653e6f6..03c2bf62ca9 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java @@ -8,13 +8,7 @@ import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.CompareFacesRequest; -import software.amazon.awssdk.services.rekognition.model.CompareFacesResponse; -import software.amazon.awssdk.services.rekognition.model.CompareFacesMatch; -import software.amazon.awssdk.services.rekognition.model.ComparedFace; -import software.amazon.awssdk.services.rekognition.model.BoundingBox; +import software.amazon.awssdk.services.rekognition.model.*; import software.amazon.awssdk.core.SdkBytes; import java.io.FileInputStream; @@ -34,73 +28,88 @@ public class CompareFaces { public static void main(String[] args) { final String usage = """ - - Usage: - + Usage: + Where: - pathSource - The path to the source image (for example, C:\\AWS\\pic1.png).\s - pathTarget - The path to the target image (for example, C:\\AWS\\pic2.png).\s - """; + bucketName - The name of the S3 bucket where the images are stored. + sourceKey - The S3 key (file name) for the source image. + targetKey - The S3 key (file name) for the target image. + """; - if (args.length != 2) { + if (args.length != 3) { System.out.println(usage); System.exit(1); } - Float similarityThreshold = 70F; - String sourceImage = args[0]; - String targetImage = args[1]; - Region region = Region.US_EAST_1; + String bucketName = args[0]; + String sourceKey = args[1]; + String targetKey = args[2]; + + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); + compareTwoFaces(rekClient, bucketName, sourceKey, targetKey); + } + + /** + * Compares two faces from images stored in an Amazon S3 bucket using AWS Rekognition. + * + *

This method takes two image keys from an S3 bucket and compares the faces within them. + * It prints out the confidence level of matched faces and reports the number of unmatched faces.

+ * + * @param rekClient The {@link RekognitionClient} used to call AWS Rekognition. + * @param bucketName The name of the S3 bucket containing the images. + * @param sourceKey The object key (file path) for the source image in the S3 bucket. + * @param targetKey The object key (file path) for the target image in the S3 bucket. + * @throws RuntimeException If the Rekognition service returns an error. + */ + public static void compareTwoFaces(RekognitionClient rekClient, String bucketName, String sourceKey, String targetKey) { + try { + Float similarityThreshold = 70F; + S3Object s3ObjectSource = S3Object.builder() + .bucket(bucketName) + .name(sourceKey) + .build(); - compareTwoFaces(rekClient, similarityThreshold, sourceImage, targetImage); - rekClient.close(); - } + Image sourceImage = Image.builder() + .s3Object(s3ObjectSource) + .build(); - public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, - String targetImage) { - try { - InputStream sourceStream = new FileInputStream(sourceImage); - InputStream tarStream = new FileInputStream(targetImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); - SdkBytes targetBytes = SdkBytes.fromInputStream(tarStream); - - // Create an Image object for the source image. - Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(targetKey) + .build(); - Image tarImage = Image.builder() - .bytes(targetBytes) - .build(); + Image targetImage = Image.builder() + .s3Object(s3ObjectTarget) + .build(); CompareFacesRequest facesRequest = CompareFacesRequest.builder() - .sourceImage(souImage) - .targetImage(tarImage) - .similarityThreshold(similarityThreshold) - .build(); + .sourceImage(sourceImage) + .targetImage(targetImage) + .similarityThreshold(similarityThreshold) + .build(); // Compare the two images. CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest); List faceDetails = compareFacesResult.faceMatches(); + for (CompareFacesMatch match : faceDetails) { ComparedFace face = match.face(); BoundingBox position = face.boundingBox(); System.out.println("Face at " + position.left().toString() - + " " + position.top() - + " matches with " + face.confidence().toString() - + "% confidence."); - + + " " + position.top() + + " matches with " + face.confidence().toString() + + "% confidence."); } - List uncompared = compareFacesResult.unmatchedFaces(); - System.out.println("There was " + uncompared.size() + " face(s) that did not match"); - System.out.println("Source image rotation: " + compareFacesResult.sourceImageOrientationCorrection()); - System.out.println("target image rotation: " + compareFacesResult.targetImageOrientationCorrection()); - } catch (RekognitionException | FileNotFoundException e) { - e.printStackTrace(); + List unmatchedFaces = compareFacesResult.unmatchedFaces(); + System.out.println("There were " + unmatchedFaces.size() + " face(s) that did not match."); + + } catch (RekognitionException e) { + System.err.println("Error comparing faces: " + e.awsErrorDetails().errorMessage()); + throw new RuntimeException(e); } } } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java index 4e4b588a2c0..b5311b05268 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java @@ -24,11 +24,11 @@ public class CreateCollection { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - collectionName - The name of the collection.\s - """; + Where: + collectionName - The name of the collection.\s + """; if (args.length != 1) { System.out.println(usage); @@ -36,7 +36,7 @@ public static void main(String[] args) { } String collectionId = args[0]; - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); @@ -46,6 +46,12 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Creates a new Amazon Rekognition collection. + * + * @param rekClient the Amazon Rekognition client used to interact with the Rekognition service + * @param collectionId the unique identifier for the collection to be created + */ public static void createMyCollection(RekognitionClient rekClient, String collectionId) { try { CreateCollectionRequest collectionRequest = CreateCollectionRequest.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java index e254ef636a7..b08a7e9d2eb 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java @@ -5,6 +5,7 @@ // snippet-start:[rekognition.java2.create_streamprocessor.main] // snippet-start:[rekognition.java2.create_streamprocessor.import] + import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.services.rekognition.model.CreateStreamProcessorRequest; @@ -27,148 +28,148 @@ /** * Before running this Java V2 code example, set up your development * environment, including your credentials. - * + *

* For more information, see the following documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateStreamProcessor { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - role - The ARN of the AWS Identity and Access Management (IAM) role to use. \s - kinInputStream - The ARN of the Kinesis video stream.\s - kinOutputStream - The ARN of the Kinesis data stream.\s - collectionName - The name of the collection to use that contains content. \s - StreamProcessorName - The name of the Stream Processor. \s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String role = args[0]; - String kinInputStream = args[1]; - String kinOutputStream = args[2]; - String collectionName = args[3]; - String streamProcessorName = args[4]; - - Region region = Region.US_EAST_1; - RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); - - processCollection(rekClient, streamProcessorName, kinInputStream, kinOutputStream, collectionName, - role); - startSpecificStreamProcessor(rekClient, streamProcessorName); - listStreamProcessors(rekClient); - describeStreamProcessor(rekClient, streamProcessorName); - deleteSpecificStreamProcessor(rekClient, streamProcessorName); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + role - The ARN of the AWS Identity and Access Management (IAM) role to use. \s + kinInputStream - The ARN of the Kinesis video stream.\s + kinOutputStream - The ARN of the Kinesis data stream.\s + collectionName - The name of the collection to use that contains content. \s + StreamProcessorName - The name of the Stream Processor. \s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); } - public static void listStreamProcessors(RekognitionClient rekClient) { - ListStreamProcessorsRequest request = ListStreamProcessorsRequest.builder() - .maxResults(15) - .build(); - - ListStreamProcessorsResponse listStreamProcessorsResult = rekClient.listStreamProcessors(request); - for (StreamProcessor streamProcessor : listStreamProcessorsResult.streamProcessors()) { - System.out.println("StreamProcessor name - " + streamProcessor.name()); - System.out.println("Status - " + streamProcessor.status()); - } + String role = args[0]; + String kinInputStream = args[1]; + String kinOutputStream = args[2]; + String collectionName = args[3]; + String streamProcessorName = args[4]; + + Region region = Region.US_EAST_1; + RekognitionClient rekClient = RekognitionClient.builder() + .region(region) + .build(); + + processCollection(rekClient, streamProcessorName, kinInputStream, kinOutputStream, collectionName, + role); + startSpecificStreamProcessor(rekClient, streamProcessorName); + listStreamProcessors(rekClient); + describeStreamProcessor(rekClient, streamProcessorName); + deleteSpecificStreamProcessor(rekClient, streamProcessorName); + } + + public static void listStreamProcessors(RekognitionClient rekClient) { + ListStreamProcessorsRequest request = ListStreamProcessorsRequest.builder() + .maxResults(15) + .build(); + + ListStreamProcessorsResponse listStreamProcessorsResult = rekClient.listStreamProcessors(request); + for (StreamProcessor streamProcessor : listStreamProcessorsResult.streamProcessors()) { + System.out.println("StreamProcessor name - " + streamProcessor.name()); + System.out.println("Status - " + streamProcessor.status()); } - - private static void describeStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - DescribeStreamProcessorRequest streamProcessorRequest = DescribeStreamProcessorRequest.builder() - .name(StreamProcessorName) - .build(); - - DescribeStreamProcessorResponse describeStreamProcessorResult = rekClient - .describeStreamProcessor(streamProcessorRequest); - System.out.println("Arn - " + describeStreamProcessorResult.streamProcessorArn()); - System.out.println("Input kinesisVideo stream - " - + describeStreamProcessorResult.input().kinesisVideoStream().arn()); - System.out.println("Output kinesisData stream - " - + describeStreamProcessorResult.output().kinesisDataStream().arn()); - System.out.println("RoleArn - " + describeStreamProcessorResult.roleArn()); - System.out.println( - "CollectionId - " - + describeStreamProcessorResult.settings().faceSearch().collectionId()); - System.out.println("Status - " + describeStreamProcessorResult.status()); - System.out.println("Status message - " + describeStreamProcessorResult.statusMessage()); - System.out.println("Creation timestamp - " + describeStreamProcessorResult.creationTimestamp()); - System.out.println("Last update timestamp - " + describeStreamProcessorResult.lastUpdateTimestamp()); + } + + private static void describeStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + DescribeStreamProcessorRequest streamProcessorRequest = DescribeStreamProcessorRequest.builder() + .name(StreamProcessorName) + .build(); + + DescribeStreamProcessorResponse describeStreamProcessorResult = rekClient + .describeStreamProcessor(streamProcessorRequest); + System.out.println("Arn - " + describeStreamProcessorResult.streamProcessorArn()); + System.out.println("Input kinesisVideo stream - " + + describeStreamProcessorResult.input().kinesisVideoStream().arn()); + System.out.println("Output kinesisData stream - " + + describeStreamProcessorResult.output().kinesisDataStream().arn()); + System.out.println("RoleArn - " + describeStreamProcessorResult.roleArn()); + System.out.println( + "CollectionId - " + + describeStreamProcessorResult.settings().faceSearch().collectionId()); + System.out.println("Status - " + describeStreamProcessorResult.status()); + System.out.println("Status message - " + describeStreamProcessorResult.statusMessage()); + System.out.println("Creation timestamp - " + describeStreamProcessorResult.creationTimestamp()); + System.out.println("Last update timestamp - " + describeStreamProcessorResult.lastUpdateTimestamp()); + } + + private static void startSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + try { + StartStreamProcessorRequest streamProcessorRequest = StartStreamProcessorRequest.builder() + .name(StreamProcessorName) + .build(); + + rekClient.startStreamProcessor(streamProcessorRequest); + System.out.println("Stream Processor " + StreamProcessorName + " started."); + + } catch (RekognitionException e) { + System.out.println(e.getMessage()); + System.exit(1); } - - private static void startSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - try { - StartStreamProcessorRequest streamProcessorRequest = StartStreamProcessorRequest.builder() - .name(StreamProcessorName) - .build(); - - rekClient.startStreamProcessor(streamProcessorRequest); - System.out.println("Stream Processor " + StreamProcessorName + " started."); - - } catch (RekognitionException e) { - System.out.println(e.getMessage()); - System.exit(1); - } - } - - private static void processCollection(RekognitionClient rekClient, String StreamProcessorName, - String kinInputStream, String kinOutputStream, String collectionName, String role) { - try { - KinesisVideoStream videoStream = KinesisVideoStream.builder() - .arn(kinInputStream) - .build(); - - KinesisDataStream dataStream = KinesisDataStream.builder() - .arn(kinOutputStream) - .build(); - - StreamProcessorOutput processorOutput = StreamProcessorOutput.builder() - .kinesisDataStream(dataStream) - .build(); - - StreamProcessorInput processorInput = StreamProcessorInput.builder() - .kinesisVideoStream(videoStream) - .build(); - - FaceSearchSettings searchSettings = FaceSearchSettings.builder() - .faceMatchThreshold(75f) - .collectionId(collectionName) - .build(); - - StreamProcessorSettings processorSettings = StreamProcessorSettings.builder() - .faceSearch(searchSettings) - .build(); - - CreateStreamProcessorRequest processorRequest = CreateStreamProcessorRequest.builder() - .name(StreamProcessorName) - .input(processorInput) - .output(processorOutput) - .roleArn(role) - .settings(processorSettings) - .build(); - - CreateStreamProcessorResponse response = rekClient.createStreamProcessor(processorRequest); - System.out.println("The ARN for the newly create stream processor is " - + response.streamProcessorArn()); - - } catch (RekognitionException e) { - System.out.println(e.getMessage()); - System.exit(1); - } + } + + private static void processCollection(RekognitionClient rekClient, String StreamProcessorName, + String kinInputStream, String kinOutputStream, String collectionName, String role) { + try { + KinesisVideoStream videoStream = KinesisVideoStream.builder() + .arn(kinInputStream) + .build(); + + KinesisDataStream dataStream = KinesisDataStream.builder() + .arn(kinOutputStream) + .build(); + + StreamProcessorOutput processorOutput = StreamProcessorOutput.builder() + .kinesisDataStream(dataStream) + .build(); + + StreamProcessorInput processorInput = StreamProcessorInput.builder() + .kinesisVideoStream(videoStream) + .build(); + + FaceSearchSettings searchSettings = FaceSearchSettings.builder() + .faceMatchThreshold(75f) + .collectionId(collectionName) + .build(); + + StreamProcessorSettings processorSettings = StreamProcessorSettings.builder() + .faceSearch(searchSettings) + .build(); + + CreateStreamProcessorRequest processorRequest = CreateStreamProcessorRequest.builder() + .name(StreamProcessorName) + .input(processorInput) + .output(processorOutput) + .roleArn(role) + .settings(processorSettings) + .build(); + + CreateStreamProcessorResponse response = rekClient.createStreamProcessor(processorRequest); + System.out.println("The ARN for the newly create stream processor is " + + response.streamProcessorArn()); + + } catch (RekognitionException e) { + System.out.println(e.getMessage()); + System.exit(1); } + } - private static void deleteSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - rekClient.stopStreamProcessor(a -> a.name(StreamProcessorName)); - rekClient.deleteStreamProcessor(a -> a.name(StreamProcessorName)); - System.out.println("Stream Processor " + StreamProcessorName + " deleted."); - } + private static void deleteSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + rekClient.stopStreamProcessor(a -> a.name(StreamProcessorName)); + rekClient.deleteStreamProcessor(a -> a.name(StreamProcessorName)); + System.out.println("Stream Processor " + StreamProcessorName + " deleted."); + } } // snippet-end:[rekognition.java2.create_streamprocessor.main] diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java index 21ce462ffb9..04ee85244ce 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java @@ -23,12 +23,11 @@ public class DeleteCollection { public static void main(String[] args) { final String usage = """ + Usage: \s - Usage: \s - - Where: - collectionId - The id of the collection to delete.\s - """; + Where: + collectionId - The id of the collection to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,6 +45,12 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Deletes an Amazon Rekognition collection. + * + * @param rekClient An instance of the {@link RekognitionClient} class, which is used to interact with the Amazon Rekognition service. + * @param collectionId The ID of the collection to be deleted. + */ public static void deleteMyCollection(RekognitionClient rekClient, String collectionId) { try { DeleteCollectionRequest deleteCollectionRequest = DeleteCollectionRequest.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java index fb86da10ef8..e868b806681 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java @@ -22,16 +22,14 @@ public class DeleteFacesFromCollection { public static void main(String[] args) { final String usage = """ + Usage: \s - Usage: \s + Where: + collectionId - The id of the collection from which faces are deleted.\s + faceId - The id of the face to delete.\s + """; - Where: - collectionId - The id of the collection from which faces are deleted.\s - - faceId - The id of the face to delete.\s - """; - - if (args.length != 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); } @@ -48,6 +46,14 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Deletes a face from the specified Amazon Rekognition collection. + * + * @param rekClient an instance of the Amazon Rekognition client + * @param collectionId the ID of the collection from which the face should be deleted + * @param faceId the ID of the face to be deleted + * @throws RekognitionException if an error occurs while deleting the face + */ public static void deleteFacesCollection(RekognitionClient rekClient, String collectionId, String faceId) { diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java index 6b4b59c00f0..160a9be82c9 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java @@ -23,12 +23,11 @@ public class DescribeCollection { public static void main(String[] args) { final String usage = """ + Usage: - Usage: - - Where: - collectionName - The name of the Amazon Rekognition collection.\s - """; + Where: + collectionName - The name of the Amazon Rekognition collection.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,6 +44,14 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Describes an Amazon Rekognition collection. + * + * @param rekClient The Amazon Rekognition client used to make the request. + * @param collectionName The name of the collection to describe. + * + * @throws RekognitionException If an error occurs while describing the collection. + */ public static void describeColl(RekognitionClient rekClient, String collectionName) { try { DescribeCollectionRequest describeCollectionRequest = DescribeCollectionRequest.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java index 2494a51bcea..4eb375c20ad 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java @@ -16,12 +16,12 @@ public class DetectCustomLabels { public static void main(String[] args) { final String USAGE = """ - Usage: DetectLabels + Usage: Where: - project arn - the arn of the model in Rekognition Custom Labels to the image (for example, arn:aws:rekognition:us-east-1:XXXXXXXXXXXX:project/YOURPROJECT/version/YOURPROJECT.YYYY-MM-DDT00.00.00/1234567890123).\s - S3 bucket - the bucket where your image is stored (for example, my-bucket-name\s - S3 key - the path of the image inside your bucket (for example, myfolder/pic1.png).\s + arn - the arn of the model in Rekognition Custom Labels to the image (for example, arn:aws:rekognition:us-east-1:XXXXXXXXXXXX:project/YOURPROJECT/version/YOURPROJECT.YYYY-MM-DDT00.00.00/1234567890123).\s + bucketName - the bucket where your image is stored (for example, my-bucket-name\s + key - the path of the image inside your bucket (for example, myfolder/pic1.png).\s """; if (args.length != 3) { @@ -40,6 +40,16 @@ public static void main(String[] args) { detectImageCustomLabels(rekClient, arn, bucket, key ); rekClient.close(); } + + + /** + * Detects custom labels in an image using an AWS Rekognition custom model. + * + * @param rekClient the AWS Rekognition client to use for the detection + * @param arn the Amazon Resource Name (ARN) of the custom model to use for the detection + * @param bucket the name of the S3 bucket where the image is stored + * @param key the key (file name) of the image in the S3 bucket + */ public static void detectImageCustomLabels(RekognitionClient rekClient, String arn, String bucket, String key ) { try { S3Object s3Object = S3Object.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java index 1534c9ed68f..f3eb95cb124 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java @@ -5,69 +5,71 @@ // snippet-start:[rekognition.java2.detect_faces.main] // snippet-start:[rekognition.java2.detect_faces.import] + import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; -import software.amazon.awssdk.services.rekognition.model.DetectFacesRequest; -import software.amazon.awssdk.services.rekognition.model.DetectFacesResponse; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.Attribute; -import software.amazon.awssdk.services.rekognition.model.FaceDetail; -import software.amazon.awssdk.services.rekognition.model.AgeRange; -import software.amazon.awssdk.core.SdkBytes; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; +import software.amazon.awssdk.services.rekognition.model.*; + import java.util.List; // snippet-end:[rekognition.java2.detect_faces.import] /** * Before running this Java V2 code example, set up your development * environment, including your credentials. - * + *

* For more information, see the following documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DetectFaces { public static void main(String[] args) { final String usage = """ + + Usage: + + Where: + bucketName = The name of the Amazon S3 bucket where the source image is stored. + sourceImage - The name of the source image file in the Amazon S3 bucket. (for example, pic1.png).\s + """; - Usage: - - Where: - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; - - if (args.length != 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); } - String sourceImage = args[0]; - Region region = Region.US_EAST_1; + String bucketName = args[0]; + String sourceImage = args[1]; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - detectFacesinImage(rekClient, sourceImage); + detectFacesinImage(rekClient, bucketName, sourceImage); rekClient.close(); } - public static void detectFacesinImage(RekognitionClient rekClient, String sourceImage) { + /** + * Detects faces in an image stored in an Amazon S3 bucket using the Amazon Rekognition service. + * + * @param rekClient The Amazon Rekognition client used to interact with the Rekognition service. + * @param bucketName The name of the Amazon S3 bucket where the source image is stored. + * @param sourceImage The name of the source image file in the Amazon S3 bucket. + */ + public static void detectFacesinImage(RekognitionClient rekClient, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); - // Create an Image object for the source image. - Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + Image targetImage = Image.builder() + .s3Object(s3ObjectTarget) + .build(); DetectFacesRequest facesRequest = DetectFacesRequest.builder() - .attributes(Attribute.ALL) - .image(souImage) - .build(); + .attributes(Attribute.ALL) + .image(targetImage) + .build(); DetectFacesResponse facesResponse = rekClient.detectFaces(facesRequest); List faceDetails = facesResponse.faceDetails(); @@ -80,7 +82,7 @@ public static void detectFacesinImage(RekognitionClient rekClient, String source System.out.println("There is a smile : " + face.smile().value().toString()); } - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java index fbcee551dcd..df4a1b93719 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java @@ -8,11 +8,8 @@ import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.DetectLabelsRequest; -import software.amazon.awssdk.services.rekognition.model.DetectLabelsResponse; -import software.amazon.awssdk.services.rekognition.model.Label; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; +import software.amazon.awssdk.services.rekognition.model.*; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; @@ -30,36 +27,45 @@ public class DetectLabels { public static void main(String[] args) { final String usage = """ + Usage: - Usage: - - Where: - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + bucketName - The name of the Amazon S3 bucket where the image is stored + sourceImage - The name of the image file (for example, pic1.png).\s + """; - if (args.length != 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); } - String sourceImage = args[0]; - Region region = Region.US_EAST_1; + String bucketName = args[0] ; + String sourceImage = args[1] ; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - detectImageLabels(rekClient, sourceImage); + detectImageLabels(rekClient, bucketName, sourceImage); rekClient.close(); } - public static void detectImageLabels(RekognitionClient rekClient, String sourceImage) { + /** + * Detects the labels in an image stored in an Amazon S3 bucket using the Amazon Rekognition service. + * + * @param rekClient the Amazon Rekognition client used to make the detection request + * @param bucketName the name of the Amazon S3 bucket where the image is stored + * @param sourceImage the name of the image file to be analyzed + */ + public static void detectImageLabels(RekognitionClient rekClient, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); - // Create an Image object for the source image. Image souImage = Image.builder() - .bytes(sourceBytes) + .s3Object(s3ObjectTarget) .build(); DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder() @@ -74,7 +80,7 @@ public static void detectImageLabels(RekognitionClient rekClient, String sourceI System.out.println(label.name() + ": " + label.confidence().toString()); } - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java index 1d6802eec29..de39dc18d4f 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java @@ -32,7 +32,8 @@ public static void main(String[] args) { Usage: Where: - bucket - The name of the Amazon S3 bucket that contains the image (for example, ,ImageBucket). image - The name of the image located in the Amazon S3 bucket (for example, Lake.png).\s + bucket - The name of the Amazon S3 bucket that contains the image (for example, ImageBucket). + image - The name of the image located in the Amazon S3 bucket (for example, Lake.png).\s """; if (args.length != 2) { @@ -51,6 +52,13 @@ public static void main(String[] args) { rekClient.close(); } + /** + * Retrieves labels from an image stored in an Amazon S3 bucket using the Amazon Rekognition service. + * + * @param rekClient the Amazon Rekognition client instance + * @param bucket the name of the S3 bucket where the image is stored + * @param image the name of the image file in the S3 bucket + */ public static void getLabelsfromImage(RekognitionClient rekClient, String bucket, String image) { try { S3Object s3Object = S3Object.builder() diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectModerationLabels.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectModerationLabels.java index d013642e467..85aa2b879e6 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectModerationLabels.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectModerationLabels.java @@ -5,14 +5,10 @@ // snippet-start:[rekognition.java2.detect_mod_labels.main] // snippet-start:[rekognition.java2.detect_mod_labels.import] -import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.DetectModerationLabelsRequest; -import software.amazon.awssdk.services.rekognition.model.DetectModerationLabelsResponse; -import software.amazon.awssdk.services.rekognition.model.ModerationLabel; +import software.amazon.awssdk.services.rekognition.model.*; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; @@ -31,38 +27,51 @@ public class DetectModerationLabels { public static void main(String[] args) { final String usage = """ + Usage: - Usage: - - Where: - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + bucketName - The name of the S3 bucket where the images are stored. + sourceImage - The name of the image (for example, pic1.png).\s + """; - if (args.length < 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); } - String sourceImage = args[0]; - Region region = Region.US_EAST_1; + String bucketName = args[0]; + String sourceImage = args[1]; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - detectModLabels(rekClient, sourceImage); + detectModLabels(rekClient, bucketName, sourceImage); rekClient.close(); } - public static void detectModLabels(RekognitionClient rekClient, String sourceImage) { + /** + * Detects moderation labels in an image stored in an Amazon S3 bucket. + * + * @param rekClient the Amazon Rekognition client to use for the detection + * @param bucketName the name of the Amazon S3 bucket where the image is stored + * @param sourceImage the name of the image file to be analyzed + * + * @throws RekognitionException if there is an error during the image detection process + */ + public static void detectModLabels(RekognitionClient rekClient, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); - Image souImage = Image.builder() - .bytes(sourceBytes) + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); + + Image targetImage = Image.builder() + .s3Object(s3ObjectTarget) .build(); DetectModerationLabelsRequest moderationLabelsRequest = DetectModerationLabelsRequest.builder() - .image(souImage) + .image(targetImage) .minConfidence(60F) .build(); @@ -76,7 +85,7 @@ public static void detectModLabels(RekognitionClient rekClient, String sourceIma + "\n Parent:" + label.parentName()); } - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { e.printStackTrace(); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectPPE.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectPPE.java index 57d8ecd89d3..83279088213 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectPPE.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectPPE.java @@ -5,6 +5,7 @@ // snippet-start:[rekognition.java2.detect_ppe.main] // snippet-start:[rekognition.java2.detect_ppe.import] + import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; @@ -22,6 +23,7 @@ import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentPerson; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; @@ -30,20 +32,19 @@ /** * Before running this Java V2 code example, set up your development * environment, including your credentials. - * + *

* For more information, see the following documentation topic: - * + *

* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DetectPPE { public static void main(String[] args) { final String usage = """ - - Usage: - - Where: - sourceImage - The name of the image in an Amazon S3 bucket (for example, people.png).\s - bucketName - The name of the Amazon S3 bucket (for example, myBucket).\s + Usage: + + Where: + bucketName - The name of the Amazon S3 bucket (for example, myBucket).\s + sourceImage - The name of the image in an Amazon S3 bucket (for example, people.png).\s """; if (args.length != 2) { @@ -51,48 +52,47 @@ public static void main(String[] args) { System.exit(1); } - String sourceImage = args[0]; - String bucketName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - + String bucketName = args[0]; + String sourceImage = args[1]; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - displayGear(s3, rekClient, sourceImage, bucketName); - s3.close(); + displayGear(rekClient, sourceImage, bucketName); rekClient.close(); System.out.println("This example is done!"); } - public static void displayGear(S3Client s3, - RekognitionClient rekClient, - String sourceImage, - String bucketName) { - - byte[] data = getObjectBytes(s3, bucketName, sourceImage); - InputStream is = new ByteArrayInputStream(data); - + /** + * Displays the protective equipment detected in the specified image using the AWS Rekognition service. + * + * @param rekClient the Rekognition client used to detect protective equipment + * @param sourceImage the name of the source image file + * @param bucketName the name of the S3 bucket containing the source image + */ + public static void displayGear(RekognitionClient rekClient, String sourceImage, String bucketName) { try { + software.amazon.awssdk.services.rekognition.model.Image rekImage = software.amazon.awssdk.services.rekognition.model.Image.builder() + .s3Object(s3Object -> s3Object + .bucket(bucketName) + .name(sourceImage) + ) + .build(); + ProtectiveEquipmentSummarizationAttributes summarizationAttributes = ProtectiveEquipmentSummarizationAttributes .builder() .minConfidence(80F) .requiredEquipmentTypesWithStrings("FACE_COVER", "HAND_COVER", "HEAD_COVER") .build(); - SdkBytes sourceBytes = SdkBytes.fromInputStream(is); - software.amazon.awssdk.services.rekognition.model.Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); - + // Create the request to detect protective equipment from Rekognition DetectProtectiveEquipmentRequest request = DetectProtectiveEquipmentRequest.builder() - .image(souImage) + .image(rekImage) .summarizationAttributes(summarizationAttributes) .build(); + // Call Rekognition to detect protective equipment DetectProtectiveEquipmentResponse result = rekClient.detectProtectiveEquipment(request); List persons = result.persons(); for (ProtectiveEquipmentPerson person : persons) { @@ -100,10 +100,9 @@ public static void displayGear(S3Client s3, List bodyParts = person.bodyParts(); if (bodyParts.isEmpty()) { System.out.println("\tNo body parts detected"); - } else + } else { for (ProtectiveEquipmentBodyPart bodyPart : bodyParts) { - System.out - .println("\t" + bodyPart.name() + ". Confidence: " + bodyPart.confidence().toString()); + System.out.println("\t" + bodyPart.name() + ". Confidence: " + bodyPart.confidence().toString()); List equipmentDetections = bodyPart.equipmentDetections(); if (equipmentDetections.isEmpty()) { @@ -127,7 +126,10 @@ public static void displayGear(S3Client s3, } } } + } } + + // Display summary statistics System.out.println("Person ID Summary\n-----------------"); displaySummary("With required equipment", result.summary().personsWithRequiredEquipment()); @@ -140,27 +142,9 @@ public static void displayGear(S3Client s3, } } - public static byte[] getObjectBytes(S3Client s3, String bucketName, String keyName) { - try { - GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); - - ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); - return objectBytes.asByteArray(); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return null; - } - static void displaySummary(String summaryType, List idList) { System.out.print(summaryType + "\n\tIDs "); - if (idList.size() == 0) { + if (idList.isEmpty()) { System.out.println("None"); } else { int count = 0; diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectText.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectText.java index 6b8048570bc..7ea52c8d6c9 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectText.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectText.java @@ -8,11 +8,8 @@ import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; -import software.amazon.awssdk.services.rekognition.model.DetectTextRequest; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.DetectTextResponse; -import software.amazon.awssdk.services.rekognition.model.TextDetection; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; +import software.amazon.awssdk.services.rekognition.model.*; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; @@ -29,35 +26,46 @@ */ public class DetectText { public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - sourceImage - The path to the image that contains text (for example, C:\\AWS\\pic1.png).\s - """; + final String usage = "\n" + + "Usage: \n" + + "\n" + + "Where:\n" + + " bucketName - The name of the S3 bucket where the image is stored\n" + + " sourceImage - The path to the image that contains text (for example, pic1.png). \n"; - if (args.length != 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); } - String sourceImage = args[0]; + String bucketName = args[0]; + String sourceImage = args[1]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); - detectTextLabels(rekClient, sourceImage); + detectTextLabels(rekClient, bucketName, sourceImage); rekClient.close(); } - public static void detectTextLabels(RekognitionClient rekClient, String sourceImage) { + /** + * Detects text labels in an image stored in an S3 bucket using Amazon Rekognition. + * + * @param rekClient an instance of the Amazon Rekognition client + * @param bucketName the name of the S3 bucket where the image is stored + * @param sourceImage the name of the image file in the S3 bucket + * @throws RekognitionException if an error occurs while calling the Amazon Rekognition API + */ + public static void detectTextLabels(RekognitionClient rekClient, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); + Image souImage = Image.builder() - .bytes(sourceBytes) + .s3Object(s3ObjectTarget) .build(); DetectTextRequest textRequest = DetectTextRequest.builder() @@ -76,7 +84,7 @@ public static void detectTextLabels(RekognitionClient rekClient, String sourceIm System.out.println(); } - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RecognizeCelebrities.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RecognizeCelebrities.java index 877bbdbecba..dfad373edf6 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RecognizeCelebrities.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RecognizeCelebrities.java @@ -12,11 +12,8 @@ import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; -import software.amazon.awssdk.services.rekognition.model.RecognizeCelebritiesRequest; -import software.amazon.awssdk.services.rekognition.model.RecognizeCelebritiesResponse; -import software.amazon.awssdk.services.rekognition.model.RekognitionException; -import software.amazon.awssdk.services.rekognition.model.Image; -import software.amazon.awssdk.services.rekognition.model.Celebrity; + +import software.amazon.awssdk.services.rekognition.model.*; // snippet-end:[rekognition.java2.recognize_celebs.import] /** @@ -30,34 +27,46 @@ public class RecognizeCelebrities { public static void main(String[] args) { final String usage = """ - Usage: + Usage: Where: + bucketName - The name of the S3 bucket where the images are stored. sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s """; - if (args.length != 1) { + if (args.length != 2) { System.out.println(usage); System.exit(1); - } + } - String sourceImage = args[0]; - Region region = Region.US_EAST_1; + String bucketName = args[0];; + String sourceImage = args[1]; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); System.out.println("Locating celebrities in " + sourceImage); - recognizeAllCelebrities(rekClient, sourceImage); + recognizeAllCelebrities(rekClient, bucketName, sourceImage); rekClient.close(); } - public static void recognizeAllCelebrities(RekognitionClient rekClient, String sourceImage) { + /** + * Recognizes all celebrities in an image stored in an Amazon S3 bucket. + * + * @param rekClient the Amazon Rekognition client used to perform the celebrity recognition operation + * @param bucketName the name of the Amazon S3 bucket where the source image is stored + * @param sourceImage the name of the source image file stored in the Amazon S3 bucket + */ + public static void recognizeAllCelebrities(RekognitionClient rekClient, String bucketName, String sourceImage) { try { - InputStream sourceStream = new FileInputStream(sourceImage); - SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); + S3Object s3ObjectTarget = S3Object.builder() + .bucket(bucketName) + .name(sourceImage) + .build(); + Image souImage = Image.builder() - .bytes(sourceBytes) + .s3Object(s3ObjectTarget) .build(); RecognizeCelebritiesRequest request = RecognizeCelebritiesRequest.builder() @@ -79,7 +88,7 @@ public static void recognizeAllCelebrities(RekognitionClient rekClient, String s } System.out.println(result.unrecognizedFaces().size() + " face(s) were unrecognized."); - } catch (RekognitionException | FileNotFoundException e) { + } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RotateImage.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RotateImage.java index 45f6eac4f59..20257488d6d 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RotateImage.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RotateImage.java @@ -45,7 +45,7 @@ public static void main(String[] args) { } String sourceImage = args[0]; - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java index 57166284561..a9d4c692ae6 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java @@ -40,7 +40,7 @@ public static void main(String[] args) { String collectionId = args[0]; String faceId = args[1]; - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java index c74b3bd9c5e..5d4d60cf741 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java @@ -47,7 +47,7 @@ public static void main(String[] args) { String collectionId = args[0]; String sourceImage = args[1]; - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoCelebrityDetection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoCelebrityDetection.java index 090af1a9278..779258271c5 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoCelebrityDetection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoCelebrityDetection.java @@ -106,7 +106,6 @@ public static void startCelebrityDetection(RekognitionClient rekClient, } public static void getCelebrityDetectionResults(RekognitionClient rekClient) { - try { String paginationToken = null; GetCelebrityRecognitionResponse recognitionResponse = null; diff --git a/javav2/example_code/rekognition/src/main/resources/log4j2.xml b/javav2/example_code/rekognition/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/rekognition/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/rekognition/src/test/java/RekognitionTest.java b/javav2/example_code/rekognition/src/test/java/RekognitionTest.java index 37d2874823a..507a5c12ec4 100644 --- a/javav2/example_code/rekognition/src/test/java/RekognitionTest.java +++ b/javav2/example_code/rekognition/src/test/java/RekognitionTest.java @@ -11,15 +11,12 @@ import com.example.rekognition.DetectLabels; import com.example.rekognition.DetectModerationLabels; import com.example.rekognition.DetectPPE; -import com.example.rekognition.DetectText; import com.example.rekognition.ListCollections; import com.example.rekognition.ListFacesInCollection; import com.example.rekognition.RecognizeCelebrities; -import com.example.rekognition.SearchFaceMatchingImageCollection; import com.example.rekognition.VideoDetectFaces; import com.example.rekognition.VideoDetectInappropriate; import com.example.rekognition.VideoDetectText; -import com.example.rekognition.VideoPersonDetection; import com.google.gson.Gson; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; @@ -30,11 +27,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.model.NotificationChannel; -import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; @@ -47,8 +44,8 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class RekognitionTest { + private static final Logger logger = LoggerFactory.getLogger(RekognitionTest.class); private static RekognitionClient rekClient; - private static S3Client s3; private static NotificationChannel channel; private static String facesImage = ""; private static String celebritiesImage = ""; @@ -69,17 +66,10 @@ public class RekognitionTest { @BeforeAll public static void setUp() { - - Region region = Region.US_EAST_1; + Region region = Region.US_WEST_2; rekClient = RekognitionClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - s3 = S3Client.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -101,215 +91,146 @@ public static void setUp() { modVid = values.getModVid(); textVid = values.getTextVid(); celVid = values.getCelVid(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * RekognitionTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * facesImage = prop.getProperty("facesImage"); - * celebritiesImage = prop.getProperty("celebritiesImage"); - * faceImage2 = prop.getProperty("faceImage2"); - * celId = prop.getProperty("celId"); - * moutainImage = prop.getProperty("moutainImage"); - * collectionName = prop.getProperty("collectionName")+ - * java.util.UUID.randomUUID(); - * ppeImage = prop.getProperty("ppeImage"); - * bucketName = prop.getProperty("bucketName"); - * textImage= prop.getProperty("textImage"); - * modImage= prop.getProperty("modImage"); - * faceVid = prop.getProperty("faceVid"); - * topicArn= prop.getProperty("topicArn"); - * roleArn = prop.getProperty("roleArn"); - * modVid= prop.getProperty("modVid"); - * textVid = prop.getProperty("textVid"); - * celVid= prop.getProperty("celVid"); - * - * - * // Required for tests that involve videos - * channel = NotificationChannel.builder() - * .snsTopicArn(topicArn) - * .roleArn(roleArn) - * .build(); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - * - */ } @Test @Tag("IntegrationTest") @Order(1) - public void DetectFaces() { - assertDoesNotThrow(() -> DetectFaces.detectFacesinImage(rekClient, facesImage)); - System.out.println("Test 1 passed"); + public void testDetectFaces() { + assertDoesNotThrow(() -> + DetectFaces.detectFacesinImage(rekClient, bucketName, facesImage) + ); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void RecognizeCelebrities() { - assertDoesNotThrow(() -> RecognizeCelebrities.recognizeAllCelebrities(rekClient, celebritiesImage)); - System.out.println("Test 2 passed"); + public void testRecognizeCelebrities() { + assertDoesNotThrow(() -> RecognizeCelebrities.recognizeAllCelebrities(rekClient, bucketName, celebritiesImage)); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void CompareFaces() { - assertDoesNotThrow(() -> CompareFaces.compareTwoFaces(rekClient, 70F, facesImage, faceImage2)); - System.out.println("Test 3 passed"); + public void testCompareFaces() { + assertDoesNotThrow(() -> CompareFaces.compareTwoFaces(rekClient, bucketName, facesImage, faceImage2)); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void CelebrityInfo() { + public void testCelebrityInfo() { assertDoesNotThrow(() -> CelebrityInfo.getCelebrityInfo(rekClient, celId)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DetectLabels() { - assertDoesNotThrow(() -> DetectLabels.detectImageLabels(rekClient, moutainImage)); - System.out.println("Test 5 passed"); + public void testDetectLabels() { + assertDoesNotThrow(() -> DetectLabels.detectImageLabels(rekClient, bucketName, moutainImage)); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void CreateCollection() { + public void testCreateCollection() { assertDoesNotThrow(() -> CreateCollection.createMyCollection(rekClient, collectionName)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void AddFacesToCollection() { - assertDoesNotThrow(() -> AddFacesToCollection.addToCollection(rekClient, collectionName, facesImage)); - System.out.println("Test 7 passed"); + public void testAddFacesToCollection() { + assertDoesNotThrow(() -> AddFacesToCollection.addToCollection(rekClient, collectionName, bucketName, facesImage)); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void ListFacesCollection() { + public void testListFacesCollection() { assertDoesNotThrow(() -> ListFacesInCollection.listFacesCollection(rekClient, collectionName)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void ListCollections() { + public void testListCollections() { assertDoesNotThrow(() -> ListCollections.listAllCollections(rekClient)); - System.out.println("Test 9 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void DescribeCollection() { + public void testDescribeCollection() { assertDoesNotThrow(() -> DescribeCollection.describeColl(rekClient, collectionName)); - System.out.println("Test 10 passed"); + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void SearchFaceMatchingImageCollection() { - assertDoesNotThrow( - () -> SearchFaceMatchingImageCollection.searchFaceInCollection(rekClient, collectionName, faceImage2)); - System.out.println("Test 11 passed"); + public void testDetectPPE() { + assertDoesNotThrow(() -> DetectPPE.displayGear(rekClient, ppeImage, bucketName)); + logger.info("Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void DetectPPE() { - assertDoesNotThrow(() -> DetectPPE.displayGear(s3, rekClient, ppeImage, bucketName)); - System.out.println("Test 12 passed"); + public void testDetectModImage() { + assertDoesNotThrow(() -> DetectModerationLabels.detectModLabels(rekClient, bucketName, modImage)); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(13) - public void DetectText() { - assertDoesNotThrow(() -> DetectText.detectTextLabels(rekClient, textImage)); - System.out.println("Test 13 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(14) - public void DetectModerationLabels() { - assertDoesNotThrow(() -> DetectModerationLabels.detectModLabels(rekClient, modImage)); - System.out.println("Test 14 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(15) - public void VideoDetectFaces() { + public void testVideoDetectFaces() { assertDoesNotThrow(() -> VideoDetectFaces.startFaceDetection(rekClient, channel, bucketName, celVid)); assertDoesNotThrow(() -> VideoDetectFaces.getFaceResults(rekClient)); - System.out.println("Test 15 passed"); + logger.info("Test 13 passed"); } @Test @Tag("IntegrationTest") - @Order(16) - public void VideoDetectInappropriate() { + @Order(14) + public void testVideoDetectInappropriate() { assertDoesNotThrow( () -> VideoDetectInappropriate.startModerationDetection(rekClient, channel, bucketName, modVid)); assertDoesNotThrow(() -> VideoDetectInappropriate.getModResults(rekClient)); - System.out.println("Test 16 passed"); + logger.info("Test 14 passed"); } @Test @Tag("IntegrationTest") - @Order(17) - public void VideoDetectText() { + @Order(15) + public void testVideoDetectText() { assertDoesNotThrow(() -> VideoDetectText.startTextLabels(rekClient, channel, bucketName, textVid)); assertDoesNotThrow(() -> VideoDetectText.getTextResults(rekClient)); - System.out.println("Test 17 passed"); + logger.info("Test 15 passed"); } - @Test - @Tag("IntegrationTest") - @Order(18) - public void VideoPersonDetection() { - assertDoesNotThrow(() -> VideoPersonDetection.startPersonLabels(rekClient, channel, bucketName, faceVid)); - assertDoesNotThrow(() -> VideoPersonDetection.getPersonDetectionResults(rekClient)); - System.out.println("Test 18 passed"); - } @Test @Tag("IntegrationTest") - @Order(19) - public void DeleteCollection() { + @Order(16) + public void testDeleteCollection() { assertDoesNotThrow(() -> DeleteCollection.deleteMyCollection(rekClient, collectionName)); - System.out.println("Test 19 passed"); + logger.info("Test 16 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/rekognition"; diff --git a/javav2/example_code/route53/pom.xml b/javav2/example_code/route53/pom.xml index 0ded9b73eb8..39e494baf37 100644 --- a/javav2/example_code/route53/pom.xml +++ b/javav2/example_code/route53/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/route53/src/main/resources/log4j2.xml b/javav2/example_code/route53/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/route53/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/route53/src/test/java/Route53Test.java b/javav2/example_code/route53/src/test/java/Route53Test.java index 409392cd038..325cb626a69 100644 --- a/javav2/example_code/route53/src/test/java/Route53Test.java +++ b/javav2/example_code/route53/src/test/java/Route53Test.java @@ -13,6 +13,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.route53.Route53Client; import org.junit.jupiter.api.TestInstance; @@ -37,7 +39,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class Route53Test { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); + private static final Logger logger = LoggerFactory.getLogger(Route53Test.class); private static String domainName = ""; private static String healthCheckId = ""; private static String hostedZoneId = ""; @@ -55,12 +57,10 @@ public class Route53Test { public static void setUp() { route53Client = Route53Client.builder() .region(Region.AWS_GLOBAL) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); route53DomainsClient = Route53DomainsClient.builder() .region(Region.AWS_GLOBAL) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -75,59 +75,30 @@ public static void setUp() { firstNameSc = values.getFirstNameSc(); lastNameSc = values.getLastNameSc(); citySc = values.getCitySc(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * Route53Test.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests - * prop.load(input); - * domainName = prop.getProperty("domainName"); - * domainSuggestionSc = prop.getProperty("domainSuggestionSc"); - * domainTypeSc = prop.getProperty("domainTypeSc"); - * phoneNumerSc = prop.getProperty("phoneNumerSc"); - * emailSc = prop.getProperty("emailSc"); - * firstNameSc = prop.getProperty("firstNameSc"); - * lastNameSc = prop.getProperty("lastNameSc"); - * citySc = prop.getProperty("citySc"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void createHealthCheck() { + public void testCreateHealthCheck() { healthCheckId = CreateHealthCheck.createCheck(route53Client, domainName); assertFalse(healthCheckId.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void createHostedZone() { + public void testCreateHostedZone() { hostedZoneId = CreateHostedZone.createZone(route53Client, domainName); assertFalse(hostedZoneId.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void getHealthCheckStatus() { + public void testGetHealthCheckStatus() { try { TimeUnit.SECONDS.sleep(20); // wait for the new health check assertDoesNotThrow(() -> GetHealthCheckStatus.getHealthStatus(route53Client, healthCheckId)); @@ -135,53 +106,52 @@ public void getHealthCheckStatus() { } catch (InterruptedException e) { e.printStackTrace(); } - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void listHealthChecks() { + public void testListHealthChecks() { assertDoesNotThrow(() -> ListHealthChecks.listAllHealthChecks(route53Client)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void updateHealthCheck() { + public void testUpdateHealthCheck() { assertDoesNotThrow(() -> UpdateHealthCheck.updateSpecificHealthCheck(route53Client, healthCheckId)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void listHostedZones() { + public void testListHostedZones() { assertDoesNotThrow(() -> ListHostedZones.listZones(route53Client)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void deleteHealthCheck() { + public void testDeleteHealthCheck() { assertDoesNotThrow(() -> DeleteHealthCheck.delHealthCheck(route53Client, healthCheckId)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void deleteHostedZone() { + public void testDeleteHostedZone() { assertDoesNotThrow(() -> DeleteHostedZone.delHostedZone(route53Client, hostedZoneId)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/route53"; diff --git a/javav2/example_code/route53recoverycluster/pom.xml b/javav2/example_code/route53recoverycluster/pom.xml index 3719c81e5d0..6363d7acbaf 100644 --- a/javav2/example_code/route53recoverycluster/pom.xml +++ b/javav2/example_code/route53recoverycluster/pom.xml @@ -3,9 +3,9 @@ 4.0.0 UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 Route53RecoveryClusterProject Route53RecoveryClusterProject @@ -17,7 +17,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import @@ -54,10 +54,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.8.1 - 8 - 8 + 21 + 21 diff --git a/javav2/example_code/s3/pom.xml b/javav2/example_code/s3/pom.xml index 7c41c1230bb..e8948ffbb60 100644 --- a/javav2/example_code/s3/pom.xml +++ b/javav2/example_code/s3/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -29,7 +29,7 @@ maven-compiler-plugin 3.11.0 - 17 + 21 @@ -55,7 +55,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/batch/HelloS3Batch.java b/javav2/example_code/s3/src/main/java/com/example/s3/batch/HelloS3Batch.java index 74fe36fbb0d..5d142d0d3e4 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/batch/HelloS3Batch.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/batch/HelloS3Batch.java @@ -86,7 +86,6 @@ private static S3ControlAsyncClient getAsyncClient() { .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return asyncClient; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/batch/S3BatchActions.java b/javav2/example_code/s3/src/main/java/com/example/s3/batch/S3BatchActions.java index 6cff30635e9..b6f1c6a5711 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/batch/S3BatchActions.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/batch/S3BatchActions.java @@ -111,7 +111,6 @@ private static S3ControlAsyncClient getAsyncClient() { .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return asyncClient; @@ -136,7 +135,6 @@ private static S3AsyncClient getS3AsyncClient() { .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } return s3AsyncClient; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java index 472686ae3f1..20a1fb5adb1 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java @@ -35,7 +35,7 @@ public class DownloadFile { private static final Logger logger = LoggerFactory.getLogger(UploadFile.class); - public final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. + public final String bucketName = "s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. public final String key = UUID.randomUUID().toString(); private final String downloadedFileName = "downloaded.pdf"; public String downloadedFileWithPath; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java index a8df923fae1..22c53c2f44a 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java @@ -35,7 +35,7 @@ public class DownloadToDirectory { private static final Logger logger = LoggerFactory.getLogger(DownloadToDirectory.class); - public final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. + public final String bucketName = "s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. public URI destinationPathURI; private final Set downloadedFileNameSet = new HashSet<>(); private final String destinationDirName = "downloadDirectory"; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java index 28d044bb846..5b26a1fc001 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java @@ -27,9 +27,9 @@ public class ObjectCopy { private static final Logger logger = LoggerFactory.getLogger(ObjectCopy.class); - public final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. + public final String bucketName = "s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. public final String key = UUID.randomUUID().toString(); - public final String destinationBucket = "amzn-s3-demo-bucket-" + UUID.randomUUID(); + public final String destinationBucket = "s3-demo-bucket-" + UUID.randomUUID(); public final String destinationKey = UUID.randomUUID().toString(); public ObjectCopy() { diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java index 152fd33032a..0e8f7f3e720 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java @@ -30,7 +30,7 @@ public class UploadADirectory { private static final Logger logger = LoggerFactory.getLogger(UploadADirectory.class); - public final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. + public final String bucketName = "s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. public URI sourceDirectory; public UploadADirectory() { diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java index b2565113eba..5dac590b59b 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java @@ -30,7 +30,7 @@ public class UploadFile { private static final Logger logger = LoggerFactory.getLogger(UploadFile.class); - public final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. + public final String bucketName = "amazon-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. public final String key = UUID.randomUUID().toString(); public URI filePathURI; diff --git a/javav2/example_code/s3/src/main/resources/batch/job-manifest.csv b/javav2/example_code/s3/src/main/resources/batch/job-manifest.csv index a1a421ff9c0..4b90c99aa45 100644 --- a/javav2/example_code/s3/src/main/resources/batch/job-manifest.csv +++ b/javav2/example_code/s3/src/main/resources/batch/job-manifest.csv @@ -1,4 +1,4 @@ -amazon-s3-demo-manifest-bucket,object-key-1.txt -amazon-s3-demo-manifest-bucket,object-key-2.txt -amazon-s3-demo-manifest-bucket,object-key-3.txt -amazon-s3-demo-manifest-bucket,object-key-4.txt +x-49267f42-03d5-49ee-bfea-0cfab75f76a8,object-key-1.txt +x-49267f42-03d5-49ee-bfea-0cfab75f76a8,object-key-2.txt +x-49267f42-03d5-49ee-bfea-0cfab75f76a8,object-key-3.txt +x-49267f42-03d5-49ee-bfea-0cfab75f76a8,object-key-4.txt diff --git a/javav2/example_code/s3/src/test/java/S3ActionsTest.java b/javav2/example_code/s3/src/test/java/S3ActionsTest.java index 92933228214..7ed6f36b8c8 100644 --- a/javav2/example_code/s3/src/test/java/S3ActionsTest.java +++ b/javav2/example_code/s3/src/test/java/S3ActionsTest.java @@ -127,7 +127,6 @@ static void teardown() throws Exception { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/s3"; diff --git a/javav2/example_code/s3/src/test/java/S3BatchTest.java b/javav2/example_code/s3/src/test/java/S3BatchTest.java index b6fed4aeef5..14933b7018c 100644 --- a/javav2/example_code/s3/src/test/java/S3BatchTest.java +++ b/javav2/example_code/s3/src/test/java/S3BatchTest.java @@ -182,7 +182,6 @@ public void testDeleteJobTags() { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/s3"; diff --git a/javav2/example_code/sagemaker/pom.xml b/javav2/example_code/sagemaker/pom.xml index a1d03f985e6..99f20bb5701 100644 --- a/javav2/example_code/sagemaker/pom.xml +++ b/javav2/example_code/sagemaker/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -97,5 +104,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/sagemaker/src/main/resources/log4j2.xml b/javav2/example_code/sagemaker/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/sagemaker/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java b/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java index eae10231e78..a6c97e44c17 100644 --- a/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java +++ b/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java @@ -3,6 +3,8 @@ import com.example.sage.*; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import org.junit.jupiter.api.*; @@ -20,6 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SageMakerTest { + private static final Logger logger = LoggerFactory.getLogger(SageMakerTest.class); private static SageMakerClient sageMakerClient; private static String image = ""; private static String modelDataUrl = ""; @@ -39,7 +42,6 @@ public static void setUp() throws IOException { Region region = Region.US_WEST_2; sageMakerClient = SageMakerClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -58,104 +60,69 @@ public static void setUp() throws IOException { channelName = values.getChannelName(); trainingImage = values.getTrainingImage(); existingModel = values.getModelName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * SageMakerTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests - * prop.load(input); - * image = prop.getProperty("image"); - * modelDataUrl = prop.getProperty("modelDataUrl"); - * executionRoleArn = prop.getProperty("executionRoleArn"); - * modelName = prop.getProperty("modelName")+ java.util.UUID.randomUUID(); - * s3UriData = prop.getProperty("s3UriData"); - * s3Uri = prop.getProperty("s3Uri"); - * roleArn = prop.getProperty("roleArn"); - * trainingJobName = prop.getProperty("trainingJobName")+ - * java.util.UUID.randomUUID(); - * s3OutputPath = prop.getProperty("s3OutputPath"); - * channelName = prop.getProperty("channelName"); - * trainingImage = prop.getProperty("trainingImage"); - * existingModel = prop.getProperty("existingModel"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateModel() { + public void testCreateModel() { assertDoesNotThrow(() -> CreateModel.createSagemakerModel(sageMakerClient, modelDataUrl, image, modelName, executionRoleArn)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateTrainingJob() { + public void testCreateTrainingJob() { assertDoesNotThrow(() -> CreateTrainingJob.trainJob(sageMakerClient, s3UriData, s3Uri, trainingJobName, roleArn, s3OutputPath, channelName, trainingImage)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeTrainingJob() { + public void testDescribeTrainingJob() { assertDoesNotThrow(() -> DescribeTrainingJob.describeTrainJob(sageMakerClient, trainingJobName)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListModels() { + public void testListModels() { assertDoesNotThrow(() -> ListModels.listAllModels(sageMakerClient)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListAlgorithms() { + public void testListAlgorithms() { assertDoesNotThrow(() -> ListAlgorithms.listAlgs(sageMakerClient)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ListTrainingJobs() { + public void testListTrainingJobs() { assertDoesNotThrow(() -> ListTrainingJobs.listJobs(sageMakerClient)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteModel() { + public void testDeleteModel() { assertDoesNotThrow(() -> DeleteModel.deleteSagemakerModel(sageMakerClient, modelName)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/sagemaker"; diff --git a/javav2/example_code/scheduler/pom.xml b/javav2/example_code/scheduler/pom.xml index 2fa41920881..73f8fda97e0 100644 --- a/javav2/example_code/scheduler/pom.xml +++ b/javav2/example_code/scheduler/pom.xml @@ -10,9 +10,9 @@ UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -57,7 +57,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/scheduler/src/test/java/SchedulerTest.java b/javav2/example_code/scheduler/src/test/java/SchedulerTest.java index 05f9ae74d18..979ad8b10a3 100644 --- a/javav2/example_code/scheduler/src/test/java/SchedulerTest.java +++ b/javav2/example_code/scheduler/src/test/java/SchedulerTest.java @@ -10,6 +10,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -20,19 +22,14 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SchedulerTest { - + private static final Logger logger = LoggerFactory.getLogger(SchedulerTest.class); private static final String STACK_NAME = "workflow-stack-name23"; - private static String emailAddress = "foo@example.com"; - private static String scheduleGroupName = "myScheduleGroup"; private static String roleArn = ""; private static String snsTopicArn = ""; - private static String oneTimeScheduleName = "testOneTime1"; - private static String recurringScheduleName = "recurringSchedule1"; - private static final EventbridgeSchedulerActions eventbridgeActions = new EventbridgeSchedulerActions(); @BeforeAll @@ -50,6 +47,7 @@ public void testCreateScheduleGroup() { assertDoesNotThrow(() -> { eventbridgeActions.createScheduleGroup(scheduleGroupName).join(); }); + logger.info("Test 1 passed"); } @Test @@ -71,6 +69,7 @@ public void testOneTimeSchedule() { true, true).join(); }); + logger.info("Test 2 passed"); } @Test @@ -90,6 +89,7 @@ public void testReoccuringSchedule() { true, true).join(); }); + logger.info("Test 3 passed"); } @Test @@ -98,8 +98,8 @@ public void testReoccuringSchedule() { public void testDeleteScheduleGroup() { assertDoesNotThrow(() -> { eventbridgeActions.deleteScheduleGroupAsync(scheduleGroupName).join(); - }); + logger.info("Test 4 passed"); } @Test @@ -108,8 +108,8 @@ public void testDeleteScheduleGroup() { public void testDelOneTimeSchedule() { assertDoesNotThrow(() -> { eventbridgeActions.deleteScheduleAsync(oneTimeScheduleName, scheduleGroupName).join(); - }); + logger.info("Test 5 passed"); } @Test @@ -119,6 +119,7 @@ public void testDelReoccringSchedule() { assertDoesNotThrow(() -> { eventbridgeActions.deleteScheduleAsync(recurringScheduleName, scheduleGroupName).join(); }); + logger.info("Test 6 passed"); } @Test @@ -128,5 +129,6 @@ public void testDelStack() { assertDoesNotThrow(() -> { CloudFormationHelper.destroyCloudFormationStack(STACK_NAME); }); + logger.info("Test 7 passed"); } } \ No newline at end of file diff --git a/javav2/example_code/secrets-manager/pom.xml b/javav2/example_code/secrets-manager/pom.xml index 78016758c56..601e6cacfec 100644 --- a/javav2/example_code/secrets-manager/pom.xml +++ b/javav2/example_code/secrets-manager/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,10 +35,17 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + @@ -65,5 +72,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/secrets-manager/src/main/resources/log4j2.xml b/javav2/example_code/secrets-manager/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/secrets-manager/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/secrets-manager/src/test/java/SecretManagerTest.java b/javav2/example_code/secrets-manager/src/test/java/SecretManagerTest.java index deefdacbb95..9cc82ddb4bf 100644 --- a/javav2/example_code/secrets-manager/src/test/java/SecretManagerTest.java +++ b/javav2/example_code/secrets-manager/src/test/java/SecretManagerTest.java @@ -3,6 +3,8 @@ import com.example.secrets.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import org.junit.jupiter.api.*; @@ -18,7 +20,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SecretManagerTest { - + private static final Logger logger = LoggerFactory.getLogger(SecretManagerTest.class); private static SecretsManagerClient secretsClient; @BeforeAll @@ -26,14 +28,13 @@ public static void setUp() { Region region = Region.US_EAST_1; secretsClient = SecretsManagerClient.builder() .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) .build(); } @Test @Order(1) - public void GetSecretValue() { + public void testGetSecretValue() { assertDoesNotThrow(() -> GetSecretValue.getValue(secretsClient, "mysecret")); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } } diff --git a/javav2/example_code/ses/pom.xml b/javav2/example_code/ses/pom.xml index 109195d8e4e..d6d40878d13 100644 --- a/javav2/example_code/ses/pom.xml +++ b/javav2/example_code/ses/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -39,6 +39,13 @@ pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + @@ -112,5 +119,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/ses/src/main/resources/log4j2.xml b/javav2/example_code/ses/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/ses/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/ses/src/test/java/AWSSesTest.java b/javav2/example_code/ses/src/test/java/AWSSesTest.java index 761b8071984..2b1b511f887 100644 --- a/javav2/example_code/ses/src/test/java/AWSSesTest.java +++ b/javav2/example_code/ses/src/test/java/AWSSesTest.java @@ -10,6 +10,8 @@ import com.example.sesv2.SendEmailTemplate; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import java.io.*; @@ -28,7 +30,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AWSSesTest { - + private static final Logger logger = LoggerFactory.getLogger(AWSSesTest.class); private static SesClient client; private static SesV2Client sesv2Client; private static String sender = ""; @@ -48,12 +50,10 @@ public class AWSSesTest { public static void setUp() throws IOException, URISyntaxException { client = SesClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); sesv2Client = SesV2Client.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -65,84 +65,59 @@ public static void setUp() throws IOException, URISyntaxException { subject = values.getSubject(); fileLocation = values.getFileLocation(); templateName = values.getTemplateName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * - * try (InputStream input = - * AWSSesTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * sender = prop.getProperty("sender"); - * recipient = prop.getProperty("recipient"); - * subject = prop.getProperty("subject"); - * fileLocation= prop.getProperty("fileLocation"); - * templateName = prop.getProperty("templateName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void SendMessage() { + public void testSendMessage() { assertDoesNotThrow(() -> SendMessage.send(client, sender, recipient, subject, bodyText, bodyHTML)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void SendMessageV2() { + public void testSendMessageV2() { assertDoesNotThrow(() -> SendEmail.send(sesv2Client, sender, recipient, subject, bodyHTML)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void SendMessageTemplateV2() { + public void testSendMessageTemplateV2() { assertDoesNotThrow(() -> SendEmailTemplate.send(sesv2Client, sender, recipient, templateName)); - System.out.println("Test 5 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void ListIdentities() { + public void testListIdentities() { assertDoesNotThrow(() -> ListIdentities.listSESIdentities(client)); - System.out.println("Test 6 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListEmailIdentities() { + public void testListEmailIdentities() { assertDoesNotThrow(() -> ListEmailIdentities.listSESIdentities(sesv2Client)); - System.out.println("Test 7 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ListEmailTemplates() { + public void testListEmailTemplates() { assertDoesNotThrow(() -> ListTemplates.listAllTemplates(sesv2Client)); - System.out.println("Test 8 passed"); + logger.info("Test 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/ses"; diff --git a/javav2/example_code/sns/pom.xml b/javav2/example_code/sns/pom.xml index 94460e9d035..d6bd0d3ce5b 100644 --- a/javav2/example_code/sns/pom.xml +++ b/javav2/example_code/sns/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -39,7 +39,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -90,5 +97,22 @@ software.amazon.awssdk sts + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/sns/src/main/resources/log4j2.xml b/javav2/example_code/sns/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/sns/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/sns/src/test/java/AWSSNSTest.java b/javav2/example_code/sns/src/test/java/AWSSNSTest.java index c735d36230d..6a15e5294aa 100644 --- a/javav2/example_code/sns/src/test/java/AWSSNSTest.java +++ b/javav2/example_code/sns/src/test/java/AWSSNSTest.java @@ -3,6 +3,8 @@ import com.example.sns.*; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -21,6 +23,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AWSSNSTest { + private static final Logger logger = LoggerFactory.getLogger(AWSSNSTest.class); private static SnsClient snsClient; private static String topicName = ""; private static String topicArn = ""; @@ -37,7 +40,6 @@ public static void setUp() { snsClient = SnsClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Random random = new Random(); @@ -53,166 +55,141 @@ public static void setUp() { lambdaarn = myValues.getLambdaarn(); phone = myValues.getPhone(); message = myValues.getMessage(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AWSSNSTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * topicName = prop.getProperty("topicName"); - * attributeName= prop.getProperty("attributeName"); - * attributeValue = prop.getProperty("attributeValue"); - * email= prop.getProperty("email"); - * lambdaarn = prop.getProperty("lambdaarn"); - * phone = prop.getProperty("phone"); - * message = prop.getProperty("message"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void createTopicTest() { + public void testCreateTopicTest() { topicArn = CreateTopic.createSNSTopic(snsClient, topicName); assertFalse(topicArn.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void listTopicsTest() { + public void testListTopicsTest() { assertDoesNotThrow(() -> ListTopics.listSNSTopics(snsClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void setTopicAttributesTest() { + public void testSetTopicAttributesTest() { assertDoesNotThrow(() -> SetTopicAttributes.setTopAttr(snsClient, attributeName, topicArn, attributeValue)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void getTopicAttributesTest() { + public void testGetTopicAttributesTest() { assertDoesNotThrow(() -> GetTopicAttributes.getSNSTopicAttributes(snsClient, topicArn)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void subscribeEmailTest() { + public void testSubscribeEmailTest() { assertDoesNotThrow(() -> SubscribeEmail.subEmail(snsClient, topicArn, email)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void subscribeLambdaTest() { + public void testSubscribeLambdaTest() { subArn = SubscribeLambda.subLambda(snsClient, topicArn, lambdaarn); assertFalse(subArn.isEmpty()); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void useMessageFilterPolicyTest() { + public void testUseMessageFilterPolicyTest() { assertDoesNotThrow(() -> UseMessageFilterPolicy.usePolicy(snsClient, subArn)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void addTagsTest() { + public void testAddTagsTest() { assertDoesNotThrow(() -> AddTags.addTopicTags(snsClient, topicArn)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void listTagsTest() { + public void testListTagsTest() { assertDoesNotThrow(() -> ListTags.listTopicTags(snsClient, topicArn)); - System.out.println("Test 9 passed"); + logger.info("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void deleteTagTest() { + public void testDeleteTagTest() { assertDoesNotThrow(() -> DeleteTag.removeTag(snsClient, topicArn, "Environment")); - System.out.println("Test 10 passed"); + logger.info("Test 10 passed"); } @Test @Tag("IntegrationTest") @Order(11) - public void unsubscribeTest() { + public void testUnsubscribeTest() { assertDoesNotThrow(() -> Unsubscribe.unSub(snsClient, subArn)); - System.out.println("Test 11 passed"); + logger.info("Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void publishTopicTest() { + public void testPublishTopicTest() { assertDoesNotThrow(() -> PublishTopic.pubTopic(snsClient, message, topicArn)); - System.out.println("Test 12 passed"); + logger.info("Test 12 passed"); } @Test @Tag("IntegrationTest") @Order(13) - public void subscribeTextSMSTest() { + public void testSubscribeTextSMSTest() { assertDoesNotThrow(() -> SubscribeTextSMS.subTextSNS(snsClient, topicArn, phone)); - System.out.println("Test 13 passed"); + logger.info("Test 13 passed"); } @Test @Tag("IntegrationTest") @Order(14) - public void publishTextSMSTest() { + public void testPublishTextSMSTest() { assertDoesNotThrow(() -> PublishTextSMS.pubTextSMS(snsClient, message, phone)); - System.out.println("Test 14 passed"); + logger.info("Test 14 passed"); } @Test @Tag("IntegrationTest") @Order(15) - public void listSubscriptionsTest() { + public void testListSubscriptionsTest() { assertDoesNotThrow(() -> ListSubscriptions.listSNSSubscriptions(snsClient)); - System.out.println("Test 15 passed"); + logger.info("Test 15 passed"); } @Test @Tag("IntegrationTest") @Order(16) - public void DeleteTopic() { + public void testDeleteTopic() { assertDoesNotThrow(() -> DeleteTopic.deleteSNSTopic(snsClient, topicArn)); - System.out.println("Test 16 passed"); + logger.info("Test 16 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/sns"; diff --git a/javav2/example_code/sqs/pom.xml b/javav2/example_code/sqs/pom.xml index 784b4ad492a..4f4738153e1 100644 --- a/javav2/example_code/sqs/pom.xml +++ b/javav2/example_code/sqs/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import @@ -92,6 +92,10 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + org.slf4j slf4j-api diff --git a/javav2/example_code/sqs/src/main/resources/log4j2.xml b/javav2/example_code/sqs/src/main/resources/log4j2.xml index ba853231574..914470047e7 100644 --- a/javav2/example_code/sqs/src/main/resources/log4j2.xml +++ b/javav2/example_code/sqs/src/main/resources/log4j2.xml @@ -1,18 +1,17 @@ - + + + + - - - - + + + + - - - - \ No newline at end of file diff --git a/javav2/example_code/sqs/src/test/java/SQSIntegrationTest.java b/javav2/example_code/sqs/src/test/java/SQSIntegrationTest.java index 3930231f6d1..200d8cb9b39 100644 --- a/javav2/example_code/sqs/src/test/java/SQSIntegrationTest.java +++ b/javav2/example_code/sqs/src/test/java/SQSIntegrationTest.java @@ -8,6 +8,9 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -26,9 +29,8 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SQSIntegrationTest { - + private static final Logger logger = LoggerFactory.getLogger(SQSIntegrationTest.class); private static SqsClient sqsClient; - private static String queueName = ""; private static String queueUrl = ""; private static String message = ""; @@ -41,7 +43,6 @@ public static void setUp() throws IOException { int randomNum = random.nextInt((10000 - 1) + 1) + 1; sqsClient = SqsClient.builder() .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -51,101 +52,77 @@ public static void setUp() throws IOException { queueName = queueMessage.getQueueName() + randomNum; dlqueueName = queueMessage.getDLQueueName(); message = queueMessage.getMessage(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * SQSIntegrationTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * queueName = prop.getProperty("QueueName"); - * message = prop.getProperty("Message"); - * dlqueueName=prop.getProperty("DLQueueName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateSQSQueue() { + public void testCreateSQSQueue() { queueUrl = SQSExample.createQueue(sqsClient, queueName); assertFalse(queueUrl.isEmpty()); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void SendMessage() { + public void testSendMessage() { assertDoesNotThrow(() -> SendMessages.sendMessage(sqsClient, queueName, message)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetMessage() { + public void testGetMessage() { messages = SQSExample.receiveMessages(sqsClient, queueUrl); assertNotNull(messages); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void GetQueueAttributes() { + public void testGetQueueAttributes() { assertDoesNotThrow(() -> GetQueueAttributes.getAttributes(sqsClient, queueName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DeleteMessages() { + public void testDeleteMessages() { assertDoesNotThrow(() -> SQSExample.deleteMessages(sqsClient, queueUrl, messages)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void LongPolling() { + public void testLongPolling() { assertDoesNotThrow(() -> LongPolling.setLongPoll(sqsClient)); - System.out.println("Test 6 passed"); + logger.info("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeadLetterQueues() { + public void testDeadLetterQueues() { assertDoesNotThrow(() -> DeadLetterQueues.setDeadLetterQueue(sqsClient)); - System.out.println("Test 7 passed"); + logger.info("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void DeleteQueue() { + public void testDeleteQueue() { assertDoesNotThrow(() -> DeleteQueue.deleteSQSQueue(sqsClient, queueName)); - System.out.println("Test 8 passed"); + logger.info("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/sqs"; diff --git a/javav2/example_code/ssm/pom.xml b/javav2/example_code/ssm/pom.xml index 42314e1eceb..92529ae80a2 100644 --- a/javav2/example_code/ssm/pom.xml +++ b/javav2/example_code/ssm/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -39,6 +39,13 @@ pom import + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMActions.java b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMActions.java index 8a4056b880b..b585c2cb46b 100644 --- a/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMActions.java +++ b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMActions.java @@ -65,26 +65,25 @@ public class SSMActions { private static SsmAsyncClient getAsyncClient() { if (ssmAsyncClient == null) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() - .maxConcurrency(100) - .connectionTimeout(Duration.ofSeconds(60)) - .readTimeout(Duration.ofSeconds(60)) - .writeTimeout(Duration.ofSeconds(60)) - .build(); + .maxConcurrency(100) + .connectionTimeout(Duration.ofSeconds(60)) + .readTimeout(Duration.ofSeconds(60)) + .writeTimeout(Duration.ofSeconds(60)) + .build(); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() - .apiCallTimeout(Duration.ofMinutes(2)) - .apiCallAttemptTimeout(Duration.ofSeconds(90)) - .retryPolicy(RetryPolicy.builder() - .numRetries(3) - .build()) - .build(); + .apiCallTimeout(Duration.ofMinutes(2)) + .apiCallAttemptTimeout(Duration.ofSeconds(90)) + .retryPolicy(RetryPolicy.builder() + .numRetries(3) + .build()) + .build(); ssmAsyncClient = SsmAsyncClient.builder() - .region(Region.US_EAST_1) - .httpClient(httpClient) - .overrideConfiguration(overrideConfig) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .httpClient(httpClient) + .overrideConfiguration(overrideConfig) + .build(); } return ssmAsyncClient; } @@ -100,17 +99,17 @@ private static SsmAsyncClient getAsyncClient() { */ public void deleteDoc(String documentName) { DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder() - .name(documentName) - .build(); + .name(documentName) + .build(); CompletableFuture future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteDocument(documentRequest) - .thenAccept(response -> { - System.out.println("The SSM document was successfully deleted."); - }) - .exceptionally(ex -> { - throw new CompletionException(ex); - }).join(); + .thenAccept(response -> { + System.out.println("The SSM document was successfully deleted."); + }) + .exceptionally(ex -> { + throw new CompletionException(ex); + }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { @@ -139,17 +138,17 @@ public void deleteDoc(String documentName) { */ public void deleteMaintenanceWindow(String winId) { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() - .windowId(winId) - .build(); + .windowId(winId) + .build(); CompletableFuture future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteMaintenanceWindow(windowRequest) - .thenAccept(response -> { - System.out.println("The maintenance window was successfully deleted."); - }) - .exceptionally(ex -> { - throw new CompletionException(ex); - }).join(); + .thenAccept(response -> { + System.out.println("The maintenance window was successfully deleted."); + }) + .exceptionally(ex -> { + throw new CompletionException(ex); + }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { @@ -178,18 +177,18 @@ public void deleteMaintenanceWindow(String winId) { */ public void resolveOpsItem(String opsID) { UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder() - .opsItemId(opsID) - .status(OpsItemStatus.RESOLVED) - .build(); + .opsItemId(opsID) + .status(OpsItemStatus.RESOLVED) + .build(); CompletableFuture future = CompletableFuture.runAsync(() -> { getAsyncClient().updateOpsItem(opsItemRequest) - .thenAccept(response -> { - System.out.println("OpsItem resolved successfully."); - }) - .exceptionally(ex -> { - throw new CompletionException(ex); - }).join(); + .thenAccept(response -> { + System.out.println("OpsItem resolved successfully."); + }) + .exceptionally(ex -> { + throw new CompletionException(ex); + }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { @@ -219,27 +218,27 @@ public void resolveOpsItem(String opsID) { */ public void describeOpsItems(String key) { OpsItemFilter filter = OpsItemFilter.builder() - .key(OpsItemFilterKey.OPS_ITEM_ID) - .values(key) - .operator(OpsItemFilterOperator.EQUAL) - .build(); + .key(OpsItemFilterKey.OPS_ITEM_ID) + .values(key) + .operator(OpsItemFilterOperator.EQUAL) + .build(); DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() - .maxResults(10) - .opsItemFilters(filter) - .build(); + .maxResults(10) + .opsItemFilters(filter) + .build(); CompletableFuture future = CompletableFuture.runAsync(() -> { getAsyncClient().describeOpsItems(itemsRequest) - .thenAccept(itemsResponse -> { - List items = itemsResponse.opsItemSummaries(); - for (OpsItemSummary item : items) { - System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString()); - } - }) - .exceptionally(ex -> { - throw new CompletionException(ex); - }).join(); + .thenAccept(itemsResponse -> { + List items = itemsResponse.opsItemSummaries(); + for (OpsItemSummary item : items) { + System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString()); + } + }) + .exceptionally(ex -> { + throw new CompletionException(ex); + }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { @@ -276,12 +275,12 @@ public void updateOpsItem(String opsItemId, String title, String description) { CompletableFuture future = getOpsItem(opsItemId).thenCompose(opsItem -> { UpdateOpsItemRequest request = UpdateOpsItemRequest.builder() - .opsItemId(opsItemId) - .title(title) - .operationalData(operationalData) - .status(opsItem.statusAsString()) - .description(description) - .build(); + .opsItemId(opsItemId) + .title(title) + .operationalData(operationalData) + .status(opsItem.statusAsString()) + .description(description) + .build(); return getAsyncClient().updateOpsItem(request).thenAccept(response -> { System.out.println(opsItemId + " updated successfully."); @@ -327,12 +326,12 @@ private static CompletableFuture getOpsItem(String opsItemId) { */ public String createSSMOpsItem(String title, String source, String category, String severity) { CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() - .description("Created by the SSM Java API") - .title(title) - .source(source) - .category(category) - .severity(severity) - .build(); + .description("Created by the SSM Java API") + .title(title) + .source(source) + .category(category) + .severity(severity) + .build(); CompletableFuture future = getAsyncClient().createOpsItem(opsItemRequest); @@ -361,8 +360,8 @@ public String createSSMOpsItem(String title, String source, String category, Str */ public void displayCommands(String commandId) { ListCommandInvocationsRequest commandInvocationsRequest = ListCommandInvocationsRequest.builder() - .commandId(commandId) - .build(); + .commandId(commandId) + .build(); CompletableFuture future = getAsyncClient().listCommandInvocations(commandInvocationsRequest); future.thenAccept(response -> { @@ -398,8 +397,8 @@ public String sendSSMCommand(String documentName, String instanceId) throws Inte CompletableFuture documentActiveFuture = CompletableFuture.runAsync(() -> { boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() - .name(documentName) - .build(); + .name(documentName) + .build(); while (!isDocumentActive) { CompletableFuture response = getAsyncClient().describeDocument(request); @@ -422,9 +421,9 @@ public String sendSSMCommand(String documentName, String instanceId) throws Inte // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() - .documentName(documentName) - .instanceIds(instanceId) - .build(); + .documentName(documentName) + .instanceIds(instanceId) + .build(); // Send the command. CompletableFuture commandFuture = getAsyncClient().sendCommand(commandRequest); @@ -437,9 +436,9 @@ public String sendSSMCommand(String documentName, String instanceId) throws Inte // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() - .commandId(commandId[0]) - .instanceId(instanceId) - .build(); + .commandId(commandId[0]) + .instanceId(instanceId) + .build(); try { System.out.println("Wait 5 secs"); @@ -508,10 +507,10 @@ public void createSSMDoc(String docName) throws SsmException { """; CreateDocumentRequest request = CreateDocumentRequest.builder() - .content(jsonData) - .name(docName) - .documentType(DocumentType.COMMAND) - .build(); + .content(jsonData) + .name(docName) + .documentType(DocumentType.COMMAND) + .build(); CompletableFuture future = getAsyncClient().createDocument(request); future.thenAccept(response -> { @@ -542,13 +541,13 @@ public void createSSMDoc(String docName) throws SsmException { */ public void updateSSMMaintenanceWindow(String id, String name) throws SsmException { UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder() - .windowId(id) - .allowUnassociatedTargets(true) - .duration(24) - .enabled(true) - .name(name) - .schedule("cron(0 0 ? * MON *)") - .build(); + .windowId(id) + .allowUnassociatedTargets(true) + .duration(24) + .enabled(true) + .name(name) + .schedule("cron(0 0 ? * MON *)") + .build(); CompletableFuture future = getAsyncClient().updateMaintenanceWindow(updateRequest); future.whenComplete((response, ex) -> { @@ -579,13 +578,13 @@ public void updateSSMMaintenanceWindow(String id, String name) throws SsmExcepti */ public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException { CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder() - .name(winName) - .description("This is my maintenance window") - .allowUnassociatedTargets(true) - .duration(2) - .cutoff(1) - .schedule("cron(0 10 ? * MON-FRI *)") - .build(); + .name(winName) + .description("This is my maintenance window") + .allowUnassociatedTargets(true) + .duration(2) + .cutoff(1) + .schedule("cron(0 10 ? * MON-FRI *)") + .build(); CompletableFuture future = getAsyncClient().createMaintenanceWindow(request); final String[] windowId = {null}; @@ -608,13 +607,13 @@ public String createMaintenanceWindow(String winName) throws SsmException, Docum if (windowId[0] == null) { MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() - .key("name") - .values(winName) - .build(); + .key("name") + .values(winName) + .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() - .filters(filter) - .build(); + .filters(filter) + .build(); CompletableFuture describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest); describeFuture.whenComplete((describeResponse, describeEx) -> { diff --git a/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java index 9476ba0a45f..d5553600a59 100644 --- a/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java +++ b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java @@ -34,10 +34,10 @@ public static void main(String[] args) { String documentName; String windowName; String instanceId = args[0]; - String title = args[1]; - String source = args[2]; - String category = args[3]; - String severity = args[4]; + String title = "Disk Space Alert" ; + String source = "EC2" ; + String category = "Availability" ; + String severity = "2" ; System.out.println(DASHES); System.out.println(""" diff --git a/javav2/example_code/ssm/src/main/resources/log4j2.xml b/javav2/example_code/ssm/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/ssm/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/ssm/src/test/java/AWSSSMTest.java b/javav2/example_code/ssm/src/test/java/AWSSSMTest.java index 085fcbc428d..fe479eefcdb 100644 --- a/javav2/example_code/ssm/src/test/java/AWSSSMTest.java +++ b/javav2/example_code/ssm/src/test/java/AWSSSMTest.java @@ -6,6 +6,8 @@ import com.example.ssm.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import static org.junit.jupiter.api.Assertions.*; @@ -24,6 +26,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AWSSSMTest { + private static final Logger logger = LoggerFactory.getLogger(AWSSSMTest.class); private static SsmClient ssmClient; private static String paraName = ""; private static String title = ""; @@ -41,7 +44,6 @@ public static void setUp() { Region region = Region.US_EAST_1; ssmClient = SsmClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -56,53 +58,28 @@ public static void setUp() { account = values.getAccount(); instance = values.getInstanceId(); severity = values.getSeverity(); - - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AWSSSMTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * paraName = prop.getProperty("paraName"); - * title = prop.getProperty("title"); - * source = prop.getProperty("source"); - * category = prop.getProperty("category"); - * severity = prop.getProperty("severity"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void HelloSSM() { + public void testHelloSSM() { assertDoesNotThrow(() -> HelloSSM.listDocuments(ssmClient, account)); - System.out.println("Integration Test 1 passed"); + logger.info("Integration Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void GetParameter() { + public void testGetParameter() { assertDoesNotThrow(() -> GetParameter.getParaValue(ssmClient, paraName)); - System.out.println("Integration Test 2 passed"); + logger.info("Integration Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void InvokeScenario() { + public void testInvokeScenario() { SSMActions actions = new SSMActions(); String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String maintenanceWindowName = "windowmain_" + currentDateTime; @@ -127,13 +104,12 @@ public void InvokeScenario() { assertDoesNotThrow(() -> actions.deleteDoc(documentName)); assertDoesNotThrow(() -> actions.deleteMaintenanceWindow(maintenanceWindowId)); - System.out.println("Test passed"); + logger.info("Test 3 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/ssm"; diff --git a/javav2/example_code/stepfunctions/pom.xml b/javav2/example_code/stepfunctions/pom.xml index f791a6baae8..39c728e4f4b 100644 --- a/javav2/example_code/stepfunctions/pom.xml +++ b/javav2/example_code/stepfunctions/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -87,5 +94,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/stepfunctions/src/main/reources/log4j2.xml b/javav2/example_code/stepfunctions/src/main/reources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/stepfunctions/src/main/reources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/stepfunctions/src/test/java/StepFunctionsTest.java b/javav2/example_code/stepfunctions/src/test/java/StepFunctionsTest.java index 39d41e6e424..ed6a101645e 100644 --- a/javav2/example_code/stepfunctions/src/test/java/StepFunctionsTest.java +++ b/javav2/example_code/stepfunctions/src/test/java/StepFunctionsTest.java @@ -2,20 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import com.example.stepfunctions.*; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.Gson; import org.junit.jupiter.api.*; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.sfn.SfnClient; import java.io.*; -import java.util.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** @@ -25,6 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class StepFunctionsTest { + private static final Logger logger = LoggerFactory.getLogger(StepFunctionsTest.class); private static SfnClient sfnClient; private static String roleNameSC = ""; private static String activityNameSC = ""; @@ -35,7 +32,6 @@ public static void setUp() throws IOException { Region region = Region.US_EAST_1; sfnClient = SfnClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -43,43 +39,16 @@ public static void setUp() throws IOException { String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); roleNameSC = values.getRoleNameSC() + java.util.UUID.randomUUID(); - ; activityNameSC = values.getActivityNameSC() + java.util.UUID.randomUUID(); - ; stateMachineNameSC = values.getStateMachineNameSC() + java.util.UUID.randomUUID(); - ; - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * StepFunctionsTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * roleNameSC = prop.getProperty("roleNameSC")+ java.util.UUID.randomUUID();; - * activityNameSC = prop.getProperty("activityNameSC")+ - * java.util.UUID.randomUUID();; - * stateMachineNameSC = prop.getProperty("stateMachineNameSC")+ - * java.util.UUID.randomUUID();; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void ListActivities() { + public void testListActivities() { assertDoesNotThrow(() -> ListActivities.listAllActivites(sfnClient)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @@ -87,13 +56,12 @@ public void ListActivities() { @Order(2) public void TestHello() { assertDoesNotThrow(() -> ListStateMachines.listMachines(sfnClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/stepfunctions"; diff --git a/javav2/example_code/sts/pom.xml b/javav2/example_code/sts/pom.xml index fdb2113c117..70335ed0e02 100644 --- a/javav2/example_code/sts/pom.xml +++ b/javav2/example_code/sts/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/sts/src/main/resources/log4j2.xml b/javav2/example_code/sts/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/sts/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/sts/src/test/java/STSServiceTest.java b/javav2/example_code/sts/src/test/java/STSServiceTest.java index 4829e3e1153..fe04f732d3c 100644 --- a/javav2/example_code/sts/src/test/java/STSServiceTest.java +++ b/javav2/example_code/sts/src/test/java/STSServiceTest.java @@ -6,6 +6,8 @@ import com.example.sts.GetCallerIdentity; import com.example.sts.GetSessionToken; import com.google.gson.Gson; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -22,6 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class STSServiceTest { + private static final Logger logger = LoggerFactory.getLogger(STSServiceTest.class); private static StsClient stsClient; private static String roleArn = ""; private static String accessKeyId = ""; @@ -32,7 +35,6 @@ public static void setUp() { Region region = Region.US_EAST_1; stsClient = StsClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -42,67 +44,43 @@ public static void setUp() { roleArn = values.getRoleArn(); accessKeyId = values.getAccessKeyId(); roleSessionName = values.getRoleSessionName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * STSServiceTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * roleArn = prop.getProperty("roleArn"); - * accessKeyId = prop.getProperty("accessKeyId"); - * roleSessionName = prop.getProperty("roleSessionName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void AssumeRole() { + public void testAssumeRole() { assertDoesNotThrow(() -> AssumeRole.assumeGivenRole(stsClient, roleArn, roleSessionName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void GetSessionToken() { + public void testGetSessionToken() { assertDoesNotThrow(() -> GetSessionToken.getToken(stsClient)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetCallerIdentity() { + public void testGetCallerIdentity() { assertDoesNotThrow(() -> GetCallerIdentity.getCallerId(stsClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void GetAccessKeyInfo() { + public void testGetAccessKeyInfo() { assertDoesNotThrow(() -> GetAccessKeyInfo.getKeyInfo(stsClient, accessKeyId)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/sts"; diff --git a/javav2/example_code/support/pom.xml b/javav2/example_code/support/pom.xml index f1490cb7769..3dc1e4bb66b 100644 --- a/javav2/example_code/support/pom.xml +++ b/javav2/example_code/support/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -58,11 +65,6 @@ jackson-databind 2.14.2 - - org.apache.logging.log4j - log4j-api - 2.20.0 - software.amazon.awssdk sso @@ -71,5 +73,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/support/src/main/java/com/example/support/SupportScenario.java b/javav2/example_code/support/src/main/java/com/example/support/SupportScenario.java index 3ed6c220503..eed81b8d8e9 100644 --- a/javav2/example_code/support/src/main/java/com/example/support/SupportScenario.java +++ b/javav2/example_code/support/src/main/java/com/example/support/SupportScenario.java @@ -81,12 +81,12 @@ public static void main(String[] args) { fileAttachment - The file can be a simple saved .txt file to use as an email attachment.\s """; - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } + // if (args.length != 1) { + // System.out.println(usage); + // System.exit(1); + // } - String fileAttachment = args[0]; + String fileAttachment = "C:\\AWS\\test.txt" ; //args[0]; Region region = Region.US_WEST_2; SupportClient supportClient = SupportClient.builder() .region(region) diff --git a/javav2/example_code/support/src/main/resources/config.properties b/javav2/example_code/support/src/main/resources/config.properties index 7b5b6426a23..0f4ad654e9f 100644 --- a/javav2/example_code/support/src/main/resources/config.properties +++ b/javav2/example_code/support/src/main/resources/config.properties @@ -1 +1 @@ -fileAttachment = +fileAttachment = Enter value diff --git a/javav2/example_code/support/src/main/resources/log4j2.xml b/javav2/example_code/support/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..a79a198a5f1 --- /dev/null +++ b/javav2/example_code/support/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/support/src/test/java/SupportTest.java b/javav2/example_code/support/src/test/java/SupportTest.java index 1284c4836bc..eb215a31ce4 100644 --- a/javav2/example_code/support/src/test/java/SupportTest.java +++ b/javav2/example_code/support/src/test/java/SupportTest.java @@ -1,10 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import com.example.support.HelloSupport; import org.junit.jupiter.api.*; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import java.io.*; @@ -12,71 +13,27 @@ import com.example.support.SupportScenario; import software.amazon.awssdk.services.support.SupportClient; +import static org.junit.jupiter.api.Assertions.*; + @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SupportTest { - + private static final Logger logger = LoggerFactory.getLogger(SupportTest.class); private static SupportClient supportClient; - private static String fileAttachment = ""; @BeforeAll public static void setUp() throws IOException { - Region region = Region.US_WEST_2; supportClient = SupportClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); - - try (InputStream input = SupportTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - prop.load(input); - - // Populate the data members required for all tests. - fileAttachment = prop.getProperty("fileAttachment"); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - } catch (IOException ex) { - ex.printStackTrace(); - } } @Test @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(supportClient); - System.out.printf("\n Test 1 passed"); - } - - @Test - @Order(2) - public void supportScenario() { - List sevCatList = SupportScenario.displayServices(supportClient); - String sevLevel = SupportScenario.displaySevLevels(supportClient); - assertFalse(sevLevel.isEmpty()); - - String caseId = SupportScenario.createSupportCase(supportClient, sevCatList, sevLevel); - if (caseId.compareTo("") == 0) { - System.exit(1); - } - - SupportScenario.getOpenCase(supportClient); - String attachmentSetId = SupportScenario.addAttachment(supportClient, fileAttachment); - assertFalse(attachmentSetId.isEmpty()); - - SupportScenario.addAttachSupportCase(supportClient, caseId, attachmentSetId); - - String attachId = SupportScenario.listCommunications(supportClient, caseId); - assertFalse(attachId.isEmpty()); - SupportScenario.describeAttachment(supportClient, attachId); - - SupportScenario.resolveSupportCase(supportClient, caseId); - SupportScenario.getResolvedCase(supportClient); - System.out.println("\n Test 2 passed"); + public void testHelp() { + assertDoesNotThrow(() -> HelloSupport.displayServices(supportClient)); + logger.info("\n Test 1 passed"); } } diff --git a/javav2/example_code/swf/pom.xml b/javav2/example_code/swf/pom.xml index 17c23b59fef..f221ea093d8 100644 --- a/javav2/example_code/swf/pom.xml +++ b/javav2/example_code/swf/pom.xml @@ -7,9 +7,9 @@ 1.0 UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -34,7 +34,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -68,5 +75,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/swf/src/main/resources/log4j2.xml b/javav2/example_code/swf/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/swf/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/swf/src/test/java/AmazonSimpleWorkflowTest.java b/javav2/example_code/swf/src/test/java/AmazonSimpleWorkflowTest.java index a4ce81fa837..679f3d6e953 100644 --- a/javav2/example_code/swf/src/test/java/AmazonSimpleWorkflowTest.java +++ b/javav2/example_code/swf/src/test/java/AmazonSimpleWorkflowTest.java @@ -7,6 +7,8 @@ import com.example.helloswf.WorkflowWorker; import com.google.gson.Gson; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -23,6 +25,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonSimpleWorkflowTest { + private static final Logger logger = LoggerFactory.getLogger(AmazonSimpleWorkflowTest.class); private static SwfClient swf; private static String workflowInput = ""; private static String domain = ""; @@ -37,7 +40,6 @@ public static void setUp() { Region region = software.amazon.awssdk.regions.Region.US_EAST_1; swf = SwfClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -50,89 +52,61 @@ public static void setUp() { workflowVersion = values.getWorkflowVersion(); activity = values.getActivity(); activityVersion = values.getActivityVersion(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonSimpleWorkflowTest.class.getClassLoader().getResourceAsStream( - * "config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * // Populate the data members required for all tests - * prop.load(input); - * domain = prop.getProperty("domain")+ java.util.UUID.randomUUID(); - * taskList = prop.getProperty("taskList"); - * workflow = prop.getProperty("workflow"); - * workflowVersion = prop.getProperty("workflowVersion"); - * activity = prop.getProperty("activity"); - * activityVersion = prop.getProperty("activityVersion"); - * - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - * - */ } @Test @Tag("IntegrationTest") @Order(1) - public void registerDomain() { + public void testRegisterDomain() { assertDoesNotThrow(() -> SWFWorkflowDemo.registerDomain(swf, domain)); - System.out.println("Test 1 passed"); + logger.info("\n Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void RegisterWorkflowType() { + public void testRegisterWorkflowType() { assertDoesNotThrow( () -> SWFWorkflowDemo.registerWorkflowType(swf, domain, workflow, workflowVersion, taskList)); - System.out.println("Test 2 passed"); + logger.info("\nTest 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void registerActivityType() { + public void testRegisterActivityType() { assertDoesNotThrow( () -> SWFWorkflowDemo.registerActivityType(swf, domain, activity, activityVersion, taskList)); - System.out.println("Test 3 passed"); + logger.info("\nTest 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void WorkflowStarter() { + public void testWorkflowStarter() { assertDoesNotThrow(() -> WorkflowStarter.startWorkflow(swf, workflowInput, domain, workflow, workflowVersion)); - System.out.println("Test 4 passed"); + logger.info("\nTest 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void WorkflowWorker() { + public void testWorkflowWorker() { assertDoesNotThrow(() -> WorkflowWorker.pollADecision(swf, domain, taskList, activity, activityVersion)); - System.out.println("Test 5 passed"); + logger.info("\nTest 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ActivityWorker() { + public void testActivityWorker() { assertDoesNotThrow(() -> ActivityWorker.getPollData(swf, domain, taskList)); - System.out.println("Test 6 passed"); + logger.info("\nTest 6 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/swf"; diff --git a/javav2/example_code/textract/pom.xml b/javav2/example_code/textract/pom.xml index eecc6813ee6..5c523881e63 100644 --- a/javav2/example_code/textract/pom.xml +++ b/javav2/example_code/textract/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -69,5 +76,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/textract/src/main/resources/log4j2.xml b/javav2/example_code/textract/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/textract/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/textract/src/test/java/TextractTest.java b/javav2/example_code/textract/src/test/java/TextractTest.java index a3d72e5e9d6..18a036419ee 100644 --- a/javav2/example_code/textract/src/test/java/TextractTest.java +++ b/javav2/example_code/textract/src/test/java/TextractTest.java @@ -7,7 +7,8 @@ import com.example.textract.StartDocumentAnalysis; import com.google.gson.Gson; import org.junit.jupiter.api.*; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; @@ -23,6 +24,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class TextractTest { + private static final Logger logger = LoggerFactory.getLogger(TextractTest.class); private static TextractClient textractClient; private static Region region; private static String sourceDoc = ""; @@ -34,7 +36,6 @@ public static void setUp() throws IOException { region = Region.US_WEST_2; textractClient = TextractClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -44,71 +45,29 @@ public static void setUp() throws IOException { sourceDoc = values.getSourceDoc(); bucketName = values.getBucketName(); docName = values.getDocName(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * TextractTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * sourceDoc = prop.getProperty("sourceDoc"); - * bucketName = prop.getProperty("bucketName"); - * docName = prop.getProperty("docName"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - * - */ } @Test @Tag("IntegrationTest") @Order(1) - public void AnalyzeDocument() { - assertDoesNotThrow(() -> AnalyzeDocument.analyzeDoc(textractClient, sourceDoc)); - System.out.println("Test 1 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void DetectDocumentText() { - assertDoesNotThrow(() -> DetectDocumentText.detectDocText(textractClient, sourceDoc)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void DetectDocumentTextS3() { + public void testDetectDocumentTextS3() { assertDoesNotThrow(() -> DetectDocumentTextS3.detectDocTextS3(textractClient, bucketName, docName)); - System.out.println("Test 3 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") - @Order(4) - public void StartDocumentAnalysis() { + @Order(2) + public void testStartDocumentAnalysis() { assertDoesNotThrow(() -> StartDocumentAnalysis.startDocAnalysisS3(textractClient, bucketName, docName)); - System.out.println("Test 4 passed"); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/textract"; - GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); diff --git a/javav2/example_code/timestream/pom.xml b/javav2/example_code/timestream/pom.xml index 47190eb9798..39b394570b9 100644 --- a/javav2/example_code/timestream/pom.xml +++ b/javav2/example_code/timestream/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/timestream/src/main/resources/log4j2.xml b/javav2/example_code/timestream/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/timestream/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/timestream/src/test/java/TimestreamTest.java b/javav2/example_code/timestream/src/test/java/TimestreamTest.java index 2de74f76ae2..34edce852b5 100644 --- a/javav2/example_code/timestream/src/test/java/TimestreamTest.java +++ b/javav2/example_code/timestream/src/test/java/TimestreamTest.java @@ -4,6 +4,8 @@ import com.google.gson.Gson; import com.timestream.write.*; import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -21,28 +23,29 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class TimestreamTest { - + private static final Logger logger = LoggerFactory.getLogger(TimestreamTest.class); private static TimestreamWriteClient timestreamWriteClient; private static TimestreamQueryClient queryClient; private static String dbName = ""; private static String newTable = ""; // TODO Change database name in this string. - private static String queryString = "SELECT\n" + - " truck_id,\n" + - " fleet,\n" + - " fuel_capacity,\n" + - " model,\n" + - " load_capacity,\n" + - " make,\n" + - " measure_name\n" + - "FROM \"ScottTimeDB\".IoTMulti"; + private static String queryString = """ + SELECT + truck_id, + fleet, + fuel_capacity, + model, + load_capacity, + make, + measure_name + FROM "ScottTimeDB".IoTMulti + """; @BeforeAll public static void setUp() throws IOException { timestreamWriteClient = TimestreamWriteClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); queryClient = TimestreamQueryClient.builder() @@ -56,115 +59,91 @@ public static void setUp() throws IOException { SecretValues values = gson.fromJson(json, SecretValues.class); dbName = values.getDbName() + java.util.UUID.randomUUID(); newTable = values.getNewTable() + java.util.UUID.randomUUID(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * TimestreamTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * dbName = prop.getProperty("dbName")+ java.util.UUID.randomUUID();; - * newTable = prop.getProperty("newTable")+ java.util.UUID.randomUUID();; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - * - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateDatabase() { + public void testCreateDatabase() { assertDoesNotThrow(() -> CreateDatabase.createNewDatabase(timestreamWriteClient, dbName)); - System.out.println("Test 1 passed"); + logger.info("\nTest 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateTable() { + public void testCreateTable() { assertDoesNotThrow(() -> CreateTable.createNewTable(timestreamWriteClient, dbName, newTable)); - System.out.println("Test 2 passed"); + logger.info("\nTest 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void DescribeDatabase() { + public void testDescribeDatabase() { assertDoesNotThrow(() -> DescribeDatabase.DescribeSingleDatabases(timestreamWriteClient, dbName)); - System.out.println("Test 3 passed"); + logger.info("\nTest 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DescribeTable() { + public void testDescribeTable() { assertDoesNotThrow(() -> DescribeTable.describeSingleTable(timestreamWriteClient, dbName, newTable)); - System.out.println("Test 4 passed"); + logger.info("\nTest 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void ListDatabases() { + public void testListDatabases() { assertDoesNotThrow(() -> ListDatabases.listAllDatabases(timestreamWriteClient)); - System.out.println("Test 5 passed"); + logger.info("\nTest 5 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void ListTables() { + public void testListTables() { assertDoesNotThrow(() -> ListTables.listAllTables(timestreamWriteClient, dbName)); - System.out.println("Test 6 passed"); + logger.info("\nTest 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void UpdateTable() { + public void testUpdateTable() { assertDoesNotThrow(() -> UpdateTable.updateTable(timestreamWriteClient, dbName, newTable)); - System.out.println("Test 7 passed"); + logger.info("\nTest 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void WriteData() { + public void testWriteData() { assertDoesNotThrow(() -> WriteData.writeRecords(timestreamWriteClient, dbName, newTable)); - System.out.println("Test 8 passed"); + logger.info("\nTest 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void DeleteTable() { + public void testDeleteTable() { assertDoesNotThrow(() -> DeleteTable.deleteSpecificTable(timestreamWriteClient, dbName, newTable)); - System.out.println("Test 9 passed"); + logger.info("\nTest 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) - public void DeleteDatabase() { + public void testDeleteDatabase() { assertDoesNotThrow(() -> DeleteDatabase.delDatabase(timestreamWriteClient, dbName)); - System.out.println("Test 10 passed"); + logger.info("\nTest 10 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/timestream"; diff --git a/javav2/example_code/transcribe-streaming/pom.xml b/javav2/example_code/transcribe-streaming/pom.xml index 8ab07035240..9b809528c88 100644 --- a/javav2/example_code/transcribe-streaming/pom.xml +++ b/javav2/example_code/transcribe-streaming/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -30,7 +30,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -43,11 +50,6 @@ 5.11.4 test - - org.slf4j - slf4j-log4j12 - 2.0.5 - software.amazon.awssdk transcribe @@ -64,5 +66,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + diff --git a/javav2/example_code/transcribe-streaming/src/main/reources/log4j2.xml b/javav2/example_code/transcribe-streaming/src/main/reources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/transcribe-streaming/src/main/reources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java b/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java index 2582bb64a56..29a9ec1268e 100644 --- a/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java +++ b/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java @@ -1,41 +1,34 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.transcribestreaming.BidirectionalStreaming; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; import software.amazon.awssdk.regions.Region; import org.junit.jupiter.api.*; import java.io.*; import java.net.URISyntaxException; -import java.util.*; -import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class TranscribeTest { - + private static final Logger logger = LoggerFactory.getLogger(TranscribeTest.class); private static TranscribeStreamingAsyncClient client; @BeforeAll public static void setUp() throws IOException, URISyntaxException { - Region region = Region.US_EAST_1; client = TranscribeStreamingAsyncClient.builder() .region(region) .build(); } - @Test + @Tag("IntegrationTest") @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(client); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) public void BidirectionalStreaming() throws Exception { BidirectionalStreaming.convertAudio(client); + logger.info("\nTest 1 passed"); } } diff --git a/javav2/example_code/transcribe/pom.xml b/javav2/example_code/transcribe/pom.xml index 27d88cfd969..da6b855eadf 100644 --- a/javav2/example_code/transcribe/pom.xml +++ b/javav2/example_code/transcribe/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,7 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 pom import diff --git a/javav2/example_code/translate/pom.xml b/javav2/example_code/translate/pom.xml index 85fa6ec52d8..96fa6f21669 100644 --- a/javav2/example_code/translate/pom.xml +++ b/javav2/example_code/translate/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -41,7 +41,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -80,5 +87,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/translate/src/main/resources/log4j2.xml b/javav2/example_code/translate/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/translate/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/translate/src/test/java/TranslateTest.java b/javav2/example_code/translate/src/test/java/TranslateTest.java index 7da5e32d971..859305bf72e 100644 --- a/javav2/example_code/translate/src/test/java/TranslateTest.java +++ b/javav2/example_code/translate/src/test/java/TranslateTest.java @@ -10,6 +10,9 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -25,6 +28,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class TranslateTest { + private static final Logger logger = LoggerFactory.getLogger(TranslateTest.class); private static TranslateClient translateClient; private static Region region; private static String s3Uri = ""; @@ -38,7 +42,6 @@ public static void setUp() throws IOException { region = Region.US_WEST_2; translateClient = TranslateClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -49,70 +52,44 @@ public static void setUp() throws IOException { s3UriOut = values.getS3UriOut(); jobName = values.getJobName() + java.util.UUID.randomUUID(); dataAccessRoleArn = values.getDataAccessRoleArn(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * TranslateTest.class.getClassLoader().getResourceAsStream("config.properties") - * ) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * // Populate the data members required for all tests. - * prop.load(input); - * s3Uri = prop.getProperty("s3Uri"); - * s3UriOut = prop.getProperty("s3UriOut"); - * jobName = prop.getProperty("jobName")+ java.util.UUID.randomUUID(); - * dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ - } @Test @Tag("IntegrationTest") @Order(1) - public void TranslateText() { + public void testTranslateText() { assertDoesNotThrow(() -> TranslateText.textTranslate(translateClient)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void BatchTranslation() { + public void testBatchTranslation() { jobId = BatchTranslation.translateDocuments(translateClient, s3Uri, s3UriOut, jobName, dataAccessRoleArn); assertFalse(jobId.isEmpty()); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void ListTextTranslationJobs() { + public void testListTextTranslationJobs() { assertDoesNotThrow(() -> ListTextTranslationJobs.getTranslationJobs(translateClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DescribeTextTranslationJob() { + public void testDescribeTextTranslationJob() { assertDoesNotThrow(() -> DescribeTextTranslationJob.describeTextTranslationJob(translateClient, jobId)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/translate"; diff --git a/javav2/example_code/workdocs/pom.xml b/javav2/example_code/workdocs/pom.xml index 3dbeeea1ea9..27ca5cff0ec 100644 --- a/javav2/example_code/workdocs/pom.xml +++ b/javav2/example_code/workdocs/pom.xml @@ -9,9 +9,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -36,7 +36,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -75,5 +82,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/workdocs/src/main/resources/log4j2.xml b/javav2/example_code/workdocs/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/workdocs/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/workdocs/src/test/java/WorkdocsTest.java b/javav2/example_code/workdocs/src/test/java/WorkdocsTest.java index 9e15d881168..dbbcbce28c5 100644 --- a/javav2/example_code/workdocs/src/test/java/WorkdocsTest.java +++ b/javav2/example_code/workdocs/src/test/java/WorkdocsTest.java @@ -7,6 +7,8 @@ import com.google.gson.Gson; import org.junit.jupiter.api.*; import com.example.workdocs.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; @@ -23,6 +25,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class WorkdocsTest { + private static final Logger logger = LoggerFactory.getLogger(WorkdocsTest.class); private static WorkDocsClient workDocs; private static String orgId = ""; private static String userEmail = "";; @@ -36,7 +39,6 @@ public static void setUp() throws IOException { Region region = Region.US_WEST_2; workDocs = WorkDocsClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -49,71 +51,28 @@ public static void setUp() throws IOException { saveDocFullName = values.getSaveDocFullName(); docName = values.getDocName(); docPath = values.getDocPath(); + } - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * WorkdocsTest.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * prop.load(input); - * orgId = prop.getProperty("orgId"); - * userEmail = prop.getProperty("userEmail"); - * workdocsName = prop.getProperty("workdocsName"); - * saveDocFullName = prop.getProperty("saveDocFullName"); - * docName = prop.getProperty("docName"); - * docPath = prop.getProperty("docPath"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ - } @Test @Tag("IntegrationTest") @Order(1) - public void UploadUserDoc() { - assertDoesNotThrow(() -> UploadUserDocs.uploadDoc(workDocs, orgId, userEmail, docName, docPath)); - System.out.println("Test 1 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void DownloadUserDoc() { - assertDoesNotThrow( - () -> DownloadUserDoc.downloadDoc(workDocs, orgId, userEmail, workdocsName, saveDocFullName)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void ListUserDocs() { + public void testListUserDocs() { assertDoesNotThrow(() -> ListUserDocs.listDocs(workDocs, orgId, userEmail)); - System.out.println("Test 3 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") - @Order(4) - public void ListUsers() { + @Order(2) + public void testListUsers() { assertDoesNotThrow(() -> ListUsers.getAllUsers(workDocs, orgId)); - System.out.println("Test 4 passed"); + logger.info("Test 2 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/workdocs"; diff --git a/javav2/example_code/xray/pom.xml b/javav2/example_code/xray/pom.xml index 52db95e81db..896f01518f3 100644 --- a/javav2/example_code/xray/pom.xml +++ b/javav2/example_code/xray/pom.xml @@ -8,9 +8,9 @@ 1.0-SNAPSHOT UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.29.45 + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -73,5 +80,22 @@ software.amazon.awssdk ssooidc + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + \ No newline at end of file diff --git a/javav2/example_code/xray/src/main/resources/log4j2.xml b/javav2/example_code/xray/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..914470047e7 --- /dev/null +++ b/javav2/example_code/xray/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/xray/src/test/java/XRayTest.java b/javav2/example_code/xray/src/test/java/XRayTest.java index 84180c32180..2aed07ab768 100644 --- a/javav2/example_code/xray/src/test/java/XRayTest.java +++ b/javav2/example_code/xray/src/test/java/XRayTest.java @@ -3,7 +3,8 @@ import com.example.xray.*; import com.google.gson.Gson; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; @@ -21,6 +22,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class XRayTest { + private static final Logger logger = LoggerFactory.getLogger(XRayTest.class); private static XRayClient xRayClient; private static String groupName = ""; private static String newGroupName = ""; @@ -28,11 +30,10 @@ public class XRayTest { @BeforeAll public static void setUp() throws IOException { - + org.apache.logging.log4j.LogManager.getContext(false); Region region = Region.US_EAST_1; xRayClient = XRayClient.builder() .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Random random = new Random(); @@ -45,76 +46,51 @@ public static void setUp() throws IOException { groupName = values.getGroupName(); newGroupName = values.getNewGroupName() + randomNum; ruleName = values.getRuleName() + randomNum; - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * XRayTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * Random rand = new Random(); - * int randomNum = rand.nextInt((10000 - 1) + 1) + 1; - * prop.load(input); - * groupName = prop.getProperty("groupName"); - * newGroupName = prop.getProperty("newGroupName")+randomNum; - * ruleName= prop.getProperty("ruleName")+ randomNum; - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void CreateGroup() { + public void testCreateGroup() { assertDoesNotThrow(() -> CreateGroup.createNewGroup(xRayClient, newGroupName)); - System.out.println("Test 1 passed"); + logger.info("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void CreateSamplingRule() { + public void testCreateSamplingRule() { assertDoesNotThrow(() -> CreateSamplingRule.createRule(xRayClient, ruleName)); - System.out.println("Test 2 passed"); + logger.info("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) - public void GetGroups() { + public void testGetGroups() { assertDoesNotThrow(() -> GetGroups.getAllGroups(xRayClient)); - System.out.println("Test 3 passed"); + logger.info("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DeleteSamplingRule() { + public void testDeleteSamplingRule() { assertDoesNotThrow(() -> DeleteSamplingRule.deleteRule(xRayClient, ruleName)); - System.out.println("Test 4 passed"); + logger.info("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) - public void DeleteGroup() { + public void testDeleteGroup() { assertDoesNotThrow(() -> DeleteGroup.deleteSpecificGroup(xRayClient, newGroupName)); - System.out.println("Test 5 passed"); + logger.info("Test 5 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/xray";