Created
November 12, 2020 15:43
-
-
Save Ugbot/3f3904db979b4216183fc1b5aedf008f to your computer and use it in GitHub Desktop.
This AWS Lambda that posts an Ably message to S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import com.amazonaws.AmazonServiceException; | |
import com.amazonaws.services.lambda.runtime.Context; | |
import com.amazonaws.services.lambda.runtime.RequestHandler; | |
import com.amazonaws.services.lambda.runtime.LambdaLogger; | |
import com.amazonaws.SdkClientException; | |
import com.amazonaws.regions.Regions; | |
import com.amazonaws.services.s3.AmazonS3; | |
import com.amazonaws.services.s3.AmazonS3ClientBuilder; | |
import com.amazonaws.services.s3.model.ObjectMetadata; | |
import com.amazonaws.services.s3.model.PutObjectRequest; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import java.io.File; | |
import java.time.LocalDateTime; | |
import java.time.format.DateTimeFormatter; | |
import java.util.Map; | |
import static java.lang.Thread.sleep; | |
// Handler value: example.Handler | |
public class Handler implements RequestHandler<Map<String,Object>, String>{ | |
Gson gson = new GsonBuilder().setPrettyPrinting().create(); | |
@Override | |
public String handleRequest(Map<String,Object> event, Context context) | |
{ | |
LambdaLogger logger = context.getLogger(); | |
String response = new String("400 fail"); | |
for (Map.Entry<String, Object> entry : event.entrySet()) { | |
logger.log("EVENT: " + (entry)); | |
} | |
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); | |
LocalDateTime now = LocalDateTime.now(); | |
//System.out.println(); | |
Regions clientRegion = Regions.EU_WEST_2; | |
String bucketName = "log-storage-demo"; | |
String stringObjKeyName = dtf.format(now); | |
try { | |
AmazonS3 s3Client = AmazonS3ClientBuilder.standard() | |
.withRegion(clientRegion) | |
.build(); | |
// Upload a text string as a new object. | |
s3Client.putObject(bucketName, stringObjKeyName, "EVENT: " +String.valueOf(event)); | |
response = new String("200 " + | |
"ok"); | |
} catch (AmazonServiceException e) { | |
// The call was transmitted successfully, but Amazon S3 couldn't process | |
// it, so it returned an error response. | |
response = new String("400 " + | |
"fail"); | |
e.printStackTrace(); | |
} catch (SdkClientException e) { | |
// Amazon S3 couldn't be contacted for a response, or the client | |
// couldn't parse the response from Amazon S3. | |
response = new String("400 " + | |
"fail"); | |
e.printStackTrace(); | |
} | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment