com.amazonaws.http.HttpMethodName Java Examples

The following examples show how to use com.amazonaws.http.HttpMethodName. 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: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_non2xx_exception() throws IOException {
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");

    try {
        client.execute(
                new GenericApiGatewayRequestBuilder()
                        .withBody(new ByteArrayInputStream("test request".getBytes()))
                        .withHttpMethod(HttpMethodName.POST)
                        .withHeaders(headers)
                        .withResourcePath("/test/orders").build());

        Assert.fail("Expected exception");
    } catch (GenericApiGatewayException e) {
        assertEquals("Wrong status code", 404, e.getStatusCode());
        assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
    }
}
 
Example #2
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_noApiKey_noCreds() throws IOException {
    client = new GenericApiGatewayClientBuilder()
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withClientConfiguration(new ClientConfiguration())
            .withHttpClient(new AmazonHttpClient(new ClientConfiguration(), mockClient, null))
            .build();

    GenericApiGatewayResponse response = client.execute(
            new GenericApiGatewayRequestBuilder()
                    .withBody(new ByteArrayInputStream("test request".getBytes()))
                    .withHttpMethod(HttpMethodName.POST)
                    .withResourcePath("/test/orders").build());

    assertEquals("Wrong response body", "test payload", response.getBody());
    assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode());

    Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>(
                    x -> (x.getMethod().equals("POST")
                            && x.getFirstHeader("x-api-key") == null
                            && x.getFirstHeader("Authorization") == null
                            && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders")))),
            any(HttpContext.class));
}
 
Example #3
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_happy_parameters() throws IOException {
    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");
    Map<String,List<String>> parameters = new HashMap<>();
    parameters.put("MyParam", Arrays.asList("MyParamValue"));
    GenericApiGatewayResponse response = client.execute(
        new GenericApiGatewayRequestBuilder()
            .withBody(new ByteArrayInputStream("test request".getBytes()))
            .withHttpMethod(HttpMethodName.POST)
            .withHeaders(headers)
            .withParameters(parameters)
            .withResourcePath("/test/orders").build());

    assertEquals("Wrong response body", "test payload", response.getBody());
    assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode());

    Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>(
                                                     x -> (x.getMethod().equals("POST")
                                                         && x.getFirstHeader("Account-Id").getValue().equals("fubar")
                                                         && x.getFirstHeader("x-api-key").getValue().equals("12345")
                                                         && x.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                                                         && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders?MyParam=MyParamValue")))),
                                                 any(HttpContext.class));
}
 
Example #4
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_happy() throws IOException {
    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");
    GenericApiGatewayResponse response = client.execute(
            new GenericApiGatewayRequestBuilder()
                    .withBody(new ByteArrayInputStream("test request".getBytes()))
                    .withHttpMethod(HttpMethodName.POST)
                    .withHeaders(headers)
                    .withResourcePath("/test/orders").build());

    assertEquals("Wrong response body", "test payload", response.getBody());
    assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode());

    Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>(
                    x -> (x.getMethod().equals("POST")
                            && x.getFirstHeader("Account-Id").getValue().equals("fubar")
                            && x.getFirstHeader("x-api-key").getValue().equals("12345")
                            && x.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                            && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders")))),
            any(HttpContext.class));
}
 
Example #5
Source File: AwsPostTestCase.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * AwsPost can perform the original {@link AwsHttpRequest}
 * @throws IOException If something goes wrong while reading
 *  the request's content.
 */
@Test
public void performsRequest() throws IOException {
    String jsonContent = "{\"testContent\":\"fake\"}";
    AwsPost<String> awsp = new AwsPost<>(
        new AwsHttpRequest.FakeAwsHttpRequest(),
        new ByteArrayInputStream(jsonContent.getBytes())
    );
    assertTrue(awsp.perform().equals("performed fake request"));
    assertTrue(awsp.request().getHttpMethod().equals(HttpMethodName.POST));

    StringWriter writer = new StringWriter();
    IOUtils.copy(awsp.request().getContent(), writer, "UTF-8");
    String content = writer.toString();

    assertTrue(content.equals(jsonContent));
}
 
Example #6
Source File: DeleteLexiconPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<DeleteLexiconRequest> marshall(DeleteLexiconRequest deleteLexiconRequest) {
    if (deleteLexiconRequest == null) {
        throw new AmazonClientException("null deleteLexiconRequest passed to marshall(...)");
    }

    Request<DeleteLexiconRequest> request = new DefaultRequest<DeleteLexiconRequest>(deleteLexiconRequest,
            IvonaSpeechCloudClient.SERVICE_NAME);
    request.setHttpMethod(HttpMethodName.POST);
    setRequestPayload(request, deleteLexiconRequest);
    request.setResourcePath(RESOURCE_PATH);

    return request;
}
 
Example #7
Source File: CreateSpeechPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<CreateSpeechRequest> marshall(CreateSpeechRequest createSpeechRequest) {

        if (createSpeechRequest == null) {
            throw new AmazonClientException("null createSpeechRequest passed to marshall(...)");
        }

        Request<CreateSpeechRequest> request = new DefaultRequest<CreateSpeechRequest>(createSpeechRequest,
                IvonaSpeechCloudClient.SERVICE_NAME);
        request.setHttpMethod(HttpMethodName.POST);
        setRequestPayload(request, createSpeechRequest);
        request.setResourcePath(RESOURCE_PATH);

        return request;
    }
 
Example #8
Source File: AwsIamAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String getSignedHeaders(AwsIamAuthenticationOptions options, AWSCredentials credentials) {

		Map<String, String> headers = createIamRequestHeaders(options);

		AWS4Signer signer = new AWS4Signer();

		DefaultRequest<String> request = new DefaultRequest<>("sts");

		request.setContent(new ByteArrayInputStream(REQUEST_BODY.getBytes()));
		request.setHeaders(headers);
		request.setHttpMethod(HttpMethodName.POST);
		request.setEndpoint(options.getEndpointUri());

		signer.setServiceName(request.getServiceName());
		signer.sign(request, credentials);

		Map<String, Object> map = new LinkedHashMap<>();

		for (Entry<String, String> entry : request.getHeaders().entrySet()) {
			map.put(entry.getKey(), Collections.singletonList(entry.getValue()));
		}

		try {
			return OBJECT_MAPPER.writeValueAsString(map);
		}
		catch (JsonProcessingException e) {
			throw new IllegalStateException("Cannot serialize headers to JSON", e);
		}
	}
 
Example #9
Source File: ListVoicesPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<ListVoicesRequest> marshall(ListVoicesRequest listVoicesRequest) {

        if (listVoicesRequest == null) {
            throw new AmazonClientException("null listVoicesRequest passed to marshall(...)");
        }

        Request<ListVoicesRequest> request = new DefaultRequest<ListVoicesRequest>(listVoicesRequest,
                IvonaSpeechCloudClient.SERVICE_NAME);
        request.setHttpMethod(HttpMethodName.POST);
        request.setResourcePath(RESOURCE_PATH);
        setRequestPayload(request, listVoicesRequest);
        return request;
    }
 
Example #10
Source File: ListVoicesGetRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<ListVoicesRequest> marshall(ListVoicesRequest listVoicesRequest) {

        if (listVoicesRequest == null) {
            throw new AmazonClientException("null listVoicesRequest passed to marshall(...)");
        }

        Request<ListVoicesRequest> request = new DefaultRequest<ListVoicesRequest>(listVoicesRequest,
                IvonaSpeechCloudClient.SERVICE_NAME);
        request.setHttpMethod(HttpMethodName.GET);
        request.setResourcePath(RESOURCE_PATH);

        setRequestParameters(request, listVoicesRequest);

        return request;
    }
 
Example #11
Source File: PutLexiconPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<PutLexiconRequest> marshall(PutLexiconRequest putLexiconRequest) {
    if (putLexiconRequest == null) {
        throw new AmazonClientException("null putLexiconRequest passed to marshall(...)");
    }

    Request<PutLexiconRequest> request = new DefaultRequest<PutLexiconRequest>(putLexiconRequest,
            IvonaSpeechCloudClient.SERVICE_NAME);
    request.setHttpMethod(HttpMethodName.POST);
    setRequestPayload(request, putLexiconRequest);
    request.setResourcePath(RESOURCE_PATH);

    return request;
}
 
Example #12
Source File: AwsHttpHeadersTestCase.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * AwsHttpHeaders can perform the original {@link AwsHttpRequest}
 */
@Test
public void performsRequest() {
    final AwsHttpHeaders<String> awsh = new AwsHttpHeaders<>(
        new AwsHttpRequest.FakeAwsHttpRequest(),
        new HashMap<String, String>()
    );        
    MatcherAssert.assertThat(awsh.perform(),
        Matchers.equalTo("performed fake request")
    );
    MatcherAssert.assertThat(awsh.request().getHttpMethod(),
        Matchers.equalTo(HttpMethodName.POST)
    );
}
 
Example #13
Source File: AwsHeadTestCase.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * AwsHead can perform the original {@link AwsHttpRequest}
 */
@Test
public void performsRequest() {
	AwsHead<String> awsh = new AwsHead<>(
           new AwsHttpRequest.FakeAwsHttpRequest()
       );
       assertTrue(awsh.perform().equals("performed fake request"));
       assertTrue(awsh.request().getHttpMethod().equals(HttpMethodName.HEAD));
   }
 
Example #14
Source File: AwsDeleteTestCase.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * AwsDelete can perform the original {@link AwsHttpRequest}
 */
@Test
public void performsRequest() {
       AwsDelete<String> awsd = new AwsDelete<>(
           new AwsHttpRequest.FakeAwsHttpRequest()
       );
       assertTrue(awsd.perform().equals("performed fake request"));
       assertTrue(awsd.request().getHttpMethod().equals(HttpMethodName.DELETE));
   }
 
Example #15
Source File: SkdSignerUtil.java    From aws-signing-request-interceptor with MIT License 5 votes vote down vote up
static public String getExpectedAuthorizationHeader(Request request) throws Exception {
    // create the signable request
    DefaultRequest signableRequest = new DefaultRequest(null, request.getServiceName());
    signableRequest.setEndpoint(new URI("http://" + request.getHost()));
    signableRequest.setResourcePath(request.getUri());
    signableRequest.setHttpMethod(HttpMethodName.valueOf(request.getHttpMethod()));
    signableRequest.setContent(new StringInputStream(request.getBody()));
    if (request.getHeaders() != null)
        signableRequest.setHeaders(request.getHeaders());
    if (request.getQueryParams() != null) {
        Map<String, List<String>> convertedQueryParams = new HashMap<>();
        for (String paramName : request.getQueryParams().keySet()) {
            convertedQueryParams.put(paramName, new ArrayList<>(request.getQueryParams().get(paramName)));
        }
        signableRequest.setParameters(convertedQueryParams);
    }

    /*
       Init the signer class

       Note: Double uri encoding is off simple before the signature does not match the expected signature of the test cases
       if it is enabled.  This was a bit unexpected because AWSElasticsearchClient (AWS SDK Class) enabled double URI encoding
       in the signer by default.  I can only assume that double encoding is needed when accessing the service but not when accessing
       elasticsearch.
     */
    AWS4Signer aws4Signer = new AWS4Signer(false);
    aws4Signer.setServiceName(request.getServiceName());
    aws4Signer.setRegionName(request.getRegion());
    Method method1 = AWS4Signer.class.getDeclaredMethod("setOverrideDate", Date.class);
    method1.setAccessible(true);
    method1.invoke(aws4Signer, request.getDate());
    aws4Signer.sign(signableRequest, request.getCredentialsProvider().getCredentials());

    return (String) signableRequest.getHeaders().get("Authorization");
}
 
Example #16
Source File: GetLexiconPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<GetLexiconRequest> marshall(GetLexiconRequest getLexiconRequest) {
    if (getLexiconRequest == null) {
        throw new AmazonClientException("null getLexiconRequest passed to marshall(...)");
    }

    Request<GetLexiconRequest> request = new DefaultRequest<GetLexiconRequest>(getLexiconRequest,
            IvonaSpeechCloudClient.SERVICE_NAME);
    request.setHttpMethod(HttpMethodName.POST);
    setRequestPayload(request, getLexiconRequest);
    request.setResourcePath(RESOURCE_PATH);

    return request;
}
 
Example #17
Source File: ListLexiconsPostRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<ListLexiconsRequest> marshall(ListLexiconsRequest listLexiconsRequest) {
    if (listLexiconsRequest == null) {
        throw new AmazonClientException("null listLexiconsRequest passed to marshall(...)");
    }

    Request<ListLexiconsRequest> request = new DefaultRequest<ListLexiconsRequest>(listLexiconsRequest,
            IvonaSpeechCloudClient.SERVICE_NAME);
    request.setHttpMethod(HttpMethodName.POST);
    setRequestPayload(request, listLexiconsRequest);
    request.setResourcePath(RESOURCE_PATH);

    return request;
}
 
Example #18
Source File: CreateSpeechGetRequestMarshaller.java    From ivona-speechcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Request<CreateSpeechRequest> marshall(CreateSpeechRequest createSpeechRequest) {
    if (createSpeechRequest == null) {
        throw new AmazonClientException("null createSpeechRequest passed to marshall(...)");
    }

    Request<CreateSpeechRequest> request = new DefaultRequest<CreateSpeechRequest>(createSpeechRequest,
            IvonaSpeechCloudClient.SERVICE_NAME);
    setRequestParameters(request, createSpeechRequest);
    request.setHttpMethod(HttpMethodName.GET);
    request.setResourcePath(RESOURCE_PATH);

    return request;
}
 
Example #19
Source File: GenericApiGatewayRequest.java    From nifi with Apache License 2.0 5 votes vote down vote up
public GenericApiGatewayRequest(HttpMethodName httpMethod, String resourcePath,
                                InputStream body, Map<String, String> headers,
                                Map<String, List<String>> parameters) {
    this.httpMethod = httpMethod;
    this.resourcePath = resourcePath;
    this.body = body;
    this.headers = headers;
    this.parameters = parameters;
}
 
Example #20
Source File: GenericApiGatewayClient.java    From apigateway-generic-java-sdk with Apache License 2.0 5 votes vote down vote up
private GenericApiGatewayResponse execute(HttpMethodName method, String resourcePath, Map<String, String> headers, Map<String,List<String>> parameters, InputStream content) {
    final ExecutionContext executionContext = buildExecutionContext();

    DefaultRequest request = new DefaultRequest(API_GATEWAY_SERVICE_NAME);
    request.setHttpMethod(method);
    request.setContent(content);
    request.setEndpoint(this.endpoint);
    request.setResourcePath(resourcePath);
    request.setHeaders(buildRequestHeaders(headers, apiKey));
    if (parameters != null) {
        request.setParameters(parameters);
    }
    return this.client.execute(request, responseHandler, errorResponseHandler, executionContext).getAwsResponse();
}
 
Example #21
Source File: GenericApiGatewayRequest.java    From apigateway-generic-java-sdk with Apache License 2.0 5 votes vote down vote up
public GenericApiGatewayRequest(HttpMethodName httpMethod, String resourcePath,
                                InputStream body, Map<String, String> headers,
                                Map<String, List<String>> parameters) {
    this.httpMethod = httpMethod;
    this.resourcePath = resourcePath;
    this.body = body;
    this.headers = headers;
    this.parameters = parameters;
}
 
