| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
AWS Serverless Java Container makes it easy to run your Spring, Spring Boot, Jersey, Struts 2, or Spark applications in AWS Lambda with Amazon API Gateway or an Application Load Balancer. The library defines a set of interfaces and abstract classes required to support other frameworks in the future. Serverless Java Container starts each framework acting as a Servlet container, such as Tomcat, and translates API Gateway proxy events into the request format accepted by the underlying framework, such as an HttpServletRequest or ContainerRequest. HTTP responses from the frameworks are translated in the object structure API Gateway expects as a return value from Lambda.
The primary purpose of the library is to act as a Servlet container; it receives events object from Lambda and translates them to a request object for the framework. Similarly, it translates responses from the framework into valid return values for API Gateway.
The current version of AWS Serverless Java Container (2.x) is compatible with Jakarta EE platform 9 and higher (jakarta.* namespace). For applications using an older version of the Jakarta EE platform (javax.* namespace) it's required to use version 1.x of Serverless Java Container library.
The framework can be used with both POJO and stream handlers. For applications that leverage context values from custom authorizers, we recommend using a stream handler: The framework uses Jackson's @JsonAnySetter/Getter annotations to extract custom values from the authorizer context, the serializer included in AWS Lambda does not process annotated fields. In all our samples, we use the RequestStreamHandler interface and the proxyStream method of the Serverless Java Container library. With a POJO-based handler, you can use the proxy method of the handler object directly.
This is the basic example of a stream handler using Jersey:
public class StreamLambdaHandler implements RequestStreamHandler {
private static final ResourceConfig jerseyApplication = new ResourceConfig()
.packages("com.amazonaws.serverless.sample.jersey")
.register(JacksonFeature.class);
private static final JerseyLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler
= JerseyLambdaContainerHandler.getAwsProxyHandler(jerseyApplication);
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
handler.proxyStream(inputStream, outputStream, context);
}
}If you are using Lambda Function URLs or HTTP APIs instead of Rest APIs with Amazon API Gateway and plan to use version 2.0 of the integration event, you can call the getHttpApiV2ProxyHandler method to get a pre-configured ContainerHandler object:
private static final JerseyLambdaContainerHandler<HttpApiV2ProxyRequest, AwsProxyResponse> handler
= JerseyLambdaContainerHandler.getHttpApiV2ProxyHandler(jerseyApplication);In the example above, and all other sample applications, the main LambdaContainerHandler is declared in a static block as a class member. This is because static variables are initialized with the runtime (the JVM) as AWS Lambda launches our function, which gives us better performance.
The samples directory in the repository contains a sample pet store application for each framework. All of the samples include a stream handler as well as a SAM template for deployment.
The samples folder includes a simple pet store application implemented with each framework supported by this library. With each application, we have included a Maven pom.xml file, Gradle build file, and a SAM template.The easiest way to deploy the samples it to use the SAM CLI.
Before proceeding, make sure you have Gradle or Maven installed, the AWS CLI installed and configured with a set of AWS credentials, and the SAM CLI.
$ cd ~/library-folder/samples/springboot3/pet-store$ sam build$ sam deploy --guided...
---------------------------------------------------------------------------------------------------------
OutputKey-Description OutputValue
---------------------------------------------------------------------------------------------------------
PetStoreApi - URL for application https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/pets
---------------------------------------------------------------------------------------------------------
$ curl https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/petsSince version 1.4 of the framework, we have added the ability to initialize the frameworks in a background thread to avoid exceeding Lambda's cold start maximum time (10 seconds). As of version 2.0.0 this will be automatically in for on-demand mode (not for provisioned concurrency and SnapStart). To initialize the framework asynchronously for older versions, you can use the HandlerBuilder object with an AsyncInitializationWrapper:
SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler =
new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
.defaultProxy()
.asyncInit()
.springBootApplication(SlowTestApplication.class)
.buildAndInitialize();Starting the handler in this way will cause this library to create a background thread and call the initialize method of the framework in the background thread. If the 10 seconds timeout expires and the framework has not completed its initialization, this library returns control to Lambda and continue waiting inside the handler method when it receives the first event. By default, the library will wait for up to 20 seconds for the initialization to complete - 10 seconds of Lambda init time + 10 seconds inside the handler method. You can customize this timeout using the ContainerConfig object.
// set the initialization timeout to 29 seconds
LambdaContainerHandler.getContainerConfig().setInitializationTimeout(29_000);
SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler =
new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
.defaultProxy()
.asyncInit()
.springBootApplication(SlowTestApplication.class)
.buildAndInitialize();To use an AWS Lambda function created with serverless-java-container as a target for an Application Load Balancer (ALB), you must first enable multi-value headers support.
API Gateway supports authentication and authorization using IAM credentials (SigV4) or bearer tokens via Cognito User Pools or custom authorizers.
The library contains a default implementation of the SecurityContextWriter that supports API Gateway's proxy integration. The generated security context uses the API Gateway $context object to establish the request security context.
The Principal object is populated for all requests in the SecurityContext and can be retrieved from the ServletRequests and Jersey's ContainerRequest or injected in an object.
With Jersey, you can inject the SecurityContext using the @Context annotation.
@Path("/test") @GET
public String testPrincipal(@Context SecurityContext securityContext) {
Principal principal = securityContext.getUserPrincipal();
// the possible values for the authentication scheme are
// 1. CUSTOM_AUTHORIZER
// 2. COGNITO_USER_POOL
// 3. AWS_IAM
// These are defined as constants in the AwsProxySecurityContext object
String authScheme = securityContext.getAuthenticationScheme();
}For servlet-based implementations such as Spring and Spark, you can retrieve the principal from the HttpServletRequest object using the getUserPrincipal() method.
@RequestMapping(path = "/test", method=RequestMethod.GET)
public String test(HttpServletRequest request, ServletResponse response) {
Principal principal = request.getUserPrincipal();
return "Hello, " + principal.getName() + "!";
}Behind the scenes, for requests authorized via IAM credentials, all information about the user is available in the ApiGatewayRequestContext object and its identity property. Custom authorizer data, including any custom values, are stored in the ApiGatewayAuthorizerContext object.
Context information that are not part of the standard HTTP request, such as the Cognito identity or custom authorizer claims, are stored in request attributes by the RequestReader object. From your implementations, you can access this data using the getAttribute(String) method of the request object. The example below extracts the API Gateway context property from the request and reads the "picture" value from the custom authorizer claims.
get("/pets", (req, res) -> {
ApiGatewayRequestContext ctx = (ApiGatewayRequestContext)req.raw().getAttribute(API_GATEWAY_CONTEXT_PROPERTY);
ApiGatewayAuthorizerContext authCtx = ctx.getAuthorizer();
String picture = authCtx.getContextValue("picture");
});You can register Filter implementations by implementing a StartupsHandler as defined in the AwsLambdaServletContainerHandler class. The onStartup methods receives a reference to the current ServletContext.
handler.onStartup(c -> {
FilterRegistration.Dynamic registration = c.addFilter("CustomHeaderFilter", CustomHeaderFilter.class);
// update the registration to map to a path
registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
// servlet name mappings are disabled and will throw an exception
});When using this framework with a custom domain name, you need to explicitly enable the domain name in the ContainerConfig object.
LambdaContainerHandler.getContainerConfig().addCustomDomain("api.myserver.com");Unless the custom domain name is explicitly enabled, the getServerName() method of the HttpServletRequest object will return the default API Gateway domain.
The Serverless Java Container library can log requests to the function's CloudWatch log stream. To format the log for each request, the library relies on implementations of the LogFormatter interface. By default, we include an implementation of the interface that generates Apache combined logs. The object is instantiated automatically by the servlet implementation of the library. You can override the formatter to create your own custom log lines using the setLogFormatter( ) method of the ContainerHandler class of your choice.
The library includes a ContainerConfig object. When the handler object is initialized, the config is set to its default values. You can change the configuration by retrieving the singleton config from the LambdaContainerHandler object.
LambdaContainerHandler.getContainerConfig().setUseStageAsServletContext(true);The configuration variables are:
To translate incoming events, the library declares two abstract classes: The RequestReader and the ResponseWriter. Both these classes use generic types for the input and output objects. Implementing libraries, such as the Jersey one, extend these classes to support their types.
Out of the box, the library supports proxy integration events.
| Back | FazBrowse Home | New Git URL |