com.amazonaws.DefaultRequest Java Examples

The following examples show how to use com.amazonaws.DefaultRequest. 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: TracingRequestHandlerTest.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void handlesAmazonServiceExceptions() {
  brave.Span braveSpan = tracing.tracer().nextSpan();
  AmazonServiceException exception = new ProvisionedThroughputExceededException("test");
  exception.setRequestId("abcd");

  DefaultRequest request = new DefaultRequest("test");
  request.addHandlerContext(new HandlerContextKey<>(brave.Span.class.getCanonicalName()), braveSpan);
  HandlerAfterAttemptContext context = HandlerAfterAttemptContext.builder()
      .withRequest(request)
      .withException(exception)
      .build();

  handler.afterAttempt(context);
  assertThat(spans).hasSize(1);
  MutableSpan reportedSpan = spans.get(0);
  assertThat(reportedSpan.traceId()).isEqualToIgnoringCase(braveSpan.context().traceIdString());
  assertThat(reportedSpan.error()).isEqualTo(exception);
  assertThat(reportedSpan.tags().get("aws.request_id")).isEqualToIgnoringCase("abcd");
}
 
Example #2
Source File: EsHttpRequest.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 * @param esEdp ElasticSearch URL.
 * @param uri REST path to the desired ElasticSearch endpoint.
 * @param respHandler Response handler.
 * @param errHandler Error handler.
 */
public EsHttpRequest(
	EsEndPoint esEdp,
    String uri,
    HttpResponseHandler<T> respHandler,
    HttpResponseHandler<AmazonServiceException> errHandler
){
	this.request = new DefaultRequest<Void>("es");
    String esEndpoint = esEdp.read();
    if(esEndpoint == null || esEndpoint.isEmpty()) {
        throw new IllegalStateException("ElasticSearch endpoint needs to be specified!");
    }
    if(esEndpoint.endsWith("/")) {
        esEndpoint += uri;
    } else {
        esEndpoint += "/" + uri;
    }
    this.request.setEndpoint(URI.create(esEndpoint));
    
    
    this.respHandler = respHandler;
    this.errHandler = errHandler;
}
 
Example #3
Source File: SpectatorRequestMetricCollectorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
private void execRequest(String endpoint, int status) {
  AWSRequestMetrics metrics = new AWSRequestMetricsFullSupport();
  metrics.addProperty(AWSRequestMetrics.Field.ServiceName, "AmazonCloudWatch");
  metrics.addProperty(AWSRequestMetrics.Field.ServiceEndpoint, endpoint);
  metrics.addProperty(AWSRequestMetrics.Field.StatusCode, "" + status);
  if (status == 503) {
    metrics.addProperty(AWSRequestMetrics.Field.AWSErrorCode, "Throttled");
  }
  String counterName = "BytesProcessed";
  String timerName = "ClientExecuteTime";
  metrics.setCounter(counterName, 12345);
  metrics.getTimingInfo().addSubMeasurement(timerName, TimingInfo.unmodifiableTimingInfo(100000L, 200000L));

  Request<?> req = new DefaultRequest(new ListMetricsRequest(), "AmazonCloudWatch");
  req.setAWSRequestMetrics(metrics);
  req.setEndpoint(URI.create(endpoint));

  HttpResponse hr = new HttpResponse(req, new HttpPost(endpoint));
  hr.setStatusCode(status);
  Response<?> resp = new Response<>(null, new HttpResponse(req, new HttpPost(endpoint)));

  collector.collectMetrics(req, resp);
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: MemoryOverwritingRequestHandlerTest.java    From fernet-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyAfterErrorClearsSecret() {
    // given
    final ByteBuffer secretBinary = ByteBuffer.wrap(new byte[] { 1, 1, 2, 3, 5, 8 });
    assertTrue(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8}));
    final PutSecretValueRequest originalRequest = new PutSecretValueRequest();
    originalRequest.setSecretBinary(secretBinary);
    final Request<PutSecretValueRequest> request = new DefaultRequest<PutSecretValueRequest>(originalRequest,
            "AWSSecretsManager");
    final PutSecretValueResult result = mock(PutSecretValueResult.class);
    final HttpResponse httpResponse = mock(HttpResponse.class);
    final Response<PutSecretValueResult> response = new Response<PutSecretValueResult>(result, httpResponse);

    // when
    handler.afterError(request, response, new Exception());

    // then
    assertFalse(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8}));
}
 
Example #17
Source File: MemoryOverwritingRequestHandlerTest.java    From fernet-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyAfterResponseClearsSecret() {
    // given
    final ByteBuffer secretBinary = ByteBuffer.wrap(new byte[] { 1, 1, 2, 3, 5, 8 });
    assertTrue(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8}));
    final PutSecretValueRequest originalRequest = new PutSecretValueRequest();
    originalRequest.setSecretBinary(secretBinary);
    final Request<PutSecretValueRequest> request = new DefaultRequest<PutSecretValueRequest>(originalRequest,
            "AWSSecretsManager");
    final PutSecretValueResult result = mock(PutSecretValueResult.class);
    final HttpResponse httpResponse = mock(HttpResponse.class);
    final Response<PutSecretValueResult> response = new Response<PutSecretValueResult>(result, httpResponse);

    // when
    handler.afterResponse(request, response);

    // then
    assertFalse(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8}));
}
 
Example #18
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 #19
Source File: AwsHttpRequest.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public FakeAwsHttpRequest() {
    this.fakeRq = new DefaultRequest<>("fake");
    this.fakeRq.setEndpoint(
        URI.create("http://localhost:8080/test")
    );
}
 
Example #20
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);
    }
}