|
| 1 | +package example; |
| 2 | + |
| 3 | +import com.amazonaws.services.lambda.runtime.Context; |
| 4 | +import com.amazonaws.services.lambda.runtime.RequestHandler; |
| 5 | +import software.amazon.awssdk.core.sync.RequestBody; |
| 6 | +import software.amazon.awssdk.services.s3.S3Client; |
| 7 | +import software.amazon.awssdk.services.s3.model.PutObjectRequest; |
| 8 | +import software.amazon.awssdk.services.s3.model.S3Exception; |
| 9 | + |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | + |
| 12 | +/** |
| 13 | + * Lambda handler for processing orders and storing receipts in S3. |
| 14 | + */ |
| 15 | +public class OrderHandler implements RequestHandler<OrderHandler.Order, String> { |
| 16 | + |
| 17 | + private static final S3Client S3_CLIENT = S3Client.builder().build(); |
| 18 | + |
| 19 | + /** |
| 20 | + * Record to model the input event. |
| 21 | + */ |
| 22 | + public record Order(String orderId, double amount, String item) {} |
| 23 | + |
| 24 | + @Override |
| 25 | + public String handleRequest(Order event, Context context) { |
| 26 | + try { |
| 27 | + // Access environment variables |
| 28 | + String bucketName = System.getenv("RECEIPT_BUCKET"); |
| 29 | + if (bucketName == null || bucketName.isEmpty()) { |
| 30 | + throw new IllegalArgumentException("RECEIPT_BUCKET environment variable is not set"); |
| 31 | + } |
| 32 | + |
| 33 | + // Create the receipt content and key destination |
| 34 | + String receiptContent = String.format("OrderID: %s\nAmount: $%.2f\nItem: %s", |
| 35 | + event.orderId(), event.amount(), event.item()); |
| 36 | + String key = "receipts/" + event.orderId() + ".txt"; |
| 37 | + |
| 38 | + // Upload the receipt to S3 |
| 39 | + uploadReceiptToS3(bucketName, key, receiptContent); |
| 40 | + |
| 41 | + context.getLogger().log("Successfully processed order " + event.orderId() + |
| 42 | + " and stored receipt in S3 bucket " + bucketName); |
| 43 | + return "Success"; |
| 44 | + |
| 45 | + } catch (Exception e) { |
| 46 | + context.getLogger().log("Failed to process order: " + e.getMessage()); |
| 47 | + throw new RuntimeException(e); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private void uploadReceiptToS3(String bucketName, String key, String receiptContent) { |
| 52 | + try { |
| 53 | + PutObjectRequest putObjectRequest = PutObjectRequest.builder() |
| 54 | + .bucket(bucketName) |
| 55 | + .key(key) |
| 56 | + .build(); |
| 57 | + |
| 58 | + // Convert the receipt content to bytes and upload to S3 |
| 59 | + S3_CLIENT.putObject(putObjectRequest, RequestBody.fromBytes(receiptContent.getBytes(StandardCharsets.UTF_8))); |
| 60 | + } catch (S3Exception e) { |
| 61 | + throw new RuntimeException("Failed to upload receipt to S3: " + e.awsErrorDetails().errorMessage(), e); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments