@Test public void handleRequestShouldThrowException() throws TemplateException, KeyOperationException, IOException { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Email"); LinkGeneratorLambdaHandler handler = mock(LinkGeneratorLambdaHandler.class); doCallRealMethod().when(handler).handleRequest(any(), any()); Exception ex = new TemplateException("Message", null); doThrow(ex).when(handler).getUploadPageUrlFromRequest(any(), any()); Context context = mock(Context.class); LambdaLogger logger = mock(LambdaLogger.class); doNothing().when(logger).log(anyString()); doReturn(logger).when(context).getLogger(); handler.handleRequest(mock(LinkGeneratorRequest.class), context); }
@Override public String handleRequest(ReducerWrapperInfo reducerWrapperInfo, Context context) { try { this.reducerWrapperInfo = reducerWrapperInfo; this.reducerLogic = instantiateReducerClass(); this.jobInfo = this.reducerWrapperInfo.getJobInfo(); this.jobId = this.jobInfo.getJobId(); List<ObjectInfoSimple> batch = reducerWrapperInfo.getBatch(); String reduceResult = processBatch(batch); if (this.reducerWrapperInfo.isLast()) storeFinalResult(reduceResult); else storeIntermediateResult(reduceResult); } catch (Exception e) { throw new RuntimeException(e); } return IGNORED_RETURN_VALUE; }
@Override public String handleRequest(ReducersDriverInfo reducersDriverInfo, Context context) { try { this.reducersDriverInfo = reducersDriverInfo; this.jobInfo = this.reducersDriverInfo.getJobInfo(); this.jobId = this.jobInfo.getJobId(); launchReducers(reducersDriverInfo.getStep()); } catch (Exception e) { throw new RuntimeException(e); } return IGNORED_RETURN_VALUE; }
@Test public void testTradeHandler() { try { TradeServiceRequestHandler tradeServiceRequestHandler = new TradeServiceRequestHandler(); Context ctx = createContext(); List<Vehicle> output = tradeServiceRequestHandler.getTradeMotTests(input, ctx); if (output != null) { System.out.println(output.toString()); } } catch (TradeException e) { e.printStackTrace(); } }
/** * This is a handler method called by the AWS Lambda runtime */ @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { // Lambda function is allowed write access to /tmp only System.setProperty("vertx.cacheDirBase", "/tmp/.vertx"); Vertx vertx = Vertx.vertx(); router = Router.router(vertx); router.route().handler(rc -> { LocalDateTime now = LocalDateTime.now(); rc.response().putHeader("content-type", "text/html").end("Hello from Lambda at " + now); }); // create a LambdaServer which will process a single HTTP request LambdaServer server = new LambdaServer(vertx, context, input, output); // trigger the HTTP request processing server.requestHandler(this::handleRequest).listen(); // block the main thread until the request has been fully processed waitForResponseEnd(); }
@Override public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { Collection<String> partitionsToRemove = new HashSet<>(); DateTime expiryThreshold = partitionConfig.partitionType().roundDownTimeUnit(clock.now()) .minus(expirationConfig.expiresAfterMillis()); Collection<String> existingPartitions = tableService.getExistingPartitions(partitionConfig.tableName()); for (String existingPartition : existingPartitions) { DateTime partitionDateTime = partitionConfig.partitionType().roundDownTimeUnit( DateTime.parse(existingPartition, DATE_TIME_PATTERN)); if (hasExpired(partitionDateTime, expiryThreshold)) { partitionsToRemove.add(existingPartition); } } if (!partitionsToRemove.isEmpty()) { tableService.removePartitions(partitionConfig.tableName(), partitionsToRemove); } }
@Before public void setUp() throws Exception { context = mock(Context.class); when(context.getLogger()).thenReturn(System.out::println); handler = new AuthLambdaHandler(TEST_AWS_REGION, TEST_JWT_KEY_ARN, TEST_VIDEO_STORAGE_BUCKET, TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(TEST_AWS_REGION) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY)) ) .build(); kmsEncrypt = new KMSEncrypt(kmsClient, TEST_JWT_KEY_ARN); }
@Test public void shouldFailOnOtherError() throws Exception { // Given Context context = mock(Context.class); SNSEvent snsEvent = createSnsEvent("push"); doThrow(new IllegalArgumentException("Expected test exception")).when(config).isWatchedBranch(any()); // When Integer response = uut.handleRequest(snsEvent, context); // Then assertThat(response, is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); verify(config, times(1)).isWatchedBranch(any()); verify(worker, times(0)).call(); }
@SuppressWarnings("unchecked") @Test public void testScheduledEventHandlerSuccessfully() throws Exception { new Expectations(TestScheduledAction.class) { { new TestScheduledAction().handle((EventActionRequest<EmptyActionBody>)any, (Context)any); times = 1; } }; ScheduledEventResult result = handler.handleRequest(event, mockContext); assertEquals(1, result.getSuccessItems().size()); assertEquals(0, result.getFailureItems().size()); assertEquals(0, result.getSkippedItems().size()); }
@Override public Object handleRequest(Map<String, Object> input, Context context) { LexRequest lexRequest = LexRequestFactory.createLexRequest(input); String content = String.format("Request came from the bot: %s, Department: %s;" + "You ordered: %s %s of %s", lexRequest.getBotName(), lexRequest.getDepartmentName(), lexRequest.getAmount(), lexRequest.getUnit(), lexRequest.getProduct() ); Message message = new Message("PlainText", content); DialogAction dialogAction = new DialogAction("Close", "Fulfilled", message); return new LexRespond(dialogAction); }
@Test public void testTradeHandler() { try { TradeServiceRequestHandler tradeServiceRequestHandler = new TradeServiceRequestHandler(); Context ctx = createContext(); List<DisplayMotTestItem> output = tradeServiceRequestHandler.getTradeMotTestsLegacy(input, ctx); if (output != null) { System.out.println(output.toString()); } } catch (TradeException e) { e.printStackTrace(); } }
private void handleDebugRequest(Map<String, Object> input, OutputStream outputStream, Context context) throws IOException { Map<String, Object> responseJson = new LinkedHashMap<>(); try { responseJson.put("statusCode", 200); responseJson.put("body", MAPPER.writeValueAsString(input)); } catch (Exception pex) { responseJson.put("statusCode", "500"); responseJson.put("exception", pex); } MAPPER.writeValue(outputStream, responseJson); }
@Override public Object handleRequest(Map<String, Object> input, Context context) { LOG.info("received: " + input); return buildResponseBody(input, context); // Or as lambda-proxy response for API Gateway: // return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(buildResponseBody(input, context)).build(); }
private Object buildResponseBody(Map<String, Object> input, Context context) { try { if (input.get("action").equals("warmup")) { sleepMinimumDuration(((Number) input.get("minimumDurationMilliseconds")).longValue()); String uptime = Files.readAllLines(Paths.get("/proc/uptime")).stream().collect(Collectors.joining()); return new WarmupResponse(uptime, context.getLogStreamName()); } return new Response("Go Serverless v1.x! Your function executed successfully!", input); } catch (Exception e) { LOG.error("Couldn't build Response", e); throw new RuntimeException(e); } }
public final void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(inputStream)); SmartHomeDirectiveRequest request = gson.fromJson(reader, SmartHomeDirectiveRequest.class); RequestHandler handler = factory.getHandler(request.getHeader().getName()); Request req = PayloadDeserializer.deserializePayload(request); Response responsePayload; try { responsePayload = handler.handle(req); } catch (Exception e) { throw new IOException(e); } SmartHomeDirectiveResponse response = new SmartHomeDirectiveResponse(); Header responseHeader = new Header(); responseHeader.setName(responsePayload.getMessageName()); responseHeader.setMessageId(request.getHeader().getMessageId()); responseHeader.setPayloadVersion(request.getHeader().getPayloadVersion()); responseHeader.setNamespace(request.getHeader().getNamespace()); response.setHeader(responseHeader); response.setPayload(responsePayload); OutputStreamWriter writer = new OutputStreamWriter(outputStream); writer.write(gson.toJson(response, SmartHomeDirectiveResponse.class)); writer.flush(); }
@Override public SampleMessageBody handle(ActionRequest<SampleMessageBody> request, Context context) { // echo back SampleMessageBody res = new SampleMessageBody(); res.message = request.getBody().message; res.name = request.getBody().name; return res; }
@Override public String handleRequest(LinkGeneratorRequest request, Context context) { try { return getUploadPageUrlFromRequest(request, context); } catch (Exception ex) { String type = getLambdaExceptionTypeLabel(ex); LambdaExceptionLogger.logException(context, ex); throw new RuntimeException("[" + type + "] " + ex.getMessage(), ex); } }
/** * {@inheritDoc} * @see com.visionarts.powerjambda.LambdaAction#handle(java.lang.Object, com.amazonaws.services.lambda.runtime.Context) */ @Override public Person handle(ActionRequest<Person> request, Context context) { Person reqPerson = request.getBody(); // echo Person response = new Person(); response.name = reqPerson.name; response.age = reqPerson.age; return response; }
public static void logException(Context context, Exception exception) { // Collect all stack traces List<String> theTrace = new ArrayList<>(); Throwable throwable = exception; while (throwable != null) { theTrace.add(throwable.getClass().getSimpleName() + ": " + throwable.getMessage()); StackTraceElement[] stackTrace = throwable.getStackTrace(); Arrays.stream(stackTrace).map(StackTraceElement::toString).forEach(theTrace::add); throwable = throwable.getCause(); } //Log the stack traces context.getLogger().log(theTrace.stream().collect(Collectors.joining("\n"))); }
/** * {@inheritDoc} * @since 2017/12/13 */ @Override public final O handleRequest(I __input, Context __context) { return IOpipeService.instance().<O>run(__context, () -> this.wrappedHandleRequest(__input, __context)); }
@Override public AwsProxyResponse handleException(Throwable exception, Context context) throws InternalErrorException { DefaultActionExceptionResolver<AwsProxyResponse> resolver = new DefaultActionExceptionResolver<>(new JsonResponseWriter<>()); return applyFilters(resolver.handleException(exception, this, context)); }
@Override public String handleRequest(Map<String, Object> request, Context context) { try { String email = request.get("email").toString(); String url = request.get("url").toString(); Mailer mailer = createMailer(email, url); mailer.send(); return "OK"; } catch (IOException | TemplateException ex) { LambdaExceptionLogger.logException(context, ex); return "NOT OK"; //TODO: Fix this } }
@Override protected final void afterHandle(ActionRequest<T> actionRequest, Context context) throws Exception { try { afterAction(actionRequest, context); } finally { FunctionalUtils.toBiConsumer(loggerAfterHandle(), logger) .accept(actionRequest, context); } }
/** * Tests throwing of an exception with a cause. * * @param __sv The running service. * @param __c The execution context. * @since 2017/12/17 */ public void baseThrowWithCause(IOpipeService __sv, Context __c) { AtomicBoolean ranfunc = new AtomicBoolean(), exceptioncaught = new AtomicBoolean(); try { __sv.<Object>run(__c, () -> { ranfunc.set(true); throw new MockException("Not our fault!", new MockException("This is why!")); }); } catch (MockException e) { exceptioncaught.set(true); } assertTrue("ranfunc", ranfunc.get()); assertTrue("exceptioncaught", exceptioncaught.get()); }
@Override public Void handleRequest(S3Event s3Event, Context context) { Collection<Partition> requiredPartitions = new HashSet<>(); TableService tableService = new TableService(); for (S3EventNotification.S3EventNotificationRecord record : s3Event.getRecords()) { String bucket = record.getS3().getBucket().getName(); String key = record.getS3().getObject().getKey(); System.out.printf("S3 event [Event: %s, Bucket: %s, Key: %s]%n", record.getEventName(), bucket, key); S3Object s3Object = new S3Object(bucket, key); if (s3Object.hasDateTimeKey()) { requiredPartitions.add(partitionConfig.createPartitionFor(s3Object)); } } if (!requiredPartitions.isEmpty()) { Collection<Partition> missingPartitions = determineMissingPartitions( partitionConfig.tableName(), requiredPartitions, tableService); tableService.addPartitions(partitionConfig.tableName(), missingPartitions); } return null; }
@Override public Void handleRequest(S3Event s3Event, Context context) { Collection<Partition> partitionsToRemove = new HashSet<>(); TableService tableService = new TableService(); for (S3EventNotification.S3EventNotificationRecord record : s3Event.getRecords()) { String bucket = record.getS3().getBucket().getName(); String key = record.getS3().getObject().getKey(); System.out.printf("S3 event [Event: %s, Bucket: %s, Key: %s]%n", record.getEventName(), bucket, key); S3Object s3Object = new S3Object(bucket, key); if (s3Object.hasDateTimeKey()) { partitionsToRemove.add(partitionConfig.createPartitionFor(s3Object)); } } if (!partitionsToRemove.isEmpty()) { tableService.removePartitions( partitionConfig.tableName(), partitionsToRemove.stream().map(Partition::spec).collect(Collectors.toList())); } return null; }
@Override public Void handleRequest(S3Event s3Event, Context context){ Collection<Partition>requiredPartitions = new HashSet<>(); TableService tableService = new TableService(); DynamoDB dynamoDBClient=new DynamoDB(new AmazonDynamoDBClient(new EnvironmentVariableCredentialsProvider())); for(S3EventNotification.S3EventNotificationRecord record:s3Event.getRecords()){ String bucket=record.getS3().getBucket().getName(); String key=record.getS3().getObject().getKey(); System.out.printf("S3event[Event:%s,Bucket:%s,Key:%s]%n",record.getEventName(),bucket,key); S3Object s3Object=new S3Object(bucket,key); if(s3Object.hasDateTimeKey()){ Partition partition = partitionConfig.createPartitionFor(s3Object); //Check if the partition exists in DynamoDBtable, if not add the partition details to the table, skip otherwise if (tryAddMissingPartition(partitionConfig.dynamoDBTableName(), dynamoDBClient, partition)) { requiredPartitions.add(partition); } } } if(!requiredPartitions.isEmpty()){ tableService.addPartitions(partitionConfig.tableName(),requiredPartitions, true); } return null; }
public static void logDebug(String message, Context context) { if (context != null && InternalLogLevel >= LEVEL_DEBUG) { context.getLogger().log("DEBUG " + message); } }
public static void logError(String message, Context context) { if (context != null && InternalLogLevel >= LEVEL_ERROR) { context.getLogger().log("ERROR " + message); } }
/** * Empties the contents of the given bucket and optionally deletes the bucket * * @param s3 The S3 client object to use * @param bucketName The bucket to empty * @param deleteBucket Flag to determine whether to delete the bucket after emptying * @param context Lambda context object */ public static void emptyBucket(AmazonS3 s3, String bucketName, boolean deleteBucket, Context context) { if (s3.doesBucketExistV2(bucketName)) { logDebug("Emptying bucket '" + bucketName + "'...", context); VersionListing versionListing = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName)); while (true) { for (S3VersionSummary vs : versionListing.getVersionSummaries()) { s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId()); } if (versionListing.isTruncated()) { logDebug("Fetching next batch of versions for bucket '" + bucketName + "'", context); versionListing = s3.listNextBatchOfVersions(versionListing); } else { break; } } logInfo("Successfully emptied bucket '" + bucketName + "'", context); if (deleteBucket) { logDebug("Deleting bucket '" + bucketName + "'...", context); s3.deleteBucket(bucketName); logInfo("Successfully deleted bucket '" + bucketName + "'", context); } } else { logWarn("Bucket '" + bucketName + "' does not exist", context); } }
@Override protected final void afterHandle(EventActionRequest<T> request, Context context) throws Exception { try { afterAction(request, context); } finally { FunctionalUtils.toBiConsumer(loggerAfterHandle(), logger) .accept(request, context); } }
private void doHandleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws AuthenticationException, IOException, AuthorizationException { // Get json input String inputJson = getStringInput(inputStream); context.getLogger().log("inputJson:" + inputJson); // Parse JSON JSONObject json = new JSONObject(inputJson); String username = json.getString("username"); String token = json.getString("token"); context.getLogger().log("username:" + username + ", token:" + token); // Authorize Claims claims = lambdaAuthorizer.getClaims(username, token); // Generate credentials context.getLogger().log("providers:" + temporaryCredentialsProvider.getBucket() + " " + temporaryCredentialsProvider.getRegion()); FederatedUserCredentials temporaryCredentials = temporaryCredentialsProvider.getFederatedTokenFor(username); context.getLogger().log("temporary credentials generated:" + temporaryCredentials); // Write AWS credentials to file temporaryCredentials.saveTo(outputStream); // Write Configuration to file List<String> challengeIds = JWTTdlTokenUtils.getChallengeIds(claims); RunnerConfiguration.of(username, challengeIds).saveTo(outputStream); }
/** * Checks if the request body should be validated * <p> * A request body validation is performed if the input argument of * the method {@link AbstractRequestHandler#execute(Object, Context)} contains the * {@link Valid} annotation. * * @return should true if the input argument has the {@link Valid} annotation * @throws SecurityException * @throws NoSuchMethodException */ private boolean shouldValidade() throws NoSuchMethodException, SecurityException { Method method = getClass().getMethod(EXECUTE_METHOD, parameterizedInput, Context.class); Annotation[][] annotations = method.getParameterAnnotations(); Annotation[] firstArgAnnotations = Arrays.stream(annotations) .findFirst() .get(); return Arrays.stream(firstArgAnnotations) .anyMatch(a -> a instanceof Valid); }
@Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { initialize(); Object value = convertStream(input); Flux<?> flux = apply(extract(value)); mapper.writeValue(output, result(value, flux)); }
public Integer handleRequest(SNSEvent event, Context context) { try { // SNS Events could be possible more than one even if this looks a bit unusual for the deploy case. for (SNSEvent.SNSRecord record : event.getRecords()) { SNSEvent.SNS sns = record.getSNS(); // Check SNS header for event type. SNSEvent.MessageAttribute attr = sns.getMessageAttributes().get(X_GITHUB_EVENT); // Only watch pushes to master. if (EVENT_PUSH.equalsIgnoreCase(attr.getValue())) { PushPayload value = MAPPER.readValue(sns.getMessage(), PushPayload.class); if (config.isWatchedBranch(new Branch(value.getRef()))) { LOG.info(format("Processing '%s' on '%s': '%s'", attr.getValue(), value.getRef(), value.getHeadCommit().getId())); switch (worker.call()) { case SUCCESS: return HttpStatus.SC_OK; case FAILED: return HttpStatus.SC_BAD_REQUEST; } } // Different branch was found. else { LOG.info(format("Push received for: '%s'", value.getRef())); } } // Different event was found. else { LOG.info(format("Event was: '%s'", attr.getValue())); } } } catch (Exception e) { LOG.error(e.getMessage(), e); return HttpStatus.SC_INTERNAL_SERVER_ERROR; } return HttpStatus.SC_BAD_REQUEST; }
@Test public void shouldFailOnOtherEvent() throws Exception { // Given Context context = mock(Context.class); SNSEvent snsEvent = createSnsEvent("commit"); // When Integer response = uut.handleRequest(snsEvent, context); // Then assertThat(response, is(HttpStatus.SC_BAD_REQUEST)); verify(config, times(0)).isWatchedBranch(any()); verify(worker, times(0)).call(); }
@Override public String handleRequest(Object parameters, Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); // Construct an object to contain the recipient address. Destination destination = new Destination().withToAddresses(new String[] { System.getenv("EMAIL_RECIPIENT") }); // Create the subject and body of the message. Content subject = new Content().withData(EMAIL_SUBJECT); Content textBody = new Content().withData(parameters.toString()); Body body = new Body().withText(textBody); // Create a message with the specified subject and body. Message message = new Message().withSubject(subject).withBody(body); // Assemble the email. SendEmailRequest request = new SendEmailRequest().withSource(System.getenv("EMAIL_FROM")).withDestination(destination) .withMessage(message); // Send the email using the AWS SES Service AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendEmail(request); context.getLogger().log("Mail sent"); return "Message sent"; }
@Override public Parameters handleRequest(S3Event event, Context context) { context.getLogger() .log("Input Function [" + context.getFunctionName() + "], S3Event [" + event.toJson().toString() + "]"); Parameters parameters = new Parameters( event.getRecords().get(0).getS3().getBucket().getName(), event.getRecords().get(0).getS3().getObject().getKey()); AWSStepFunctions client = AWSStepFunctionsClientBuilder.defaultClient(); ObjectMapper jsonMapper = new ObjectMapper(); StartExecutionRequest request = new StartExecutionRequest(); request.setStateMachineArn(System.getenv("STEP_MACHINE_ARN")); try { request.setInput(jsonMapper.writeValueAsString(parameters)); } catch (JsonProcessingException e) { throw new AmazonServiceException("Error in ["+context.getFunctionName()+"]", e); } context.getLogger() .log("Step Function [" + request.getStateMachineArn() + "] will be called with [" + request.getInput() + "]"); StartExecutionResult result = client.startExecution(request); context.getLogger() .log("Output Function [" + context.getFunctionName() + "], Result [" + result.toString() + "]"); return parameters; }
@Override protected S3EventResult handleEvent(S3EventNotification event, Context context) { AwsEventRequest request = readEvent(event); S3EventResult result = new S3EventResult(); AwsEventResponse res = actionRouterHandle(request, context); if (res.isSuccessful()) { result.addSuccessItem(request); } else { logger.error("Failed processing S3Event", res.getCause()); result.addFailureItem(request); } return result; }