com.amazonaws.serverless.proxy.model.AwsProxyRequest Java Examples

The following examples show how to use com.amazonaws.serverless.proxy.model.AwsProxyRequest. 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: AwsProxyHttpServletRequestReaderTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Test
public void readRequest_contentCharset_setsDefaultCharsetWhenNotSpecified() {
    String requestCharset = "application/json";
    AwsProxyRequest request = new AwsProxyRequestBuilder(ENCODED_REQUEST_PATH, "GET").header(HttpHeaders.CONTENT_TYPE, requestCharset).build();
    try {
        HttpServletRequest servletRequest = reader.readRequest(request, null, null, ContainerConfig.defaultConfig());
        assertNotNull(servletRequest);
        assertNotNull(servletRequest.getHeader(HttpHeaders.CONTENT_TYPE));
        String contentAndCharset = requestCharset + "; charset=" + LambdaContainerHandler.getContainerConfig().getDefaultContentCharset();
        assertEquals(contentAndCharset, servletRequest.getHeader(HttpHeaders.CONTENT_TYPE));
        assertEquals(LambdaContainerHandler.getContainerConfig().getDefaultContentCharset(), servletRequest.getCharacterEncoding());
    } catch (InvalidRequestEventException e) {
        e.printStackTrace();
        fail("Could not read request");
    }
}
 
Example #2
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void alb_basicRequest_expectSuccess() {
    AwsProxyRequest request = getRequestBuilder("/echo/headers", "GET")
            .json()
            .header(CUSTOM_HEADER_KEY, CUSTOM_HEADER_VALUE)
            .alb()
            .build();

    AwsProxyResponse output = handler.proxy(request, lambdaContext);
    assertEquals(200, output.getStatusCode());
    assertEquals("application/json", output.getMultiValueHeaders().getFirst("Content-Type"));
    assertNotNull(output.getStatusDescription());
    System.out.println(output.getStatusDescription());

    validateMapResponseModel(output);
}
 
Example #3
Source File: ApacheCombinedServletLogFormatterTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  proxyRequest = new AwsProxyRequest();
  Clock fixedClock = Clock.fixed(Instant.ofEpochSecond(665888523L), ZoneId.of("UTC"));
  mockServletRequest = mock(HttpServletRequest.class);
  context = new AwsProxyRequestContext();
  context.setIdentity(new ApiGatewayRequestIdentity());
  when(mockServletRequest.getAttribute(eq(API_GATEWAY_CONTEXT_PROPERTY)))
      .thenReturn(context);
  when(mockServletRequest.getMethod())
      .thenReturn("GET");
  mockServletResponse = mock(HttpServletResponse.class);
  proxyRequest.setRequestContext(context);

  sut = new ApacheCombinedServletLogFormatter(fixedClock);
}
 
Example #4
Source File: MicronautRequestReader.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
private static String getPathNoBase(AwsProxyRequest request) {
    if (request.getResource() == null || "".equals(request.getResource())) {
        return request.getPath();
    }

    if (request.getPathParameters() == null || request.getPathParameters().isEmpty()) {
        return request.getResource();
    }

    String path = request.getResource();
    for (Map.Entry<String, String> variable : request.getPathParameters().entrySet()) {
        path = path.replaceAll("\\{" + Pattern.quote(variable.getKey()) + "\\+?}", variable.getValue());
    }

    return path;
}
 
Example #5
Source File: SparkLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of an SparkLambdaContainerHandler initialized to work with <code>AwsProxyRequest</code>
 * and <code>AwsProxyResponse</code> objects.
 *
 * @return a new instance of <code>SparkLambdaContainerHandler</code>
 *
 * @throws ContainerInitializationException Throws this exception if we fail to initialize the Spark container.
 * This could be caused by the introspection used to insert the library as the default embedded container
 */
public static SparkLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler()
        throws ContainerInitializationException {
    SparkLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> newHandler = new SparkLambdaContainerHandler<>(AwsProxyRequest.class,
                                                                                     AwsProxyResponse.class,
                                                                                     new AwsProxyHttpServletRequestReader(),
                                                                                     new AwsProxyHttpServletResponseWriter(),
                                                                                     new AwsProxySecurityContextWriter(),
                                                                                     new AwsProxyExceptionHandler(),
                                                                                     new LambdaEmbeddedServerFactory());

    // For Spark we cannot call initialize here. It needs to be called manually after the routes are set
    //newHandler.initialize();

    return newHandler;
}
 
Example #6
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void errors_unknownRoute_expect404() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    AwsProxyRequest request = getRequestBuilder("/echo/test33", "GET").build();

    AwsProxyResponse output = handler.proxy(request, lambdaContext);
    assertEquals(404, output.getStatusCode());
}
 
Example #7
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void error_statusCode_methodNotAllowed() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    AwsProxyRequest request = getRequestBuilder("/echo/status-code", "POST")
            .json()
            .queryString("status", "201")
            .build();

    AwsProxyResponse output = handler.proxy(request, lambdaContext);
    assertEquals(405, output.getStatusCode());
}
 
Example #8
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void automaticStripBasePath_route_shouldRouteCorrectly() {
    handler.stripBasePath("/custompath");
    try {
        AwsProxyRequest request = getRequestBuilder("/custompath/echo/status-code", "GET")
                .json()
                .queryString("status", "201")
                .build();
        request.setResource("/{proxy+}");
        request.setPathParameters(Collections.singletonMap("proxy", "echo/status-code"));

        AwsProxyResponse output = handler.proxy(request, lambdaContext);
        assertEquals(201, output.getStatusCode());
    } finally {
        handler.stripBasePath("");
    }
}
 
Example #9
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void automaticStripBasePath_route_shouldRouteCorrectly2() {
    handler.stripBasePath("/custompath");
    try {
        AwsProxyRequest request = getRequestBuilder("/custompath/echo/status-code", "GET")
                .json()
                .queryString("status", "201")
                .build();

        request.setResource("/{controller}/{action}");

        Map<String, String> pathParameters = new HashMap<>();
        pathParameters.put("controller", "echo");
        pathParameters.put("action", "status-code");
        request.setPathParameters(pathParameters);

        AwsProxyResponse output = handler.proxy(request, lambdaContext);
        assertEquals(201, output.getStatusCode());
    } finally {
        handler.stripBasePath("");
    }
}
 
Example #10
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void stripBasePath_route_shouldReturn404() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    handler.stripBasePath("/custom");
    try {
        AwsProxyRequest request = getRequestBuilder("/custompath/echo/status-code", "GET")
                .json()
                .queryString("status", "201")
                .build();
        AwsProxyResponse output = handler.proxy(request, lambdaContext);
        assertEquals(404, output.getStatusCode());
    } finally {

        handler.stripBasePath("");
    }
}
 
Example #11
Source File: LambdaHandler.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context)
{
     if (!isinitialized) {
         isinitialized = true;
         try {
         	XmlWebApplicationContext wc = new XmlWebApplicationContext();
         	wc.setConfigLocation("classpath:/staticAppContext.xml");
             handler = SpringLambdaContainerHandler.getAwsProxyHandler(wc);
         } catch (ContainerInitializationException e) {
             e.printStackTrace();
             return null;
         }
     }
     AwsProxyResponse res = handler.proxy(awsProxyRequest, context);
     return res;
}
 
