Error: Could not find JobId Service: AmazonRekognition; Status Code: 400; - amazon-web-services

I am using this Java Lambda code provided by AWS to detect labels in a video:
https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/code_examples/java_examples/stored_video/java-lambda-handler-sns.java
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import java.util.List;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.GetLabelDetectionRequest;
import com.amazonaws.services.rekognition.model.GetLabelDetectionResult;
import com.amazonaws.services.rekognition.model.LabelDetection;
import com.amazonaws.services.rekognition.model.LabelDetectionSortBy;
import com.amazonaws.services.rekognition.model.VideoMetadata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JobCompletionHandler implements RequestHandler<SNSEvent, String> {
#Override
public String handleRequest(SNSEvent event, Context context) {
String message = event.getRecords().get(0).getSNS().getMessage();
LambdaLogger logger = context.getLogger();
// Parse SNS event for analysis results. Log results
try {
ObjectMapper operationResultMapper = new ObjectMapper();
JsonNode jsonResultTree = operationResultMapper.readTree(message);
logger.log("Rekognition Video Operation:=========================");
logger.log("Job id: " + jsonResultTree.get("JobId"));
logger.log("Status : " + jsonResultTree.get("Status"));
logger.log("Job tag : " + jsonResultTree.get("JobTag"));
logger.log("Operation : " + jsonResultTree.get("API"));
if (jsonResultTree.get("API").asText().equals("StartLabelDetection")) {
if (jsonResultTree.get("Status").asText().equals("SUCCEEDED")){
GetResultsLabels(jsonResultTree.get("JobId").asText(), context);
}
else{
String errorMessage = "Video analysis failed for job "
+ jsonResultTree.get("JobId")
+ "State " + jsonResultTree.get("Status");
throw new Exception(errorMessage);
}
} else
logger.log("Operation not StartLabelDetection");
} catch (Exception e) {
logger.log("Error: " + e.getMessage());
throw new RuntimeException (e);
}
return message;
}
void GetResultsLabels(String startJobId, Context context) throws Exception {
LambdaLogger logger = context.getLogger();
AmazonRekognition rek = AmazonRekognitionClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
int maxResults = 1000;
String paginationToken = null;
GetLabelDetectionResult labelDetectionResult = null;
String labels = "";
Integer labelsCount = 0;
String label = "";
String currentLabel = "";
//Get label detection results and log them.
do {
GetLabelDetectionRequest labelDetectionRequest = new GetLabelDetectionRequest().withJobId(startJobId)
.withSortBy(LabelDetectionSortBy.NAME).withMaxResults(maxResults).withNextToken(paginationToken);
labelDetectionResult = rek.getLabelDetection(labelDetectionRequest);
paginationToken = labelDetectionResult.getNextToken();
VideoMetadata videoMetaData = labelDetectionResult.getVideoMetadata();
// Add labels to log
List<LabelDetection> detectedLabels = labelDetectionResult.getLabels();
for (LabelDetection detectedLabel : detectedLabels) {
label = detectedLabel.getLabel().getName();
if (label.equals(currentLabel)) {
continue;
}
labels = labels + label + " / ";
currentLabel = label;
labelsCount++;
}
} while (labelDetectionResult != null && labelDetectionResult.getNextToken() != null);
logger.log("Total number of labels : " + labelsCount);
logger.log("labels : " + labels);
}
}
When checking the results in cloudwatch I receive an error:

05:23:48
Rekognition Video Operation:=========================

05:23:48
Job id: "f647269c4f8bab504cfc9e50a2d89593e463c31755e3bdf41fac18b8be603d65"

05:23:48
Status : "SUCCEEDED"

05:23:48
Job tag : null

05:23:48
Operation : "StartLabelDetection"

05:23:49
*Error: Could not find JobId (Service: AmazonRekognition; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: c4d9bbe0-00f2-11e9-8aa2-21ecd18719a6)*

