com.amazonaws.services.lambda.runtime.Context Java Examples
The following examples show how to use
com.amazonaws.services.lambda.runtime.Context.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringBootLambdaContainerHandler.java From aws-serverless-java-container with Apache License 2.0 | 6 votes |
@Override protected void handleRequest(HttpServletRequest containerRequest, AwsHttpServletResponse containerResponse, Context lambdaContext) throws Exception { // this method of the AwsLambdaServletContainerHandler sets the servlet context Timer.start("SPRINGBOOT2_HANDLE_REQUEST"); // wire up the application context on the first invocation if (!initialized) { initialize(); } // process filters & invoke servlet Servlet reqServlet = ((AwsServletContext)getServletContext()).getServletForPath(containerRequest.getPathInfo()); if (AwsHttpServletRequest.class.isAssignableFrom(containerRequest.getClass())) { ((AwsHttpServletRequest)containerRequest).setServletContext(getServletContext()); ((AwsHttpServletRequest)containerRequest).setResponse(containerResponse); } doFilter(containerRequest, containerResponse, reqServlet); Timer.stop("SPRINGBOOT2_HANDLE_REQUEST"); }
Example #2
Source File: TerraformRequestHandler.java From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 | 6 votes |
private void handle(Context context, CustomResourceRequest request) { EnvConfig envConfig = EnvConfig.fromEnvironmentVariables(); String externalId = StsFacade.getExternalId(context); AWSCredentialsProvider launchRoleCredentials = getLaunchRoleCredentials(externalId, request); // Since Terraform doesn't handle rollback, we no-op for rollback cases. Simply post success. CloudFormationFacade cfnFacade = getCfnFacade(request, launchRoleCredentials); if (request.getRequestType() == RequestType.UPDATE && cfnFacade.isStackInUpdateRollback(request.getStackId())) { ResponsePoster.postSuccess(request); return; } verifyWhitelistedTerraformArtifactSource(request.getResourceProperties(), envConfig); CommandSender commandSender = new CommandSender(request, envConfig, externalId); commandSender.sendCommand(); }
Example #3
Source File: LambdaWrapperTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@Test public void invokeHandler_withDefaultInjection_returnsInProgress() throws IOException { final TestModel model = new TestModel(); model.setProperty1("abc"); model.setProperty2(123); wrapper.setTransformResponse(resourceHandlerRequest); // respond with immediate success to avoid callback invocation final ProgressEvent<TestModel, TestContext> pe = ProgressEvent.<TestModel, TestContext>builder() .status(OperationStatus.IN_PROGRESS).resourceModel(model).build(); wrapper.setInvokeHandlerResponse(pe); try (final InputStream in = loadRequestStream("create.request.json"); final OutputStream out = new ByteArrayOutputStream()) { final Context context = getLambdaContext(); wrapper.handleRequest(in, out, context); // verify output response verifyHandlerResponse(out, ProgressEvent.<TestModel, TestContext>builder().status(OperationStatus.IN_PROGRESS) .resourceModel(TestModel.builder().property1("abc").property2(123).build()).build()); } }
Example #4
Source File: LambdaWrapperTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@Test public void invokeHandler_withNullInputStream_returnsFailureResponse() throws IOException { try (final OutputStream out = new ByteArrayOutputStream()) { final Context context = getLambdaContext(); try { wrapper.handleRequest(null, out, context); } catch (final Error e) { // ignore so we can perform verifications } // verify output response verifyHandlerResponse(out, ProgressEvent.<TestModel, TestContext>builder().errorCode(HandlerErrorCode.InternalFailure) .status(OperationStatus.FAILED).message("No request object received").build()); } }
Example #5
Source File: LambdaTest.java From github-bucket with ISC License | 6 votes |
@Test public void shouldFailOnWrongWorkerCall() throws Exception { // Given Context context = mock(Context.class); SNSEvent snsEvent = createSnsEvent("push"); when(config.isWatchedBranch(new Branch("changes"))).thenReturn(true); when(worker.call()).thenReturn(Status.FAILED); // When Integer response = uut.handleRequest(snsEvent, context); // Then assertThat(response, is(HttpStatus.SC_BAD_REQUEST)); verify(config, times(1)).isWatchedBranch(new Branch("changes")); verify(worker, times(1)).call(); }
Example #6
Source File: ServiceRequestHandler.java From jrestless with Apache License 2.0 | 6 votes |
@Override protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest, JRestlessContainerRequest containerRequest, ServiceRequestAndLambdaContext requestAndLambdaContext) { ServiceRequest request = requestAndLambdaContext.getServiceRequest(); Context lambdaContext = requestAndLambdaContext.getLambdaContext(); actualContainerRequest.setRequestScopedInitializer(locator -> { Ref<ServiceRequest> serviceRequestRef = locator .<Ref<ServiceRequest>>getInstance(SERVICE_REQUEST_TYPE); if (serviceRequestRef != null) { serviceRequestRef.set(request); } else { LOG.error("ServiceFeature has not been registered. ServiceRequest injection won't work."); } Ref<Context> contextRef = locator .<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE); if (contextRef != null) { contextRef.set(lambdaContext); } else { LOG.error("AwsFeature has not been registered. Context injection won't work."); } }); }
Example #7
Source File: MyLambdaHandler.java From Serverless-Programming-Cookbook with MIT License | 6 votes |
/** * Handle request. * * @param request - input to lambda handler * @param context - context object * @return greeting text */ public IAMOperationResponse handleRequest(final IAMOperationRequest request, final Context context) { context.getLogger().log("Requested operation = " + request.getOperation() + ". User name = " + request.getUserName()); switch (request.getOperation()) { case "CREATE" : return this.service.createUser(request.getUserName()); case "CHECK" : return this.service.checkUser(request.getUserName()); case "DELETE" : return this.service.deleteUser(request.getUserName()); default: return new IAMOperationResponse(null, "Invalid operation " + request.getOperation() + ". Allowed: CREATE, CHECK, DELETE."); } }
Example #8
Source File: Handler.java From Building-Serverless-Architectures with MIT License | 6 votes |
@Override public AuthorizationOutput handleRequest(AuthorizationInput input, Context context) { final String authenticationToken = input.getAuthorizationToken(); final PolicyDocument policyDocument = new PolicyDocument(); PolicyStatement.Effect policyEffect = PolicyStatement.Effect.ALLOW; String principalId = null; try { User authenticatedUser = userService.getUserByToken(authenticationToken); principalId = String.valueOf(authenticatedUser.getId()); } catch (UserNotFoundException userNotFoundException) { policyEffect = PolicyStatement.Effect.DENY; LOGGER.info("User authentication failed for token " + authenticationToken); } policyDocument.withPolicyStatement(new PolicyStatement("execute-api:Invoke", policyEffect, input.getMethodArn())); return new AuthorizationOutput(principalId, policyDocument); }
Example #9
Source File: AbstractLambdaContainerHandler.java From micronaut-aws with Apache License 2.0 | 6 votes |
/** * Proxies requests to the underlying container given the incoming Lambda request. This method returns a populated * return object for the Lambda function. * * @param request The incoming Lambda request * @param context The execution context for the Lambda function * @return A valid response type */ public ResponseType proxy(RequestType request, Context context) { lambdaContext = context; try { SecurityContext securityContext = securityContextWriter.writeSecurityContext(request, context); CountDownLatch latch = new CountDownLatch(1); ContainerRequestType containerRequest = requestReader.readRequest(request, securityContext, context, config); ContainerResponseType containerResponse = getContainerResponse(containerRequest, latch); handleRequest(containerRequest, containerResponse, context); latch.await(); if (logFormatter != null) { log.info(SecurityUtils.crlf(logFormatter.format(containerRequest, containerResponse, securityContext))); } return responseWriter.writeResponse(containerResponse, context); } catch (Exception e) { log.error("Error while handling request", e); return exceptionHandler.handle(e); } }
Example #10
Source File: JerseyAwsProxyTest.java From aws-serverless-java-container with Apache License 2.0 | 6 votes |
private AwsProxyResponse executeRequest(AwsProxyRequestBuilder requestBuilder, Context lambdaContext) { switch (type) { case "API_GW": if (handler == null) { handler = JerseyLambdaContainerHandler.getAwsProxyHandler(app); } return handler.proxy(requestBuilder.build(), lambdaContext); case "ALB": if (handler == null) { handler = JerseyLambdaContainerHandler.getAwsProxyHandler(app); } return handler.proxy(requestBuilder.alb().build(), lambdaContext); case "HTTP_API": if (httpApiHandler == null) { httpApiHandler = JerseyLambdaContainerHandler.getHttpApiV2ProxyHandler(httpApiApp); } return httpApiHandler.proxy(requestBuilder.toHttpApiV2Request(), lambdaContext); default: throw new RuntimeException("Unknown request type: " + type); } }
Example #11
Source File: LambdaWrapperTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@Test public void invokeHandler_invalidModelTypes_causesSchemaValidationFailure() throws IOException { // use actual validator to verify behaviour final WrapperOverride wrapper = new WrapperOverride(providerLoggingCredentialsProvider, platformEventsLogger, providerEventsLogger, providerMetricsPublisher, new Validator() { }, httpClient); wrapper.setTransformResponse(resourceHandlerRequest); try (final InputStream in = loadRequestStream("create.request.with-invalid-model-types.json"); final OutputStream out = new ByteArrayOutputStream()) { final Context context = getLambdaContext(); wrapper.handleRequest(in, out, context); // verify output response verifyHandlerResponse(out, ProgressEvent.<TestModel, TestContext>builder().errorCode(HandlerErrorCode.InvalidRequest) .status(OperationStatus.FAILED) .message("Model validation failed (#/property1: expected type: String, found: JSONArray)").build()); } }
Example #12
Source File: MetadataHandler.java From aws-athena-query-federation with Apache License 2.0 | 6 votes |
public final void handleRequest(InputStream inputStream, OutputStream outputStream, final Context context) throws IOException { try (BlockAllocator allocator = new BlockAllocatorImpl()) { ObjectMapper objectMapper = VersionedObjectMapperFactory.create(allocator); try (FederationRequest rawReq = objectMapper.readValue(inputStream, FederationRequest.class)) { if (rawReq instanceof PingRequest) { try (PingResponse response = doPing((PingRequest) rawReq)) { assertNotNull(response); objectMapper.writeValue(outputStream, response); } return; } if (!(rawReq instanceof MetadataRequest)) { throw new RuntimeException("Expected a MetadataRequest but found " + rawReq.getClass()); } doHandleRequest(allocator, objectMapper, (MetadataRequest) rawReq, outputStream); } catch (Exception ex) { logger.warn("handleRequest: Completed with an exception.", ex); throw (ex instanceof RuntimeException) ? (RuntimeException) ex : new RuntimeException(ex); } } }
Example #13
Source File: LambdaTest.java From github-bucket with ISC License | 6 votes |
@Test public void shouldFailOnOtherBranch() throws Exception { // Given Context context = mock(Context.class); SNSEvent snsEvent = createSnsEvent("push"); when(config.isWatchedBranch(new Branch("changes"))).thenReturn(false); // When Integer response = uut.handleRequest(snsEvent, context); // Then assertThat(response, is(HttpStatus.SC_BAD_REQUEST)); verify(config, times(1)).isWatchedBranch(any()); verify(worker, times(0)).call(); }
Example #14
Source File: SnsRequestHandler.java From jrestless with Apache License 2.0 | 6 votes |
@Override protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest, JRestlessContainerRequest containerRequest, SnsRecordAndLambdaContext snsRecordAndContext) { SNSRecord snsRecord = snsRecordAndContext.getSnsRecord(); Context lambdaContext = snsRecordAndContext.getLambdaContext(); actualContainerRequest.setRequestScopedInitializer(locator -> { Ref<SNSRecord> snsRecordRef = locator.<Ref<SNSRecord>>getInstance(SNS_RECORD_TYPE); if (snsRecordRef != null) { snsRecordRef.set(snsRecord); } else { LOG.error("SnsFeature has not been registered. SNSRecord injection won't work."); } Ref<Context> contextRef = locator .<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE); if (contextRef != null) { contextRef.set(lambdaContext); } else { LOG.error("AwsFeature has not been registered. Context injection won't work."); } }); }
Example #15
Source File: HandlerTest.java From djl-demo with Apache License 2.0 | 6 votes |
@Test public void invokeTest() throws IOException { Context context = new MockContext(); Handler handler = new Handler(); Request request = new Request(); request.setInputImageUrl("https://djl-ai.s3.amazonaws.com/resources/images/kitten.jpg"); Gson gson = new Gson(); byte[] buf = gson.toJson(request).getBytes(StandardCharsets.UTF_8); InputStream is = new ByteArrayInputStream(buf); ByteArrayOutputStream os = new ByteArrayOutputStream(); handler.handleRequest(is, os, context); String result = os.toString(StandardCharsets.UTF_8.name()); Type type = new TypeToken<List<Classifications.Classification>>() {}.getType(); List<Classifications.Classification> list = gson.fromJson(result, type); Assert.assertNotNull(list); Assert.assertEquals(list.get(0).getClassName(), "n02123045 tabby, tabby cat"); }
Example #16
Source File: FullControlLambda.java From blog-tutorials with MIT License | 5 votes |
@Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Person person = objectMapper.readValue(input, Person.class); System.out.println("Parsed person: " + person); person.setId(UUID.randomUUID().toString()); objectMapper.writeValue(output, person); }
Example #17
Source File: LambdaHandler.java From aws-serverless-java-container with Apache License 2.0 | 5 votes |
@Override public AwsProxyResponse handleRequest(AwsProxyRequestBuilder awsProxyRequest, Context context) { switch (type) { case "API_GW": return handler.proxy(awsProxyRequest.build(), context); case "ALB": return handler.proxy(awsProxyRequest.alb().build(), context); case "HTTP_API": return httpApiHandler.proxy(awsProxyRequest.toHttpApiV2Request(), context); default: throw new RuntimeException("Unknown request type: " + type); } }
Example #18
Source File: LambdaContext.java From bender with Apache License 2.0 | 5 votes |
public LambdaContext(Context ctx) { this.ctx = ctx; if (ctx == null) { return; } this.ctxMap.put("functionVersion", ctx.getFunctionVersion()); this.ctxMap.put("functionName", ctx.getFunctionName()); this.ctxMap.put("awsRequestId", ctx.getAwsRequestId()); this.ctxMap.put("invokedFunctionArn", ctx.getInvokedFunctionArn()); this.ctxMap.put("logGroupName", ctx.getLogGroupName()); this.ctxMap.put("logStreamName", ctx.getLogStreamName()); ClientContext cc = ctx.getClientContext(); if (cc != null) { this.ctxMap.put("clientContextCustom", cc.getCustom().toString()); this.ctxMap.put("clientContextEnvironment", cc.getEnvironment().toString()); Client c = cc.getClient(); if (c != null) { this.ctxMap.put("clientContextClientInstallationId", c.getInstallationId()); this.ctxMap.put("clientContextClientAppPackageName", c.getAppPackageName()); this.ctxMap.put("clientContextClientAppTitle", c.getAppTitle()); this.ctxMap.put("clientContextClientAppVersionCode", c.getAppVersionCode()); this.ctxMap.put("clientContextClientAppVersionName", c.getAppVersionName()); } } this.ctxMap.values().removeIf(Objects::isNull); }
Example #19
Source File: DynamodbHandler.java From bender with Apache License 2.0 | 5 votes |
public void handler(DynamodbEvent event, Context context) throws HandlerException { if (!initialized) { init(context); } this.recordIterator = new DynamodbEventIterator( new LambdaContext(context), event.getRecords()); DynamodbStreamRecord firstRecord = event.getRecords().get(0); this.source = SourceUtils.getSource(firstRecord.getEventSourceARN(), sources); super.process(context); }
Example #20
Source File: Main.java From apigateway-generic-java-sdk with Apache License 2.0 | 5 votes |
public void hello(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { ProxyResponse resp = new ProxyResponse("200", "{\"message\" : \"Hello World\"}"); String responseString = new ObjectMapper(new JsonFactory()).writeValueAsString(resp); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(responseString); writer.close(); }
Example #21
Source File: LambdaSnsPublishHandler.java From Serverless-Programming-Cookbook with MIT License | 5 votes |
/** * Handle request. * * @param request - input to lambda handler. * @param context - context object. * @return Message id of the published message. */ public String handleRequest(final Request request, final Context context) { context.getLogger().log("Received Request: " + request); final PublishResult result; try { PublishRequest publishRequest = new PublishRequest(request.getTopicArn(), request.getMessage()); result = snsClient.publish(publishRequest); } catch (Exception e) { return "Exception occurred: " + e.getMessage(); } return "Message Id: " + result.getMessageId(); }
Example #22
Source File: LambdaFormFunctionHandlerTest.java From aws-lambda-java-example with Apache License 2.0 | 5 votes |
private Context createContext() { TestContext ctx = new TestContext(); // TODO: customize your context here if needed. ctx.setFunctionName("LambdaForm"); return ctx; }
Example #23
Source File: LambdaSnsEventHandler.java From Serverless-Programming-Cookbook with MIT License | 5 votes |
/** * Handle request. * * @param snsEvent - SQS Event passed as input to lambda handler * @param context - context object * @return true if success, else false. */ public Boolean handleRequest(final SNSEvent snsEvent, final Context context) { context.getLogger().log("Received SQS event: " + snsEvent); final SnsService snsService = new SnsServiceImpl(this.sqsClient); // It is a good practice to prefix environment variables with a project specific prefix. // E.g. SPC is a prefix that denote Serverless Programming Cookbook. return snsService.processEvent(snsEvent, System.getenv("SPC_OUTPUT_QUEUE_URL"), context.getLogger()); }
Example #24
Source File: FunctionInvoker.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { Message requestMessage = this.generateMessage(input, context); Message<byte[]> responseMessage = (Message<byte[]>) this.function.apply(requestMessage); byte[] responseBytes = responseMessage.getPayload(); if (requestMessage.getHeaders().containsKey("httpMethod") || requestMessage.getPayload() instanceof APIGatewayProxyRequestEvent) { // API Gateway Map<String, Object> response = new HashMap<String, Object>(); response.put("isBase64Encoded", false); MessageHeaders headers = responseMessage.getHeaders(); int statusCode = headers.containsKey("statusCode") ? (int) headers.get("statusCode") : 200; response.put("statusCode", statusCode); if (isKinesis(requestMessage)) { HttpStatus httpStatus = HttpStatus.valueOf(statusCode); response.put("statusDescription", httpStatus.toString()); } String body = new String(responseMessage.getPayload(), StandardCharsets.UTF_8).replaceAll("\"", ""); response.put("body", body); Map<String, String> responseHeaders = new HashMap<>(); headers.keySet().forEach(key -> responseHeaders.put(key, headers.get(key).toString())); response.put("headers", responseHeaders); responseBytes = mapper.writeValueAsBytes(response); } StreamUtils.copy(responseBytes, output); }
Example #25
Source File: InvokeTest.java From aws-doc-sdk-examples with Apache License 2.0 | 5 votes |
@Test void invokeTest() { AWSXRay.beginSegment("blank-java-test"); String path = "src/test/resources/event.json"; String eventString = loadJsonFile(path); SQSEvent event = gson.fromJson(eventString, SQSEvent.class); Context context = new TestContext(); String requestId = context.getAwsRequestId(); Handler handler = new Handler(); String result = handler.handleRequest(event, context); assertTrue(result.contains("totalCodeSize")); AWSXRay.endSegment(); }
Example #26
Source File: SnsLambdaHandler.java From Building-Serverless-Architectures with MIT License | 5 votes |
@Override public Void handleRequest(SNSEvent input, Context context) { input.getRecords().forEach(snsMessage -> { try { I deserializedPayload = objectMapper.readValue(snsMessage.getSNS().getMessage(), getJsonType()); handleSnsRequest(deserializedPayload, context); } catch (IOException anyException) { LOGGER.error("JSON could not be deserialized", anyException); } }); return null; }
Example #27
Source File: MyLambdaHandler.java From Serverless-Programming-Cookbook with MIT License | 5 votes |
/** * Handle request. * * @param request - input to lambda handler * @param context - context object * @return greeting text */ public Response handleRequest(final Request request, final Context context) { context.getLogger().log("Creating table " + request.getTableName()); final String version = System.getenv("API_VERSION"); if (version != null && version.equals("V2")) { service = new DynamoDBServiceImpl2(); } else { service = new DynamoDBServiceImpl1(); } return service.createTable(request); }
Example #28
Source File: Handler.java From Building-Serverless-Architectures with MIT License | 5 votes |
@Override public TestOutput handleRequest(TestInput input, Context context) { LOGGER.debug("Input from Lambda event " + input.value); TestOutput testOutput = new TestOutput(); testOutput.value = input.value; return testOutput; }
Example #29
Source File: HelloHandler.java From Cloud-Native-Applications-in-Java with MIT License | 5 votes |
@Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) { String who = "World"; if ( request.getPathParameters() != null ) { String name = request.getPathParameters().get("name"); if ( name != null && !"".equals(name.trim()) ) { who = name; } } return new APIGatewayProxyResponseEvent().withStatusCode(HttpURLConnection.HTTP_OK).withBody(String.format("Hello %s!", who)); }
Example #30
Source File: CheckPublicAcessService.java From pacbot with Apache License 2.0 | 5 votes |
/** * The method will get triggered from Lambda Function with following * parameters * * @param s3bucketURL * * ************* Following are the Rule Parameters********* <br> * <br> * * s3bucketURL : URL of the s3 bucket<br> * <br> * * @param context * null * */ @Override public String handleRequest(String s3bucketURL, Context context) { String publicAccess = null; try { URL s3BucketURL = new URL(s3bucketURL); HttpURLConnection connection = (HttpURLConnection) s3BucketURL .openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code == 200) { publicAccess = "YES"; } else { publicAccess = "NO"; } } catch (MalformedURLException malexp) { logger.error("error", malexp); } catch (IOException ioex) { logger.error("IOException", ioex); } return publicAccess; }