Example #12
Source File: AwsProxyHttpServletRequestFormTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Test
public void postForm_getParts_parsing() {
    try {
        AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/form", "POST")
                                               .header(MULTIPART_FORM_DATA.getContentType().getName(), MULTIPART_FORM_DATA.getContentType().getValue())
                                               //.header(formData.getContentEncoding().getName(), formData.getContentEncoding().getValue())
                                               .body(IOUtils.toString(MULTIPART_FORM_DATA.getContent()))
                                               .build();

        HttpServletRequest request = new AwsProxyHttpServletRequest(proxyRequest, null, null);
        assertNotNull(request.getParts());
        assertEquals(2, request.getParts().size());
        assertEquals(PART_VALUE_1, IOUtils.toString(request.getPart(PART_KEY_1).getInputStream()));
        assertEquals(PART_VALUE_2, IOUtils.toString(request.getPart(PART_KEY_2).getInputStream()));
    } catch (IOException | ServletException e) {
        fail(e.getMessage());
    }
}
 
Example #13
Source File: LambdaHandler.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
public LambdaHandler(String reqType) {
    type = reqType;
    try {
        switch (type) {
            case "API_GW":
            case "ALB":
                handler = new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
                        .defaultProxy()
                        .initializationWrapper(new InitializationWrapper())
                        .springBootApplication(WebFluxTestApplication.class)
                        .buildAndInitialize();
                break;
            case "HTTP_API":
                httpApiHandler = new SpringBootProxyHandlerBuilder<HttpApiV2ProxyRequest>()
                        .defaultHttpApiV2Proxy()
                        .initializationWrapper(new InitializationWrapper())
                        .springBootApplication(WebFluxTestApplication.class)
                        .buildAndInitialize();
                break;
        }
    } catch (ContainerInitializationException e) {
        e.printStackTrace();
    }
}
 
Example #14
Source File: AwsProxyHttpServletRequest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
private List<String> getHeaderValues(String key) {
    // special cases for referer and user agent headers
    List<String> values = new ArrayList<>();

    if (request.getRequestSource() == AwsProxyRequest.RequestSource.API_GATEWAY) {
        if ("referer".equals(key.toLowerCase(Locale.ENGLISH))) {
            values.add(request.getRequestContext().getIdentity().getCaller());
            return values;
        }
        if ("user-agent".equals(key.toLowerCase(Locale.ENGLISH))) {
            values.add(request.getRequestContext().getIdentity().getUserAgent());
            return values;
        }
    }

    if (request.getMultiValueHeaders() == null) {
        return null;
    }

    return request.getMultiValueHeaders().get(key);
}
 
Example #15
Source File: AwsProxyHttpServletRequestReader.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Override
public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config)
        throws InvalidRequestEventException {
    // Expect the HTTP method and context to be populated. If they are not, we are handling an
    // unsupported event type.
    if (request.getHttpMethod() == null || request.getHttpMethod().equals("") || request.getRequestContext() == null) {
        throw new InvalidRequestEventException(INVALID_REQUEST_ERROR);
    }

    request.setPath(stripBasePath(request.getPath(), config));
    if (request.getMultiValueHeaders() != null && request.getMultiValueHeaders().getFirst(HttpHeaders.CONTENT_TYPE) != null) {
        String contentType = request.getMultiValueHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        // put single as we always expect to have one and only one content type in a request.
        request.getMultiValueHeaders().putSingle(HttpHeaders.CONTENT_TYPE, getContentTypeWithCharset(contentType, config));
    }
    AwsProxyHttpServletRequest servletRequest = new AwsProxyHttpServletRequest(request, lambdaContext, securityContext, config);
    servletRequest.setServletContext(servletContext);
    servletRequest.setAttribute(API_GATEWAY_CONTEXT_PROPERTY, request.getRequestContext());
    servletRequest.setAttribute(API_GATEWAY_STAGE_VARS_PROPERTY, request.getStageVariables());
    servletRequest.setAttribute(API_GATEWAY_EVENT_PROPERTY, request);
    servletRequest.setAttribute(ALB_CONTEXT_PROPERTY, request.getRequestContext().getElb());
    servletRequest.setAttribute(LAMBDA_CONTEXT_PROPERTY, lambdaContext);
    servletRequest.setAttribute(JAX_SECURITY_CONTEXT_PROPERTY, securityContext);

    return servletRequest;
}
 
Example #16
Source File: AwsProxyRequestDispatcher.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the destination path in the given request. Uses the <code>AwsProxyRequest.setPath</code> method which
 * is in turn read by the <code>HttpServletRequest</code> implementation.
 * @param req The request object to be modified
 * @param destinationPath The new path for the request
 * @throws IllegalStateException If the given request object does not include the <code>API_GATEWAY_EVENT_PROPERTY</code>
 *  attribute or the value for the attribute is not of the correct type: <code>AwsProxyRequest</code>.
 */
void setRequestPath(ServletRequest req, final String destinationPath) {
    if (req instanceof AwsProxyHttpServletRequest) {
        ((AwsProxyHttpServletRequest) req).getAwsProxyRequest().setPath(dispatchTo);
        return;
    }
    if (req instanceof AwsHttpApiV2ProxyHttpServletRequest) {
        ((AwsHttpApiV2ProxyHttpServletRequest) req).getRequest().setRawPath(destinationPath);
        return;
    }

    log.debug("Request is not an proxy request generated by this library, attempting to extract the proxy event type from the request attributes");
    if (req.getAttribute(API_GATEWAY_EVENT_PROPERTY) != null && req.getAttribute(API_GATEWAY_EVENT_PROPERTY) instanceof AwsProxyRequest) {
        ((AwsProxyRequest)req.getAttribute(API_GATEWAY_EVENT_PROPERTY)).setPath(dispatchTo);
        return;
    }
    if (req.getAttribute(HTTP_API_EVENT_PROPERTY) != null && req.getAttribute(HTTP_API_EVENT_PROPERTY) instanceof HttpApiV2ProxyRequest) {
        ((HttpApiV2ProxyRequest)req.getAttribute(HTTP_API_EVENT_PROPERTY)).setRawPath(destinationPath);
        return;
    }

    throw new IllegalStateException("Could not set new target path for the given ServletRequest object");
}
 
Example #17
Source File: AwsProxyRequestDispatcherTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Test
public void include_addsToResponse_appendsCorrectly() throws InvalidRequestEventException, IOException {
    final String firstPart = "first";
    final String secondPart = "second";
    AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build();

    AwsProxyResponse resp = mockLambdaHandler((AwsProxyHttpServletRequest req, AwsHttpServletResponse res)-> {
        if (req.getAttribute("cnt") == null) {
            res.getOutputStream().write(firstPart.getBytes());
            req.setAttribute("cnt", 1);
            req.getRequestDispatcher("/includer").include(req, res);
            res.setStatus(200);
            res.flushBuffer();
        } else {
            res.getOutputStream().write(secondPart.getBytes());
        }
    }).proxy(proxyRequest, new MockLambdaContext());
    assertEquals(firstPart + secondPart, resp.getBody());
}
 
Example #18
Source File: AwsProxyRequestDispatcherTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Test
public void include_appendsNewHeader_cannotAppendNewHeaders() throws InvalidRequestEventException, IOException {
    final String firstPart = "first";
    final String secondPart = "second";
    final String headerKey = "X-Custom-Header";
    AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build();

    AwsProxyResponse resp = mockLambdaHandler((AwsProxyHttpServletRequest req, AwsHttpServletResponse res)-> {
        if (req.getAttribute("cnt") == null) {
            res.getOutputStream().write(firstPart.getBytes());
            req.setAttribute("cnt", 1);
            req.getRequestDispatcher("/includer").include(req, res);
            res.setStatus(200);
            res.flushBuffer();
        } else {
            res.getOutputStream().write(secondPart.getBytes());
            res.addHeader(headerKey, "value");
        }
    }).proxy(proxyRequest, new MockLambdaContext());
    assertEquals(firstPart + secondPart, resp.getBody());
    assertFalse(resp.getMultiValueHeaders().containsKey(headerKey));
}
 
Example #19
Source File: SparkLambdaContainerHandlerTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void filters_onStartupMethod_executeFilters() {

    SparkLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler = null;
    try {
         handler = SparkLambdaContainerHandler.getAwsProxyHandler();
    } catch (ContainerInitializationException e) {
        e.printStackTrace();
        fail();
    }

    handler.onStartup(c -> {
        if (c == null) {
            fail();
        }
        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
    });

    configureRoutes();

    Spark.awaitInitialization();

    AwsProxyRequest req = new AwsProxyRequestBuilder().method("GET").path("/header-filter").build();
    AwsProxyResponse response = handler.proxy(req, new MockLambdaContext());

    assertNotNull(response);
    assertEquals(200, response.getStatusCode());
    assertTrue(response.getMultiValueHeaders().containsKey(CustomHeaderFilter.HEADER_NAME));
    assertEquals(CustomHeaderFilter.HEADER_VALUE, response.getMultiValueHeaders().getFirst(CustomHeaderFilter.HEADER_NAME));
    assertEquals(RESPONSE_BODY_TEXT, response.getBody());

}
 
Example #20
Source File: Struts2LambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
public static Struts2LambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler() {
    return new Struts2LambdaContainerHandler(
            AwsProxyRequest.class,
            AwsProxyResponse.class,
            new AwsProxyHttpServletRequestReader(),
            new AwsProxyHttpServletResponseWriter(),
            new AwsProxySecurityContextWriter(),
            new AwsProxyExceptionHandler());
}
 
Example #21
Source File: LambdaHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
public LambdaHandler() throws ContainerInitializationException {
    long startTime = Instant.now().toEpochMilli();
    handler = new SpringProxyHandlerBuilder<AwsProxyRequest>()
            .defaultProxy()
            .asyncInit()
            .configurationClasses(SlowAppConfig.class)
            .buildAndInitialize();
    constructorTime = Instant.now().toEpochMilli() - startTime;
}
 
Example #22
Source File: HelloWorldSparkTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void multiCookie_setCookieOnResponse_singleHeaderWithMultipleValues() {
    AwsProxyRequest req = getRequestBuilder().method("GET").path("/multi-cookie").build();
    AwsProxyResponse response = handler.proxy(req, new MockLambdaContext());

    assertEquals(200, response.getStatusCode());
    assertTrue(response.getMultiValueHeaders().containsKey(HttpHeaders.SET_COOKIE));

    assertEquals(2, response.getMultiValueHeaders().get(HttpHeaders.SET_COOKIE).size());
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_NAME + "=" + COOKIE_VALUE));
    assertTrue(response.getMultiValueHeaders().get(HttpHeaders.SET_COOKIE).get(1).contains(COOKIE_NAME + "2=" + COOKIE_VALUE + "2"));
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_DOMAIN));
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_PATH));
}
 
Example #23
Source File: AwsProxyHttpServletRequestReaderTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void readRequest_validEventEmptyPath_expectException() {
    try {
        AwsProxyRequest req = new AwsProxyRequestBuilder(null, "GET").build();
        HttpServletRequest servletReq = reader.readRequest(req, null, null, ContainerConfig.defaultConfig());
        assertNotNull(servletReq);
    } catch (InvalidRequestEventException e) {
        e.printStackTrace();
        fail("Could not read a request with a null path");
    }
}
 
Example #24
Source File: HelloWorldSparkTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void rootResource_basicRequest_expectSuccess() {
    AwsProxyRequest req = getRequestBuilder().method("GET").path("/").build();
    AwsProxyResponse response = handler.proxy(req, new MockLambdaContext());

    assertEquals(200, response.getStatusCode());
    assertTrue(response.getMultiValueHeaders().containsKey(CUSTOM_HEADER_KEY));
    assertEquals(CUSTOM_HEADER_VALUE, response.getMultiValueHeaders().getFirst(CUSTOM_HEADER_KEY));
    assertEquals(BODY_TEXT_RESPONSE, response.getBody());
}
 
Example #25
Source File: SpringBootLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default SpringLambdaContainerHandler initialized with the `AwsProxyRequest` and `AwsProxyResponse` objects and the given Spring profiles
 * @param springBootInitializer {@code SpringBootServletInitializer} class
 * @param profiles A list of Spring profiles to activate
 * @return An initialized instance of the `SpringLambdaContainerHandler`
 * @throws ContainerInitializationException If an error occurs while initializing the Spring framework
 */
public static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler(Class<?> springBootInitializer, String... profiles)
        throws ContainerInitializationException {
    return new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
            .defaultProxy()
            .initializationWrapper(new InitializationWrapper())
            .springBootApplication(springBootInitializer)
            .profiles(profiles)
            .buildAndInitialize();
}
 
Example #26
Source File: SpringLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default SpringLambdaContainerHandler initialized with the `AwsProxyRequest` and `AwsProxyResponse` objects
 * @param config A set of classes annotated with the Spring @Configuration annotation
 * @return An initialized instance of the `SpringLambdaContainerHandler`
 * @throws ContainerInitializationException When the Spring framework fails to start.
 */
public static SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler(Class<?>... config) throws ContainerInitializationException {
    return new SpringProxyHandlerBuilder<AwsProxyRequest>()
            .defaultProxy()
            .initializationWrapper(new InitializationWrapper())
            .configurationClasses(config)
            .buildAndInitialize();
}
 
Example #27
Source File: LambdaHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
public LambdaHandler() {
    try {
        long startTime = Instant.now().toEpochMilli();
        System.out.println("startCall: " + startTime);
        handler = new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
                .defaultProxy()
                .asyncInit()
                .springBootApplication(SlowTestApplication.class)
                .buildAndInitialize();
        constructorTime = Instant.now().toEpochMilli() - startTime;
    } catch (ContainerInitializationException e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: AwsProxyHttpServletRequestReaderTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void readRequest_nullHeaders_expectSuccess() {
    AwsProxyRequest req = new AwsProxyRequestBuilder("/path", "GET").build();
    req.setMultiValueHeaders(null);
    try {
        HttpServletRequest servletReq = reader.readRequest(req, null, null, ContainerConfig.defaultConfig());
        String headerValue = servletReq.getHeader(HttpHeaders.CONTENT_TYPE);
        assertNull(headerValue);
    } catch (InvalidRequestEventException e) {
        e.printStackTrace();
        fail("Failed to read request with null headers");
    }
}
 
Example #29
Source File: HelloWorldSparkTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void addCookie_setCookieOnResponse_validCustomCookie() {
    AwsProxyRequest req = getRequestBuilder().method("GET").path("/cookie").build();
    AwsProxyResponse response = handler.proxy(req, new MockLambdaContext());

    assertEquals(200, response.getStatusCode());
    assertTrue(response.getMultiValueHeaders().containsKey(HttpHeaders.SET_COOKIE));
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_NAME + "=" + COOKIE_VALUE));
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_DOMAIN));
    assertTrue(response.getMultiValueHeaders().getFirst(HttpHeaders.SET_COOKIE).contains(COOKIE_PATH));
}
 
Example #30
Source File: AwsProxyHttpServletRequestReaderTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void readRequest_invalidEventEmptyContext_expectException() {
    try {
        AwsProxyRequest req = new AwsProxyRequestBuilder("/path", "GET").build();
        req.setRequestContext(null);
        reader.readRequest(req, null, null, ContainerConfig.defaultConfig());
        fail("Expected InvalidRequestEventException");
    } catch (InvalidRequestEventException e) {
        assertEquals(AwsProxyHttpServletRequestReader.INVALID_REQUEST_ERROR, e.getMessage());
    }
}