05:23:49
com.amazonaws.services.rekognition.model.ResourceNotFoundException: Could not find JobId (Service: AmazonRekognition; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: c4d9bbe0-00f2-11e9-8aa2-21ecd18719a6): java.lang.RuntimeException java.lang.RuntimeException: com.amazonaws.services.rekognition.model.ResourceNotFoundException: Could not find JobId (Service: AmazonRekognition; S

05:23:49
END RequestId: 4f531035-00f2-11e9-96d7-f55b78da9771

05:23:49
REPORT RequestId: 4f531035-00f2-11e9-96d7-f55b78da9771 Duration: 941.37 ms Billed Duration: 1000 ms Memory Size: 1024 MB Max Memory Used: 98 MB
I am using the root account and have set up AWS as described in the " Create the AWS Toolkit for Eclipse Lambda Project" Rekognition developer-guide.
Is the problem with the code or something else ?

After consulting with AWS Rekognition forum I was advised to make sure I am calling the fucntion from the same region as stipulated in the function :
AmazonRekognition rek =
AmazonRekognitionClientBuilder.standard().withRegion(Regions.US_EAST_1).build();

Related

Get all the failed executions of a state machine in AWS Step function and execute dynamically. (In java)

I want to fetch all the failed executions and need to re-trigger them dynamically.
PS: In stepfunction definition I had proper retry mechanism, now I want to rerun the failed executions dynamically.
I need to implement it in java. Please help me with the approach.
Thanks in advance.
You can use the AWS Step Functions API to get a list of excutions:
https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sfn/SfnClient.html#listExecutions-
Then you can get a list of ExecutionListItem by calling the executions() method that belongs to the ListExecutionsResponse object (returned by the listExecutions method)
https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sfn/model/ExecutionListItem.html
Using this object - you can do two things:
1 - check status - https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sfn/model/ExecutionStatus.html
2 - get state machine ARN value - https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sfn/model/ExecutionListItem.html#stateMachineArn--
Using the state machine ARN value, you can execute a state machine with the AWS Step Functions Java API V2:
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.UUID;
// snippet-end:[stepfunctions.java2.start_execute.import]
public class StartExecution {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" StartExecution <stateMachineArn> <jsonFile>\n\n" +
"Where:\n" +
" stateMachineArn - the ARN of the state machine.\n\n" +
" jsonFile - A JSON file that contains the values to pass to the worflow.\n" ;
if (args.length != 2) {
System.out.println(USAGE);
System.exit(1);
}
String stateMachineArn = args[0];
String jsonFile = args[1];
Region region = Region.US_EAST_1;
SfnClient sfnClient = SfnClient.builder()
.region(region)
.build();
String exeArn = startWorkflow(sfnClient,stateMachineArn, jsonFile);
System.out.println("The execution ARN is" +exeArn);
sfnClient.close();
}
// snippet-start:[stepfunctions.java2.start_execute.main]
public static String startWorkflow(SfnClient sfnClient, String stateMachineArn, String jsonFile) {
String json = getJSONString(jsonFile);
// Specify the name of the execution by using a GUID value.
UUID uuid = UUID.randomUUID();
String uuidValue = uuid.toString();
try {
StartExecutionRequest executionRequest = StartExecutionRequest.builder()
.input(json)
.stateMachineArn(stateMachineArn)
.name(uuidValue)
.build();
StartExecutionResponse response = sfnClient.startExecution(executionRequest);
return response.executionArn();
} catch (SfnException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
private static String getJSONString(String path) {
try {
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(new FileReader(path));//path to the JSON file.
String json = data.toJSONString();
return json;
} catch (IOException | org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
return "";
}
// snippet-end:[stepfunctions.java2.start_execute.main]
}

Unable to fetch the data from AWS DynamoDB

I want to fetch the data from AWS dynamodb in eclipse maven/java but shows the following error
Requested resource not found (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: NU99FP2PJA0PELJ9R20R7LCHSNVV4KQNSO5AEMVJF66Q9ASUAAJG)
Cannot retrieve items.
Requested resource not found (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 3DFTIT8QENPPB5L2BCQLCQJF2JVV4KQNSO5AEMVJF66Q9ASUAAJG)
I have tried the following code to add the region but still showing this error
dynamoDB.setRegion(Region.getRegion(Regions.ap-south-1));
My code:
package DB;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.partitions.model.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
public class Test {
#SuppressWarnings("deprecation")
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
// dynamoDB.setRegion(Region.getRegion(Regions.ap-south-1));
// Region usWest2 = Region.getRegion(Regions.US_EAST_1);
// dynamoDB.setRegion(usWest2);
static String tblName = "ProductList";
public static void main(String[] args) throws IOException {
createItems();
retrieveItem();
}
private static void createItems() {
Table table = dynamoDB.getTable(tblName);
try {
Item item = new Item()
.withPrimaryKey("ID", 303)
.withString("Nomenclature", "Polymer Blaster 4000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
.withNumber("Price", 50000)
.withBoolean("InProduction", true)
.withString("Category", "Laser Cutter");
table.putItem(item);
item = new Item()
.withPrimaryKey("ID", 313)
.withString("Nomenclature", "Agitatatron 2000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
.withNumber("Price", 40000)
.withBoolean("InProduction", true)
.withString("Category", "Agitator");
table.putItem(item);
} catch (Exception e) {
System.err.println("Cannot create items.");
System.err.println(e.getMessage());
}
}
private static void retrieveItem() {
Table table = dynamoDB.getTable(tblName);
try {
Item item = table.getItem("ID", 303, "ID, Nomenclature, Manufacturers", null);
System.out.println("Displaying retrieved items...");
System.out.println(item.toJSONPretty());
} catch (Exception e) {
System.err.println("Cannot retrieve items.");
System.err.println(e.getMessage());
}
}
}
Your code looks fine, therefore make sure that your table does exist in ap-south-1 region.

Listing folders on S3

just trying to parse and display a whole bucket, i can't get rid off the message no suchKeyException which is odd ..
The code below is connecting and displaying to standard out:
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.s3.model.EncodingType
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable
import java.net.URI
internal class S3ObjectsOps {
companion object {
private val BUCKET: String = "mybucket"
private val REGION_IRE = software.amazon.awssdk.regions.Region.EU_WEST_1
val s3c = S3Client.builder()
.region(REGION_IRE)
.endpointOverride(URI("https://${BUCKET}.s3-eu-west-1.amazonaws.com/"))
.credentialsProvider(ProfileCredentialsProvider.builder()
.profileName("default")
.build())
.build()
fun lsfolders(bucket: String) {
val listReq = ListObjectsV2Request.builder()
.bucket(bucket)
.delimiter("/")
.prefix("")
.maxKeys(10_000)
.build()
val listRes = s3c.listObjectsV2Paginator(listReq)
listRes.contents().onEach { f ->
if (!f.key().isNullOrBlank()) {
println(">> ${f.key()}")
} else {
println(" = ")
}
}
}
#JvmStatic
fun main(args: Array<String>) {
val bucket: String = ((args.size > 0 && !args[0].isNullOrEmpty()).toString()) ?: BUCKET
println("s3 ls test for bucket ${bucket}")
lsfolders(bucket)
}
}
}
Which raises:
software.amazon.awssdk.services.s3.model.NoSuchKeyException: The specified key does not exist. (Service: S3Client; Status Code: 404; Request ID: C8AF9CB788D77F74)
Exception in thread "main" software.amazon.awssdk.services.s3.model.NoSuchKeyException: The specified key does not exist. (Service: S3Client; Status Code: 404; Request ID: C8AF9CB788D77F74)
at software.amazon.awssdk.core.http.pipeline.stages.HandleResponseStage.handleErrorResponse(HandleResponseStage.java:114)
Same Exception using a stream
listRes.contents().stream().forEach { content -> println(" Key: " + content.key() + " | ") }
Thanks folks !
The right calls of ListObjectsV2Request is:
val listReq = ListObjectsV2Request.builder()
.bucket(bucket)
.delimiter("/")
.build()
val listRes = s3c.listObjectsV2Paginator(listReq)
listRes.contents().stream().forEach { content -> println(" Key: " + content.key() + " | ") }
Then, s3client must init with mimimum params:
val s3c = S3Client.builder()
.credentialsProvider(ProfileCredentialsProvider.builder().profileName("default").build())
.region(REGION_IRE)
.build()

Async HTTP Upload to S3 using presignedURL (with progress indicator)

The code below provides the ability to upload a zip archive to a AWS s3 presigned URL. I resorted to using HttpURLConnection to conduct the upload, but it seems to block on getResponse. I am looking to implement a feedback loop so that I can print the progress of upload completed.
How I can go about capturing progress of upload that I can print to stdout?
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
public class App {
private static String bucketName = "XXXXX";
private static String objectKey = "XXXX/file.zip";
public static void main(String[] args) throws Exception {
URL url = getPresignedUrl();
uploadToUrlHTTP(url,new File("/XXX/XXXX/file.zip"));
}
public static URL getPresignedUrl() {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider("default")).build();
try {
System.out.println("Generating pre-signed URL.");
java.util.Date expiration = new java.util.Date();
long milliSeconds = expiration.getTime();
milliSeconds += 1000 * 60 * 60; // Add 1 hour.
expiration.setTime(milliSeconds);
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
generatePresignedUrlRequest.setExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
System.out.println("Pre-Signed URL = " + url.toString());
return url;
} catch (AmazonServiceException exception) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + exception.getMessage());
System.out.println("HTTP Code: " + exception.getStatusCode());
System.out.println("AWS Error Code:" + exception.getErrorCode());
System.out.println("Error Type: " + exception.getErrorType());
System.out.println("Request ID: " + exception.getRequestId());
return null;
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
return null;
}
}
public static void uploadToUrlHTTP(URL url, File file) {
HttpURLConnection connection;
try {
InputStream inputStream = new FileInputStream(file);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
OutputStream out =
connection.getOutputStream();
byte[] buf = new byte[1024];
int count;
int total = 0;
long fileSize = file.length();
while ((count =inputStream.read(buf)) != -1)
{
if (Thread.interrupted())
{
throw new InterruptedException();
}
out.write(buf, 0, count);
total += count;
int pctComplete = new Double(new Double(total) / new Double(fileSize) * 100).intValue();
System.out.print("\r");
System.out.print(String.format("PCT Complete: %d", pctComplete));
}
System.out.println();
out.close();
inputStream.close();
System.out.println("Finishing...");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.printf("Successfully uploaded.");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

aws credentials not found error

I have a jar uploaded to aws lambda but it keeps throwing below error:
{
"errorMessage": "java.lang.NullPointerException",
"errorType": "java.lang.NullPointerException",
"stackTrace": [
"com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:143)",
"com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:132)",
"com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:99)",
"com.amazonaws.auth.profile.ProfileCredentialsProvider.getCredentials(ProfileCredentialsProvider.java:135)",
"com.amazonaws.http.AmazonHttpClient.getCredentialsFromContext(AmazonHttpClient.java:802)",
"com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:828)",
"com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:723)",
"com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:475)",
"com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:437)",
"com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:386)",
"com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:2074)",
"com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2044)",
"com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.putItem(AmazonDynamoDBClient.java:1580)",
"com.amazonaws.services.dynamodbv2.document.internal.PutItemImpl.doPutItem(PutItemImpl.java:85)",
"com.amazonaws.services.dynamodbv2.document.internal.PutItemImpl.putItem(PutItemImpl.java:41)",
"com.amazonaws.services.dynamodbv2.document.Table.putItem(Table.java:144)",
"augury.api.SaveAuguryApi.handleRequest(SaveAuguryApi.java:46)",
"sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
"sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)",
"sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)",
"java.lang.reflect.Method.invoke(Method.java:498)"
]
}
and stack trace:
java.lang.NullPointerException: java.lang.NullPointerException
java.lang.NullPointerException
at com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:143)
at com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:132)
at com.amazonaws.auth.profile.ProfilesConfigFile.<init>(ProfilesConfigFile.java:99)
at com.amazonaws.auth.profile.ProfileCredentialsProvider.getCredentials(ProfileCredentialsProvider.java:135)
at com.amazonaws.http.AmazonHttpClient.getCredentialsFromContext(AmazonHttpClient.java:802)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:828)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:723)
at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:475)
at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:437)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:386)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:2074)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2044)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.putItem(AmazonDynamoDBClient.java:1580)
at com.amazonaws.services.dynamodbv2.document.internal.PutItemImpl.doPutItem(PutItemImpl.java:85)
at com.amazonaws.services.dynamodbv2.document.internal.PutItemImpl.putItem(PutItemImpl.java:41)
at com.amazonaws.services.dynamodbv2.document.Table.putItem(Table.java:144)
at augury.api.SaveAuguryApi.handleRequest(SaveAuguryApi.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
END RequestId: b2b9807e-6a09-11e6-9873-2588e6cfa497
REPORT RequestId: b2b9807e-6a09-11e6-9873-2588e6cfa497 Duration: 305.85 ms Billed Duration: 400 ms Memory Size: 512 MB Max Memory Used: 61 MB
And also my lambda java code:
package augury.api;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import augury.pojo.AuguryResponse;
import augury.pojo.AuguryResult;
public class SaveAuguryApi implements RequestHandler<AuguryResult, AuguryResponse> {
// Initialize the Log4j logger.
static final Logger log = Logger.getLogger(SaveAuguryApi.class);
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
static String tableName = "tarot_history";
public AuguryResponse handleRequest(AuguryResult result, Context context) {
String userId = result.getUserId();
List<Integer> tarotIds = result.getTarotIds();
String createTime = result.getCreate_time();
if (log.isDebugEnabled()) {
log.debug("requestId = " + context.getAwsRequestId() + ", userId = " + userId + ", tarotIds = " + tarotIds
+ ", create_time = " + createTime);
}
if (StringUtils.isBlank(userId) || tarotIds == null || tarotIds.isEmpty() || StringUtils.isBlank(createTime)) {
return new AuguryResponse(400, "this request doesn't contain rightful parameters, please check log");
}
Table table = dynamoDB.getTable(tableName);
Item item = new Item();
item.withString("create_time", createTime);
item.withString("user_id", userId);
item.withList("tarot_ids", tarotIds);
item.withInt("id", 1);
table.putItem(item);
return new AuguryResponse(201, "tarot history created");
}
}
i tried but i still couldn't locate the problem. I'm new to aws lambda and I was trying to learn from the link
The example you are looking at assumes you have credential properties saved to a file, which isn't going to be the case in your Lambda environment. To use the IAM role assigned to the Lambda function change this:
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
To this:
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient());