Java 类com.amazonaws.http.HttpMethodName 实例源码

项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientTest.java   
@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));
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientTest.java   
@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));
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientTest.java   
@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());
    }
}
项目:ibm-cos-sdk-java    文件:ApacheHttpRequestFactory.java   
private void addRequestConfig(final HttpRequestBase base,
                              final Request<?> request,
                              final HttpClientSettings settings) {
    final RequestConfig.Builder requestConfigBuilder = RequestConfig
            .custom()
            .setConnectionRequestTimeout(settings.getConnectionPoolRequestTimeout())
            .setConnectTimeout(settings.getConnectionTimeout())
            .setSocketTimeout(settings.getSocketTimeout())
            .setLocalAddress(settings.getLocalAddress());

    /*
     * Enable 100-continue support for PUT operations, since this is
     * where we're potentially uploading large amounts of data and want
     * to find out as early as possible if an operation will fail. We
     * don't want to do this for all operations since it will cause
     * extra latency in the network interaction.
     */
    if (HttpMethodName.PUT == request.getHttpMethod() && settings.isUseExpectContinue()) {
        requestConfigBuilder.setExpectContinueEnabled(true);
    }

    addProxyConfig(requestConfigBuilder, settings);

    base.setConfig(requestConfigBuilder.build());
}
项目:ibm-cos-sdk-java    文件:AbortedExceptionClientExecutionTimerIntegrationTest.java   
@Test(expected = ClientExecutionTimeoutException.class)
public void
clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_expired()
        throws Exception {
    ClientConfiguration config = new ClientConfiguration()
            .withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)
            .withMaxErrorRetry(0);
    ConnectionManagerAwareHttpClient rawHttpClient =
            createRawHttpClientSpy(config);

    httpClient = new AmazonHttpClient(config, rawHttpClient, null);

    execute(httpClient, new EmptyHttpRequest(server.getEndpoint(),
            HttpMethodName.PUT, new SdkBufferedInputStream(new InputStream() {
        @Override
        public int read() throws IOException {
            // Sleeping here to avoid OOM issues from a limitless InputStream
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return 1;
        }
    })));
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void request_has_proxy_config_when_proxy_auth_enabled() throws Exception {
    List<ProxyAuthenticationMethod> authMethods = Arrays.asList(ProxyAuthenticationMethod.BASIC,
                                                                ProxyAuthenticationMethod.DIGEST,
                                                                ProxyAuthenticationMethod.KERBEROS,
                                                                ProxyAuthenticationMethod.NTLM,
                                                                ProxyAuthenticationMethod.SPNEGO);
    List<String> expectedAuthMethods = Arrays.asList(AuthSchemes.BASIC,
                                                     AuthSchemes.DIGEST,
                                                     AuthSchemes.KERBEROS,
                                                     AuthSchemes.NTLM,
                                                     AuthSchemes.SPNEGO);

    ClientConfiguration configuration = new ClientConfiguration().withProxyHost("localhost")
                                                                 .withProxyPort(80)
                                                                 .withProxyUsername("user")
                                                                 .withProxyPassword("password")
                                                                 .withProxyAuthenticationMethods(authMethods);
    HttpClientSettings settings = HttpClientSettings.adapt(configuration);
    HttpRequestBase requestBase = requestFactory.create(newDefaultRequest(HttpMethodName.POST), settings);
    Assert.assertEquals(expectedAuthMethods, requestBase.getConfig().getProxyPreferredAuthSchemes());
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public VersionListing listVersions(ListVersionsRequest listVersionsRequest)
        throws SdkClientException, AmazonServiceException {
    listVersionsRequest = beforeClientExecution(listVersionsRequest);
    rejectNull(listVersionsRequest.getBucketName(), "The bucket name parameter must be specified when listing versions in a bucket");

    /**
     * This flag shows whether we need to url decode S3 key names. This flag is enabled
     * only when the customers don't explicitly call {@link listVersionsRequest#setEncodingType(String)},
     * otherwise, it will be disabled for maintaining backwards compatibility.
     */
    final boolean shouldSDKDecodeResponse = listVersionsRequest.getEncodingType() == null;

    Request<ListVersionsRequest> request = createRequest(listVersionsRequest.getBucketName(), null, listVersionsRequest, HttpMethodName.GET);
    request.addParameter("versions", null);

    addParameterIfNotNull(request, "prefix", listVersionsRequest.getPrefix());
    addParameterIfNotNull(request, "key-marker", listVersionsRequest.getKeyMarker());
    addParameterIfNotNull(request, "version-id-marker", listVersionsRequest.getVersionIdMarker());
    addParameterIfNotNull(request, "delimiter", listVersionsRequest.getDelimiter());

    if (listVersionsRequest.getMaxResults() != null && listVersionsRequest.getMaxResults() >= 0) request.addParameter("max-keys", listVersionsRequest.getMaxResults().toString());
    request.addParameter("encoding-type", shouldSDKDecodeResponse ? Constants.URL_ENCODING : listVersionsRequest.getEncodingType());

    return invoke(request, new Unmarshallers.VersionListUnmarshaller(shouldSDKDecodeResponse), listVersionsRequest.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest)
        throws SdkClientException, AmazonServiceException {
    listObjectsRequest = beforeClientExecution(listObjectsRequest);
    rejectNull(listObjectsRequest.getBucketName(), "The bucket name parameter must be specified when listing objects in a bucket");

    /**
     * This flag shows whether we need to url decode S3 key names. This flag is enabled
     * only when the customers don't explicitly call {@link ListObjectsRequest#setEncodingType(String)},
     * otherwise, it will be disabled for maintaining backwards compatibility.
     */
    final boolean shouldSDKDecodeResponse = listObjectsRequest.getEncodingType() == null;

    Request<ListObjectsRequest> request = createRequest(listObjectsRequest.getBucketName(), null, listObjectsRequest, HttpMethodName.GET);
    addParameterIfNotNull(request, "prefix", listObjectsRequest.getPrefix());
    addParameterIfNotNull(request, "marker", listObjectsRequest.getMarker());
    addParameterIfNotNull(request, "delimiter", listObjectsRequest.getDelimiter());
    if (listObjectsRequest.getMaxKeys() != null && listObjectsRequest.getMaxKeys().intValue() >= 0) request.addParameter("max-keys", listObjectsRequest.getMaxKeys().toString());
    request.addParameter("encoding-type", shouldSDKDecodeResponse ? Constants.URL_ENCODING : listObjectsRequest.getEncodingType());

    return invoke(request, new Unmarshallers.ListObjectsUnmarshaller(shouldSDKDecodeResponse), listObjectsRequest.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public List<Bucket> listBuckets(ListBucketsRequest listBucketsRequest)
        throws SdkClientException, AmazonServiceException {
    listBucketsRequest = beforeClientExecution(listBucketsRequest);
    rejectNull(listBucketsRequest, "The request object parameter listBucketsRequest must be specified.");
    Request<ListBucketsRequest> request = createRequest(null, null, listBucketsRequest, HttpMethodName.GET);

    //Add IBM Service Instance Id to headers
    if ((null != this.awsCredentialsProvider ) && (this.awsCredentialsProvider.getCredentials() instanceof IBMOAuthCredentials)) {
        IBMOAuthCredentials oAuthCreds = (IBMOAuthCredentials)this.awsCredentialsProvider.getCredentials();
        if (oAuthCreds.getServiceInstanceId() != null) {
            request.addHeader(Headers.IBM_SERVICE_INSTANCE_ID, oAuthCreds.getServiceInstanceId());  
        }
    }

    return invoke(request, new Unmarshallers.ListBucketsUnmarshaller(), null, null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public ObjectMetadata getObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest)
        throws SdkClientException, AmazonServiceException {
    getObjectMetadataRequest = beforeClientExecution(getObjectMetadataRequest);
    rejectNull(getObjectMetadataRequest, "The GetObjectMetadataRequest parameter must be specified when requesting an object's metadata");

    String bucketName = getObjectMetadataRequest.getBucketName();
    String key = getObjectMetadataRequest.getKey();
    String versionId = getObjectMetadataRequest.getVersionId();

    rejectNull(bucketName, "The bucket name parameter must be specified when requesting an object's metadata");
    rejectNull(key, "The key parameter must be specified when requesting an object's metadata");

    Request<GetObjectMetadataRequest> request = createRequest(bucketName, key, getObjectMetadataRequest, HttpMethodName.HEAD);

    if (versionId != null) request.addParameter("versionId", versionId);

    populateRequesterPaysHeader(request, getObjectMetadataRequest.isRequesterPays());
    addPartNumberIfNotNull(request, getObjectMetadataRequest.getPartNumber());

    populateSSE_C(request, getObjectMetadataRequest.getSSECustomerKey());

    return invoke(request, new S3MetadataResponseHandler(), bucketName, key);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public void deleteVersion(DeleteVersionRequest deleteVersionRequest)
        throws SdkClientException, AmazonServiceException {
    deleteVersionRequest = beforeClientExecution(deleteVersionRequest);
    rejectNull(deleteVersionRequest,
        "The delete version request object must be specified when deleting a version");

    String bucketName = deleteVersionRequest.getBucketName();
    String key = deleteVersionRequest.getKey();
    String versionId = deleteVersionRequest.getVersionId();

    rejectNull(bucketName, "The bucket name must be specified when deleting a version");
    rejectNull(key, "The key must be specified when deleting a version");
    rejectNull(versionId, "The version ID must be specified when deleting a version");

    Request<DeleteVersionRequest> request = createRequest(bucketName, key, deleteVersionRequest, HttpMethodName.DELETE);
    if (versionId != null) request.addParameter("versionId", versionId);

    if (deleteVersionRequest.getMfa() != null) {
        populateRequestWithMfaDetails(request, deleteVersionRequest.getMfa());
    }

    invoke(request, voidResponseHandler, bucketName, key);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public BucketCrossOriginConfiguration getBucketCrossOriginConfiguration(GetBucketCrossOriginConfigurationRequest getBucketCrossOriginConfigurationRequest) {
    getBucketCrossOriginConfigurationRequest = beforeClientExecution(getBucketCrossOriginConfigurationRequest);
    rejectNull(getBucketCrossOriginConfigurationRequest, "The request object parameter getBucketCrossOriginConfigurationRequest must be specified.");
    String bucketName = getBucketCrossOriginConfigurationRequest.getBucketName();
    rejectNull(bucketName, "The bucket name must be specified when retrieving the bucket cross origin configuration.");

    Request<GetBucketCrossOriginConfigurationRequest> request = createRequest(bucketName, null, getBucketCrossOriginConfigurationRequest, HttpMethodName.GET);
    request.addParameter("cors", null);

    try {
        return invoke(request, new Unmarshallers.BucketCrossOriginConfigurationUnmarshaller(), bucketName, null);
    } catch (AmazonServiceException ase) {
        switch (ase.getStatusCode()) {
        case 404:
            return null;
        default:
            throw ase;
        }
    }
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public BucketTaggingConfiguration getBucketTaggingConfiguration(GetBucketTaggingConfigurationRequest getBucketTaggingConfigurationRequest) {
    getBucketTaggingConfigurationRequest = beforeClientExecution(getBucketTaggingConfigurationRequest);
    rejectNull(getBucketTaggingConfigurationRequest, "The request object parameter getBucketTaggingConfigurationRequest must be specifed.");
    String bucketName = getBucketTaggingConfigurationRequest.getBucketName();
    rejectNull(bucketName, "The bucket name must be specified when retrieving the bucket tagging configuration.");

    Request<GetBucketTaggingConfigurationRequest> request = createRequest(bucketName, null, getBucketTaggingConfigurationRequest, HttpMethodName.GET);
    request.addParameter("tagging", null);

    try {
        return invoke(request, new Unmarshallers.BucketTaggingConfigurationUnmarshaller(), bucketName, null);
    } catch (AmazonServiceException ase) {
        switch (ase.getStatusCode()) {
        case 404:
            return null;
        default:
            throw ase;
        }
    }
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public void deleteBucketTaggingConfiguration(
        DeleteBucketTaggingConfigurationRequest deleteBucketTaggingConfigurationRequest) {
    deleteBucketTaggingConfigurationRequest = beforeClientExecution(deleteBucketTaggingConfigurationRequest);
    rejectNull(deleteBucketTaggingConfigurationRequest,
            "The delete bucket tagging configuration request object must be specified.");

    String bucketName = deleteBucketTaggingConfigurationRequest.getBucketName();
    rejectNull(bucketName,
            "The bucket name parameter must be specified when deleting bucket tagging configuration.");

    Request<DeleteBucketTaggingConfigurationRequest> request = createRequest(bucketName, null, deleteBucketTaggingConfigurationRequest, HttpMethodName.DELETE);
    request.addParameter("tagging", null);

    invoke(request, voidResponseHandler, bucketName, null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public void abortMultipartUpload(AbortMultipartUploadRequest abortMultipartUploadRequest)
        throws SdkClientException, AmazonServiceException {
    abortMultipartUploadRequest = beforeClientExecution(abortMultipartUploadRequest);
    rejectNull(abortMultipartUploadRequest,
        "The request parameter must be specified when aborting a multipart upload");
    rejectNull(abortMultipartUploadRequest.getBucketName(),
        "The bucket name parameter must be specified when aborting a multipart upload");
    rejectNull(abortMultipartUploadRequest.getKey(),
        "The key parameter must be specified when aborting a multipart upload");
    rejectNull(abortMultipartUploadRequest.getUploadId(),
        "The upload ID parameter must be specified when aborting a multipart upload");

    String bucketName = abortMultipartUploadRequest.getBucketName();
    String key = abortMultipartUploadRequest.getKey();

    Request<AbortMultipartUploadRequest> request = createRequest(bucketName, key, abortMultipartUploadRequest, HttpMethodName.DELETE);
    request.addParameter("uploadId", abortMultipartUploadRequest.getUploadId());
    populateRequesterPaysHeader(request, abortMultipartUploadRequest.isRequesterPays());

    invoke(request, voidResponseHandler, bucketName, key);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest)
        throws SdkClientException, AmazonServiceException {
    listMultipartUploadsRequest = beforeClientExecution(listMultipartUploadsRequest);
    rejectNull(listMultipartUploadsRequest,
        "The request parameter must be specified when listing multipart uploads");

    rejectNull(listMultipartUploadsRequest.getBucketName(),
        "The bucket name parameter must be specified when listing multipart uploads");

    Request<ListMultipartUploadsRequest> request = createRequest(listMultipartUploadsRequest.getBucketName(), null, listMultipartUploadsRequest, HttpMethodName.GET);
    request.addParameter("uploads", null);

    if (listMultipartUploadsRequest.getKeyMarker() != null) request.addParameter("key-marker", listMultipartUploadsRequest.getKeyMarker());
    if (listMultipartUploadsRequest.getMaxUploads() != null) request.addParameter("max-uploads", listMultipartUploadsRequest.getMaxUploads().toString());
    if (listMultipartUploadsRequest.getUploadIdMarker() != null) request.addParameter("upload-id-marker", listMultipartUploadsRequest.getUploadIdMarker());
    if (listMultipartUploadsRequest.getDelimiter() != null) request.addParameter("delimiter", listMultipartUploadsRequest.getDelimiter());
    if (listMultipartUploadsRequest.getPrefix() != null) request.addParameter("prefix", listMultipartUploadsRequest.getPrefix());
    if (listMultipartUploadsRequest.getEncodingType() != null) request.addParameter("encoding-type", listMultipartUploadsRequest.getEncodingType());

    return invoke(request, new Unmarshallers.ListMultipartUploadsResultUnmarshaller(), listMultipartUploadsRequest.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
protected <X extends AmazonWebServiceRequest> Request<X> createRequest(String bucketName, String key, X originalRequest, HttpMethodName httpMethod, URI endpoint) {
    // If the underlying AmazonS3Client has enabled accelerate mode and the original
    // request operation is accelerate mode supported, then the request will use the
    // s3-accelerate endpoint to performe the operations.
    if (clientOptions.isAccelerateModeEnabled() && !(originalRequest instanceof S3AccelerateUnsupported)) {
        if (clientOptions.isDualstackEnabled()) {
            endpoint = RuntimeHttpUtils.toUri(Constants.S3_ACCELERATE_DUALSTACK_HOSTNAME, clientConfiguration);
        } else {
            endpoint = RuntimeHttpUtils.toUri(Constants.S3_ACCELERATE_HOSTNAME, clientConfiguration);
        }
    }

    Request<X> request = new DefaultRequest<X>(originalRequest, Constants.S3_SERVICE_DISPLAY_NAME);
    request.setHttpMethod(httpMethod);
    request.addHandlerContext(S3HandlerContextKeys.IS_CHUNKED_ENCODING_DISABLED,
            Boolean.valueOf(clientOptions.isChunkedEncodingDisabled()));
    request.addHandlerContext(S3HandlerContextKeys.IS_PAYLOAD_SIGNING_ENABLED,
            Boolean.valueOf(clientOptions.isPayloadSigningEnabled()));
    resolveRequestEndpoint(request, bucketName, key, endpoint);

    return request;
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
/**
 * Retrieves the request payment configuration for a given Amazon S3 bucket.
 * <p>
 * When the request payment configuration for a Amazon S3 bucket is
 * <code>Requester</code>, the requester instead of the bucket owner pays
 * the cost of the request and the data download from the bucket. The bucket
 * owner always pays the cost of storing data.
 */
private RequestPaymentConfiguration getBucketRequestPayment(
        GetRequestPaymentConfigurationRequest getRequestPaymentConfigurationRequest) {

    String bucketName = getRequestPaymentConfigurationRequest
            .getBucketName();

    rejectNull(
            bucketName,
            "The bucket name parameter must be specified while getting the Request Payment Configuration.");

    Request<GetRequestPaymentConfigurationRequest> request = createRequest(
            bucketName, null, getRequestPaymentConfigurationRequest,
            HttpMethodName.GET);
    request.addParameter("requestPayment", null);
    request.addHeader("Content-Type", "application/xml");

    return invoke(request,
            new Unmarshallers.RequestPaymentConfigurationUnmarshaller(),
            bucketName, null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
/**
 * Retrieves the region of the bucket by making a HeadBucket request to us-west-1 region.
 *
 * Currently S3 doesn't return region in a HEAD Bucket request if the bucket
 * owner has enabled bucket to accept only SigV4 requests via bucket
 * policies.
 */
private String getBucketRegionViaHeadRequest(String bucketName) {
    String bucketRegion = null;

    try {
        Request<HeadBucketRequest> request = createRequest(bucketName, null,
                new HeadBucketRequest(bucketName), HttpMethodName.HEAD);

        HeadBucketResult result = invoke(request, new HeadBucketResultHandler(), bucketName, null, true);
        bucketRegion = result.getBucketRegion();
    } catch (AmazonS3Exception exception) {
        if (exception.getAdditionalDetails() != null) {
            bucketRegion = exception.getAdditionalDetails().get(
                Headers.S3_BUCKET_REGION);
        }
    }

    if (bucketRegion == null && log.isDebugEnabled()) {
        log.debug("Not able to derive region of the " + bucketName + " from the HEAD Bucket requests.");
    }

    return bucketRegion;
}
项目:charles-rest    文件:AwsPostTestCase.java   
/**
 * 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));
}
项目:aws-hal-client-java    文件:HalClient.java   
private <T> T invoke(HttpMethodName httpMethodName, String resourcePath, Object representation,
                     HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler)
        throws AmazonClientException {
    ExecutionContext executionContext = createExecutionContext();
    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();

    awsRequestMetrics.startEvent(AWSRequestMetrics.Field.RequestMarshallTime.name());
    Request request = buildRequest(httpMethodName, resourcePath, representation);
    awsRequestMetrics.endEvent(AWSRequestMetrics.Field.RequestMarshallTime.name());

    awsRequestMetrics.startEvent(AWSRequestMetrics.Field.CredentialsRequestTime.name());
    AWSCredentials credentials = awsCredentialsProvider.getCredentials();
    awsRequestMetrics.endEvent(AWSRequestMetrics.Field.CredentialsRequestTime.name());

    executionContext.setCredentials(credentials);

    awsRequestMetrics.startEvent(AWSRequestMetrics.Field.ClientExecuteTime.name());
    Response<T> response = client.execute(request, responseHandler, errorResponseHandler, executionContext);
    awsRequestMetrics.endEvent(AWSRequestMetrics.Field.ClientExecuteTime.name());

    awsRequestMetrics.log();

    return response.getAwsResponse();
}
项目:apigateway-generic-java-sdk    文件:Main.java   
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();
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayRequest.java   
public GenericApiGatewayRequest(HttpMethodName httpMethod, String resourcePath,
                                InputStream body, Map<String, String> headers) {
    this.httpMethod = httpMethod;
    this.resourcePath = resourcePath;
    this.body = body;
    this.headers = headers;
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClient.java   
private GenericApiGatewayResponse execute(HttpMethodName method, String resourcePath, Map<String, String> headers, 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));

    return this.client.execute(request, responseHandler, errorResponseHandler, executionContext).getAwsResponse();
}
项目:async-sqs    文件:AsyncRequestConverterTest.java   
@Test
public void testRequestConversion() throws URISyntaxException {


    Map<String, String> headers = new HashMap<>();
    headers.put(TEST_KEY_A, TEST_VALUE_B);
    headers.put(TEST_KEY_C, TEST_VALUE_D);

    Map<String, List<String>> params = new HashMap<>();
    params.put(TEST_KEY_A, Collections.singletonList(TEST_VALUE_B));
    params.put(TEST_KEY_C, Collections.singletonList(TEST_VALUE_D));

    SignableRequest<?> signableRequest = mock(SignableRequest.class);
    URI endpoint = new URI("http://bandwidth.com");
    when(signableRequest.getHttpMethod()).thenReturn(HttpMethodName.GET);
    when(signableRequest.getEndpoint()).thenReturn(endpoint);
    when(signableRequest.getResourcePath()).thenReturn(PATH);
    when(signableRequest.getHeaders()).thenReturn(headers);
    when(signableRequest.getParameters()).thenReturn(params);

    Function<SignableRequest<?>, Request> converter = new AsyncRequestConverter();
    Request output = converter.apply(signableRequest);

    assertThat(output.getMethod()).isEqualToIgnoringCase(GET_METHOD);
    assertThat(output.getUri().getPath()).isEqualTo(PATH);
    assertThat(output.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B);
    assertThat(output.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D);
    assertThat(output.getStringData()).isEqualTo(ENCODED_BODY);
    assertThat(output.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE))
            .isEqualTo(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
}
项目:ibm-cos-sdk-java    文件:ApacheHttpRequestFactory.java   
@Override
public HttpRequestBase create(final Request<?> request,
                              final HttpClientSettings settings)
        throws
        FakeIOException {
    URI endpoint = request.getEndpoint();

    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String uri = SdkHttpUtils.appendUri(endpoint.toString(), request
            .getResourcePath(), true);
    String encodedParams = SdkHttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    final HttpRequestBase base = createApacheRequest(request, uri, encodedParams);
    addHeadersToRequest(base, request);
    addRequestConfig(base, request, settings);

    return base;
}
项目:ibm-cos-sdk-java    文件:ApacheHttpRequestFactory.java   
private HttpRequestBase wrapEntity(Request<?> request,
                                   HttpEntityEnclosingRequestBase entityEnclosingRequest,
                                   String encodedParams) throws FakeIOException {

    if (HttpMethodName.POST == request.getHttpMethod()) {
        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            entityEnclosingRequest.setEntity(ApacheUtils.newStringEntity(encodedParams));
        } else {
            entityEnclosingRequest.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
    } else {
        /*
         * We should never reuse the entity of the previous request, since
         * reading from the buffered entity will bypass reading from the
         * original request content. And if the content contains InputStream
         * wrappers that were added for validation-purpose (e.g.
         * Md5DigestCalculationInputStream), these wrappers would never be
         * read and updated again after AmazonHttpClient resets it in
         * preparation for the retry. Eventually, these wrappers would
         * return incorrect validation result.
         */
        if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get(HttpHeaders.CONTENT_LENGTH) == null) {
                entity = ApacheUtils.newBufferedHttpEntity(entity);
            }
            entityEnclosingRequest.setEntity(entity);
        }
    }
    return entityEnclosingRequest;
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void uri_resourcepath_escapes_double_slash() throws IOException, URISyntaxException {

    final Request<Object> request = newDefaultRequest(HttpMethodName.GET);
    request.setResourcePath("//foo");
    request.setEndpoint(new URI(ENDPOINT));
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    URI expectredUri = requestBase.getURI();
    Assert.assertEquals("/%2Ffoo", expectredUri.getRawPath());
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void query_parameters_moved_to_payload_for_post_request_with_no_payload
        () throws IOException, URISyntaxException {
    final Request<Object> request = newDefaultRequest(HttpMethodName.POST);
    request.withParameter("foo", "bar")
            .withParameter("alpha", "beta");
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    Assert.assertThat(requestBase, Matchers.instanceOf(HttpPost
            .class));
    HttpPost post = (HttpPost) requestBase;
    HttpEntity entity = post.getEntity();
    byte[] actualContents = drainInputStream(entity.getContent());
    Assert.assertTrue(actualContents.length > 0);
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void query_parameters_in_uri_for_all_non_post_requests() throws IOException, URISyntaxException {
    final Request<Object> request = newDefaultRequest(HttpMethodName.GET);
    request.withParameter("foo", "bar");
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    Assert.assertEquals("foo=bar", requestBase.getURI().getQuery());
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void query_params_in_uri_for_post_request_with_payload() throws IOException, URISyntaxException {
    final Request<Object> request = newDefaultRequest(HttpMethodName.POST);
    request.withParameter("foo", "bar");
    final String payload = "dummy string stream";
    request.setContent(new StringInputStream(payload));
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    Assert.assertThat(requestBase, Matchers.instanceOf(HttpPost
            .class));
    Assert.assertEquals("foo=bar", requestBase.getURI().getQuery());
    Assert.assertThat(requestBase, Matchers.instanceOf(HttpPost
            .class));
    Assert.assertEquals(payload, IOUtils.toString(((HttpPost)requestBase).getEntity().getContent()));
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void request_has_default_content_type_set_when_not_explicitly_set() throws IOException,
        URISyntaxException {
    final Request<Object> request = newDefaultRequest(HttpMethodName.POST);
    request.setContent(new StringInputStream("dummy string stream"));
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    assertContentTypeContains("application/x-www-form-urlencoded",
            requestBase.getHeaders(CONTENT_TYPE));
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void apache_request_has_content_type_set_when_not_explicitly_set() throws IOException,
        URISyntaxException {

    final Request<Object> request = newDefaultRequest(HttpMethodName.POST);
    final String testContentype = "testContentType";
    request.addHeader(HttpHeaders.CONTENT_TYPE, testContentype);
    request.setContent(new StringInputStream("dummy string stream"));
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    assertContentTypeContains(testContentype,
            requestBase.getHeaders(CONTENT_TYPE));

}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
@Test
public void request_has_no_proxy_config_when_proxy_auth_disabled() throws Exception {
    List<ProxyAuthenticationMethod> authMethods = Collections.singletonList(ProxyAuthenticationMethod.BASIC);
    ClientConfiguration configuration = new ClientConfiguration().withProxyHost("localhost")
                                                                 .withProxyPort(80)
                                                                 .withProxyAuthenticationMethods(authMethods);
    HttpClientSettings settings = HttpClientSettings.adapt(configuration);
    HttpRequestBase requestBase = requestFactory.create(newDefaultRequest(HttpMethodName.POST), settings);
    Assert.assertThat(requestBase.getConfig().getProxyPreferredAuthSchemes(), Matchers.nullValue());
}
项目:ibm-cos-sdk-java    文件:ApacheDefaultHttpRequestFactoryTest.java   
private DefaultRequest<Object> newDefaultRequest(HttpMethodName httpMethod) throws
        URISyntaxException {

    final DefaultRequest<Object> request = new DefaultRequest<Object>
            (null, SERVICE_NAME);
    request.setEndpoint(new URI(ENDPOINT));
    request.setHttpMethod(httpMethod);
    return request;
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public ListObjectsV2Result listObjectsV2(ListObjectsV2Request listObjectsV2Request)
        throws SdkClientException, AmazonServiceException {
    listObjectsV2Request = beforeClientExecution(listObjectsV2Request);
    rejectNull(listObjectsV2Request.getBucketName(), "The bucket name parameter must be specified when listing objects in a bucket");
    Request<ListObjectsV2Request> request = createRequest(listObjectsV2Request.getBucketName(), null, listObjectsV2Request, HttpMethodName.GET);

    /**
     * List type '2' is required to opt-in to listObjectsV2.
     */
    request.addParameter("list-type", "2");

    addParameterIfNotNull(request, "start-after", listObjectsV2Request.getStartAfter());
    addParameterIfNotNull(request, "continuation-token", listObjectsV2Request.getContinuationToken());
    addParameterIfNotNull(request, "delimiter", listObjectsV2Request.getDelimiter());
    addParameterIfNotNull(request, "max-keys", listObjectsV2Request.getMaxKeys());
    addParameterIfNotNull(request, "prefix", listObjectsV2Request.getPrefix());
    addParameterIfNotNull(request, "encoding-type", listObjectsV2Request.getEncodingType());
    request.addParameter("fetch-owner", Boolean.toString(listObjectsV2Request.isFetchOwner()));

    /**
     * If URL encoding has been requested from S3 we'll automatically decode the response.
     */
    final boolean shouldSDKDecodeResponse = listObjectsV2Request.getEncodingType() == Constants.URL_ENCODING;

    return invoke(request, new Unmarshallers.ListObjectsV2Unmarshaller(shouldSDKDecodeResponse), listObjectsV2Request.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public Owner getS3AccountOwner(GetS3AccountOwnerRequest getS3AccountOwnerRequest)
        throws SdkClientException, AmazonServiceException {
    getS3AccountOwnerRequest = beforeClientExecution(getS3AccountOwnerRequest);
    rejectNull(getS3AccountOwnerRequest, "The request object parameter getS3AccountOwnerRequest must be specified.");
    Request<GetS3AccountOwnerRequest> request = createRequest(null, null, getS3AccountOwnerRequest, HttpMethodName.GET);
    return invoke(request, new Unmarshallers.ListBucketsOwnerUnmarshaller(), null, null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public HeadBucketResult headBucket(HeadBucketRequest headBucketRequest)
        throws SdkClientException, AmazonServiceException {
    headBucketRequest = beforeClientExecution(headBucketRequest);
    String bucketName = headBucketRequest.getBucketName();

    rejectNull(bucketName,
            "The bucketName parameter must be specified.");

    Request<HeadBucketRequest> request = createRequest(bucketName, null,
            headBucketRequest, HttpMethodName.HEAD);

    return invoke(request, new HeadBucketResultHandler(), bucketName, null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public void deleteBucket(DeleteBucketRequest deleteBucketRequest)
        throws SdkClientException, AmazonServiceException {
    deleteBucketRequest = beforeClientExecution(deleteBucketRequest);
    rejectNull(deleteBucketRequest,
            "The DeleteBucketRequest parameter must be specified when deleting a bucket");

    String bucketName = deleteBucketRequest.getBucketName();
    rejectNull(bucketName,
            "The bucket name parameter must be specified when deleting a bucket");

    Request<DeleteBucketRequest> request = createRequest(bucketName, null, deleteBucketRequest, HttpMethodName.DELETE);
    invoke(request, voidResponseHandler, bucketName, null);
    bucketRegionCache.remove(bucketName);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public void deleteObject(DeleteObjectRequest deleteObjectRequest)
        throws SdkClientException, AmazonServiceException {
    deleteObjectRequest = beforeClientExecution(deleteObjectRequest);
    rejectNull(deleteObjectRequest,
        "The delete object request must be specified when deleting an object");

    rejectNull(deleteObjectRequest.getBucketName(), "The bucket name must be specified when deleting an object");
    rejectNull(deleteObjectRequest.getKey(), "The key must be specified when deleting an object");

    Request<DeleteObjectRequest> request = createRequest(deleteObjectRequest.getBucketName(), deleteObjectRequest.getKey(), deleteObjectRequest, HttpMethodName.DELETE);
    invoke(request, voidResponseHandler, deleteObjectRequest.getBucketName(), deleteObjectRequest.getKey());
}