Hi,
I am using below lambda function with S3Event.
But below if statement not working. If I execute below Lambda function by IntelliJ ide AWS plugin then its working. But if I trigger event in S3 bucket then this if statement is not working. And without if statement able to execute properly. Kindly suggest.
if(env.equalsIgnoreCase("stage")) {
package com.zackroppel.lambda.gradebook;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.ByteBuffer;
public class TestLambdaS3Event implements RequestHandler<S3Event, String> {
private AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();
AWSLambda s3EventClient = AWSLambdaClientBuilder.standard().build();
public TestLambdaS3Event() {
}
@Override
public String handleRequest(S3Event event, Context context) {
context.getLogger().log("Received event: " + event);
// Get the object from the event and show its content type
String bucket = event.getRecords().get(0).getS3().getBucket().getName();
System.out.println("bucket##"+bucket);
String key = event.getRecords().get(0).getS3().getObject().getKey();
System.out.println("key##"+key);
try {
S3Object response = s3.getObject(new GetObjectRequest(bucket, key));
System.out.println("response##"+response);
String contentType = response.getObjectMetadata().getContentType();
byte[] byteArray = IOUtils.toByteArray(response.getObjectContent());
String env = bucket.substring(bucket.lastIndexOf("/")+1);
System.out.println("env@@"+ env);
if(env.equalsIgnoreCase("stage")) {
UpdateFunctionCodeRequest request = new UpdateFunctionCodeRequest().withFunctionName("sagemaker_stick_and_slip_prediction")
.withZipFile(ByteBuffer.wrap(byteArray));
System.out.println("request## " + request);
UpdateFunctionCodeResult responseUpdate = s3EventClient.updateFunctionCode(request);
System.out.println("responseUpdate## " + responseUpdate);
}
return contentType;
} catch (IOException | AmazonS3Exception e) {
e.printStackTrace();
System.out.println("Exception## "+ e.getMessage());
context.getLogger().log(String.format("Error getting object %s from bucket %s. Make sure they exist and"
+ " your bucket is in the same region as this function.", bucket, key));
return e.toString();
}
}
}