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