Example #22
Source File: Main.java    From apigateway-generic-java-sdk with Apache License 2.0 5 votes vote down vote up
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    String apiIntputStream = new Scanner(inputStream).useDelimiter("\\A").next();
    JsonNode rootNode = (new ObjectMapper(new JsonFactory())).readTree(apiIntputStream);
    String myApiId = rootNode.path("requestContext").path("apiId").asText();
    if (myApiId.isEmpty()) { myApiId = "TODO"; } // Not called from API Gateway

    final GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withCredentials(new EnvironmentVariableCredentialsProvider())
            .withEndpoint("https://" + myApiId + ".execute-api.us-west-2.amazonaws.com") // your API ID
            .withRegion(Region.getRegion(Regions.fromName("us-west-2")))
            .build();

    GenericApiGatewayResponse apiResponse;
    ProxyResponse resp;
    try {
        apiResponse = client.execute(  // throws exception for non-2xx response
                new GenericApiGatewayRequestBuilder()
                        .withHttpMethod(HttpMethodName.GET)
                        .withResourcePath("/Prod/hello").build());

        System.out.println("Response: " + apiResponse.getBody());
        System.out.println("Status: " + apiResponse.getHttpResponse().getStatusCode());

        resp = new ProxyResponse("200", apiResponse.getBody());

    } catch (GenericApiGatewayException e) {
        System.out.println("Client threw exception " + e);
        resp = new ProxyResponse("400", e.getMessage());
    }

    String responseString = new ObjectMapper(new JsonFactory()).writeValueAsString(resp);
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseString);
    writer.close();
}
 
Example #23
Source File: GenericApiGatewayClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
private GenericApiGatewayResponse execute(HttpMethodName method, String resourcePath, Map<String, String> headers, Map<String,List<String>> parameters, InputStream content) {
    final ExecutionContext executionContext = buildExecutionContext();

    DefaultRequest request = new DefaultRequest(API_GATEWAY_SERVICE_NAME);
    request.setHttpMethod(method);
    request.setContent(content);
    request.setEndpoint(this.endpoint);
    request.setResourcePath(resourcePath);
    request.setHeaders(buildRequestHeaders(headers, apiKey));
    if (parameters != null) {
        request.setParameters(parameters);
    }
    return this.client.execute(request, responseHandler, errorResponseHandler, executionContext).getAwsResponse();
}
 
Example #24
Source File: KinesisVideoAWS4Signer.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
public SimpleSignableRequest(final HttpClient httpClient) {
    super("kinesisvideo");
    try {
        setHttpMethod(HttpMethodName.fromValue(httpClient.getMethod().name()));
        setEndpoint(new URI(httpClient.getUri().getScheme() + "://" + httpClient.getUri().getHost()));
        setResourcePath(httpClient.getUri().getPath());
        setHeaders(httpClient.getHeaders());
        setContent(httpClient.getContent());
    } catch (final Throwable e) {
        throw new RuntimeException("Exception while creating signable request ! ", e);
    }
}
 
Example #25
Source File: AbstractAWSGatewayApiProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected GenericApiGatewayRequest configureRequest(final ProcessContext context,
                                                    final ProcessSession session,
                                                    final String resourcePath,
                                                    final FlowFile requestFlowFile) {
    String method = trimToEmpty(
            context.getProperty(PROP_METHOD).evaluateAttributeExpressions(requestFlowFile)
                    .getValue()).toUpperCase();
    HttpMethodName methodName = HttpMethodName.fromValue(method);
    return configureRequest(context, session, resourcePath,requestFlowFile, methodName);
}
 
Example #26
Source File: GettingStarted.java    From getting-started with MIT License 5 votes vote down vote up
private static Request createRequest(final HttpMethodName httpMethodName, final String path) {
  final Request request = new DefaultRequest(AWS_SERVICE);
  request.setHttpMethod(httpMethodName);
  request.setEndpoint(URI.create(OPENBANKING_ENDPOINT));
  request.setResourcePath(path);
  request.addHeader("Accept", "application/json");
  request.addHeader("Content-type", "application/json");
  request.addHeader(API_KEY_HEADER, Config.get("API_KEY"));
  return request;
}
 
Example #27
Source File: GenericApiGatewayRequest.java    From nifi with Apache License 2.0 4 votes vote down vote up
public HttpMethodName getHttpMethod() {
    return httpMethod;
}
 
Example #28
Source File: GenericApiGatewayRequestBuilder.java    From nifi with Apache License 2.0 4 votes vote down vote up
public GenericApiGatewayRequestBuilder withHttpMethod(HttpMethodName name) {
    httpMethod = name;
    return this;
}
 
Example #29
Source File: AwsRequestSigner.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws IOException
{
    String method = request.getRequestLine().getMethod();

    URI uri = URI.create(request.getRequestLine().getUri());
    URIBuilder uriBuilder = new URIBuilder(uri);

    Map<String, List<String>> parameters = new TreeMap<>(CASE_INSENSITIVE_ORDER);
    for (NameValuePair parameter : uriBuilder.getQueryParams()) {
        parameters.computeIfAbsent(parameter.getName(), key -> new ArrayList<>())
                .add(parameter.getValue());
    }

    Map<String, String> headers = Arrays.stream(request.getAllHeaders())
            .collect(toImmutableMap(Header::getName, Header::getValue));

    InputStream content = null;
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
        if (enclosingRequest.getEntity() != null) {
            content = enclosingRequest.getEntity().getContent();
        }
    }

    DefaultRequest<?> awsRequest = new DefaultRequest<>(SERVICE_NAME);

    HttpHost host = (HttpHost) context.getAttribute(HTTP_TARGET_HOST);
    if (host != null) {
        awsRequest.setEndpoint(URI.create(host.toURI()));
    }
    awsRequest.setHttpMethod(HttpMethodName.fromValue(method));
    awsRequest.setResourcePath(uri.getRawPath());
    awsRequest.setContent(content);
    awsRequest.setParameters(parameters);
    awsRequest.setHeaders(headers);

    signer.sign(awsRequest, credentialsProvider.getCredentials());

    Header[] newHeaders = awsRequest.getHeaders().entrySet().stream()
            .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
            .toArray(Header[]::new);

    request.setHeaders(newHeaders);

    InputStream newContent = awsRequest.getContent();
    checkState(newContent == null || request instanceof HttpEntityEnclosingRequest);
    if (newContent != null) {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(newContent);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }
}
 
Example #30
Source File: AbstractAWSGatewayApiProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected GenericApiGatewayRequest configureRequest(final ProcessContext context,
                                                    final ProcessSession session,
                                                    final String resourcePath,
                                                    final FlowFile requestFlowFile,
                                                    final HttpMethodName methodName) {

    GenericApiGatewayRequestBuilder builder = new GenericApiGatewayRequestBuilder()
        .withResourcePath(resourcePath);
    final Map<String, List<String>> parameters = getParameters(context);
    builder = builder.withParameters(parameters);

    InputStream requestBody = null;
    switch (methodName) {
        case GET:
            builder = builder.withHttpMethod(HttpMethodName.GET);
            break;
        case POST:
            requestBody = getRequestBodyToSend(session, context, requestFlowFile);
            builder = builder.withHttpMethod(HttpMethodName.POST).withBody(requestBody);
            break;
        case PUT:
            requestBody = getRequestBodyToSend(session, context, requestFlowFile);
            builder = builder.withHttpMethod(HttpMethodName.PUT).withBody(requestBody);
            break;
        case PATCH:
            requestBody = getRequestBodyToSend(session, context, requestFlowFile);
            builder = builder.withHttpMethod(HttpMethodName.PATCH).withBody(requestBody);
            break;
        case HEAD:
            builder = builder.withHttpMethod(HttpMethodName.HEAD);
            break;
        case DELETE:
            builder = builder.withHttpMethod(HttpMethodName.DELETE);
            break;
        case OPTIONS:
            requestBody = getRequestBodyToSend(session, context, requestFlowFile);
            builder = builder.withHttpMethod(HttpMethodName.OPTIONS).withBody(requestBody);
            break;
    }

    builder = setHeaderProperties(context, builder, methodName, requestFlowFile);
    return builder.build();
}