Java 类com.amazonaws.AmazonWebServiceRequest 实例源码

项目:ibm-cos-sdk-java    文件:StackedRequestHandlerTest.java   
/**
 * The beforeMarshalling step is a bit different. It's expected to take the potentially
 * modified {@link AmazonWebServiceRequest} returned by
 * {@link RequestHandler2#beforeMarshalling(AmazonWebServiceRequest)} and forward that
 * result as input to the next request handler in the chain. This tests makes sure that each
 * request handler forwards the appropriate the result to the next in the chain and that the
 * end result is what's returned by the last request handler in the chain
 */
@Test
public void beforeMarshalling_ModifiedRequestForwardedToNextInChain() {
    final AmazonWebServiceRequest origAwsRequest = mock(AmazonWebServiceRequest.class);
    final AmazonWebServiceRequest afterFirstAwsRequest = mock(AmazonWebServiceRequest.class);
    final AmazonWebServiceRequest afterSecondAwsRequest = mock(AmazonWebServiceRequest.class);
    final AmazonWebServiceRequest afterThirdAwsRequest = mock(AmazonWebServiceRequest.class);

    doReturn(afterFirstAwsRequest).when(first).beforeMarshalling(origAwsRequest);
    doReturn(afterSecondAwsRequest).when(second).beforeMarshalling(afterFirstAwsRequest);
    doReturn(afterThirdAwsRequest).when(third).beforeMarshalling(afterSecondAwsRequest);

    assertEquals(afterThirdAwsRequest, stackedRequestHandler.beforeMarshalling(origAwsRequest));

    InOrder inOrder = inOrder(first, second, third);
    inOrder.verify(first).beforeMarshalling(origAwsRequest);
    inOrder.verify(second).beforeMarshalling(afterFirstAwsRequest);
    inOrder.verify(third).beforeMarshalling(afterSecondAwsRequest);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
private boolean shouldRetryCompleteMultipartUpload(AmazonWebServiceRequest originalRequest,
                                                   AmazonS3Exception exception,
                                                   int retriesAttempted) {

    final RetryPolicy retryPolicy = clientConfiguration.getRetryPolicy();

    if (retryPolicy == null || retryPolicy.getRetryCondition() == null) {
        return false;
    }

    if (retryPolicy == PredefinedRetryPolicies.NO_RETRY_POLICY) {
        return false;
    }

    return completeMultipartUploadRetryCondition.shouldRetry
            (originalRequest, exception, retriesAttempted);
}
项目: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;
}
项目:photon-model    文件:AWSTaskStatusChecker.java   
private void runSearch(T type) {
    AmazonWebServiceRequest descRequest = buildRequest(type);
    AsyncHandler describeHandler = buildHandler(type);
    if (type instanceof Instance) {
        this.amazonEC2Client.describeInstancesAsync(
                (DescribeInstancesRequest) descRequest, describeHandler);
    } else if (type instanceof NatGateway) {
        this.amazonEC2Client.describeNatGatewaysAsync(
                (DescribeNatGatewaysRequest) descRequest, describeHandler);
    } else if (type instanceof Volume) {
        this.amazonEC2Client.describeVolumesAsync(
                (DescribeVolumesRequest) descRequest, describeHandler);
    } else {
        AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(
                new IllegalArgumentException("Invalid type " + type));
    }
}
项目:ivona-speechcloud-sdk-java    文件:IvonaSpeechCloudClient.java   
private <Y> Request<Y> prepareRequest(Request<Y> request, ExecutionContext executionContext, boolean signRequest) {
    request.setEndpoint(endpoint);
    request.setTimeOffset(timeOffset);

    AWSCredentials credentials = awsCredentialsProvider.getCredentials();

    AmazonWebServiceRequest originalRequest = request.getOriginalRequest();
    if (originalRequest != null && originalRequest.getRequestCredentials() != null) {
        credentials = originalRequest.getRequestCredentials();
    }
    if (signRequest) {
        // expiration date is not currently supported on service side, but presignRequest method requires
        // this argument so one with default value is provided.
        Date expirationDate = DateTime.now(DateTimeZone.UTC)
                .plusMinutes(DEFAULT_GET_REQUEST_EXPIRATION_MINUTES).toDate();
        signer.presignRequest(request, credentials, expirationDate);
    } else {
        executionContext.setSigner(signer);
        executionContext.setCredentials(credentials);
    }
    return request;
}
项目:aws-sdk-java-resources    文件:ActionUtils.java   
private static Method tryFindClientMethod(Object client, String name) {
    // TODO: Cache me.
    for (Method method : client.getClass().getMethods()) {
        if (!method.getName().equals(name)) {
            continue;
        }

        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length != 1) {
            continue;
        }

        // This is the inverse of the normal approach of findMethod() -
        // we're looking for a method which will accept a specific subtype
        // of AmazonWebServiceRequest, without worrying overmuch about
        // what subtype it is. We'll create an object of the appropriate
        // type and fill it in.
        if (AmazonWebServiceRequest.class.isAssignableFrom(parameters[0])) {
            return method;
        }
    }

    return null;
}
项目:aws-sdk-java-resources    文件:ResourceImpl.java   
/**
 * Performs the given action on this resource. This always involves a
 * request to the service. It may mark the cached attributes of this
 * resource object dirty.
 *
 * @param name the name of the action to perform
 * @param request the client-specified request object
 * @param extractor an optional result extractor object
 * @return the result of executing the action
 */
public ActionResult performAction(
        String name,
        AmazonWebServiceRequest request,
        ResultCapture<?> extractor) {

    ActionModel action = resourceModel.getAction(name);
    if (action == null) {
        throw new UnsupportedOperationException(
                "Resource does not support the action " + name);
    }

    // The facade generator will ensure we only ever pass in an
    // appropriately-typed extractor object.
    @SuppressWarnings("unchecked")
    ResultCapture<Object> erasedExtractor =
            (ResultCapture<Object>) extractor;

    return ActionUtils.perform(this, action, request, erasedExtractor);
}
项目:aws-sdk-java-resources    文件:ServiceImpl.java   
public ActionResult performAction(
        String name,
        AmazonWebServiceRequest request,
        ResultCapture<?> extractor) {

    ActionModel action = model.getAction(name);
    if (action == null) {
        throw new UnsupportedOperationException(
                "Service does not support the action " + name);
    }

    // The facade generator will ensure we only ever pass in an
    // appropriately-typed extractor object.
    @SuppressWarnings("unchecked")
    ResultCapture<Object> erasedExtractor =
            (ResultCapture<Object>) extractor;

    return ActionUtils.perform(this, action, request, erasedExtractor);
}
项目:cloudwatch-logback-appender    文件:CloudWatchAppender.java   
/**
 * This is a hack to work around the problems that were introduced when the appender was compiled with AWS SDK
 * version 1.9 or 1.10 but the user was running with version 1.11.
 * 
 * The problem was that the createLogStream() method added a return object somewhere between 1.10 and 1.11 which
 * broke backwards compatibility and the applications would throw NoSuchMethodError. Using reflection causes the
 * linkage to be weaker and seems to work.
 */
private void callLogClientMethod(String methodName, AmazonWebServiceRequest arg) {
    try {
        Method method = awsLogsClient.getClass().getMethod(methodName, arg.getClass());
        method.invoke(awsLogsClient, arg);
        logInfo("Created: " + arg);
    } catch (Exception e) {
        logError("Problems creating: " + arg, e);
    }
}
项目:circus-train    文件:CounterBasedRetryCondition.java   
@Override
public boolean shouldRetry(
    AmazonWebServiceRequest originalRequest,
    AmazonClientException exception,
    int retriesAttempted) {
  LOG.debug("Exception caught during upload, retries attempted = {} out of {}", retriesAttempted, maxErrorRetry,
      exception);
  return retriesAttempted <= maxErrorRetry;
}
项目:circus-train    文件:ExponentialBackoffStrategy.java   
@Override
public long delayBeforeNextRetry(
    AmazonWebServiceRequest originalRequest,
    AmazonClientException exception,
    int retriesAttempted) {
  long backoffDelay = retriesAttempted * errorRetryDelay;
  LOG.debug("Exception caught during upload, retries attempted = {}, will retry in {} ms", retriesAttempted,
      backoffDelay, exception);
  return backoffDelay;
}
项目:ibm-cos-sdk-java    文件:JsonProtocolMarshaller.java   
private DefaultRequest<OrigRequest> createRequest(OperationInfo operationInfo, OrigRequest originalRequest) {
    if (originalRequest instanceof AmazonWebServiceRequest) {
        return new DefaultRequest<OrigRequest>((AmazonWebServiceRequest) originalRequest, operationInfo.serviceName());
    } else {
        return new DefaultRequest<OrigRequest>(operationInfo.serviceName());
    }
}
项目:ibm-cos-sdk-java    文件:AwsResponseHandlerAdapter.java   
@Override
public T handle(HttpResponse response) throws Exception {
    final AmazonWebServiceResponse<T> awsResponse = delegate.handle(response);

    if (awsResponse == null) {
        throw new RuntimeException("Unable to unmarshall response metadata. Response Code: "
                                   + response.getStatusCode() + ", Response Text: " +
                                   response.getStatusText());
    }

    AmazonWebServiceRequest userRequest = request.getOriginalRequest();
    if (userRequest.getCloneRoot() != null) {
        userRequest = userRequest.getCloneRoot();
    }
    responseMetadataCache.add(userRequest, awsResponse.getResponseMetadata());
    final String awsRequestId = awsResponse.getRequestId();

    if (requestLog.isDebugEnabled()) {
        requestLog
                .debug("Received successful response: " + response.getStatusCode() +
                       ", AWS Request ID: " + awsRequestId);
    }

    if (!logHeaderRequestId(response)) {
        // Logs the AWS request ID extracted from the payload if
        // it is not available from the response header.
        logResponseRequestId(awsRequestId);
    }
    awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSRequestID, awsRequestId);
    return fillInResponseMetadata(awsResponse, response);
}
项目:ibm-cos-sdk-java    文件:ClientHandlerImpl.java   
/**
 * Runs the {@code beforeMarshalling} method of any {@code RequestHandler2}s associated with
 * this client.
 *
 * @param request the request passed in from the user
 * @return The (possibly different) request to marshall
 */
@SuppressWarnings("unchecked")
protected final <T extends AmazonWebServiceRequest> T beforeMarshalling(T request) {
    T local = request;
    for (RequestHandler2 handler : requestHandler2s) {
        local = (T) handler.beforeMarshalling(local);
    }
    return local;
}
项目:ibm-cos-sdk-java    文件:ProgressInputStream.java   
/**
 * Returns an input stream for request progress tracking purposes. If request/response progress
 * tracking is not enabled, this method simply return the given input stream as is.
 *
 * @param is the request content input stream
 * @deprecated
 */
@Deprecated
public static InputStream inputStreamForRequest(InputStream is,
        AmazonWebServiceRequest req) {
    return req == null
         ? is
         : inputStreamForRequest(is, req.getGeneralProgressListener());
}
项目:ibm-cos-sdk-java    文件:StackedRequestHandler.java   
@Override
public AmazonWebServiceRequest beforeExecution(AmazonWebServiceRequest origRequest) {
    AmazonWebServiceRequest toReturn = origRequest;
    for (RequestHandler2 handler : inOrderRequestHandlers) {
        toReturn = handler.beforeExecution(toReturn);
    }
    return toReturn;
}
项目:ibm-cos-sdk-java    文件:StackedRequestHandler.java   
@Override
public AmazonWebServiceRequest beforeMarshalling(AmazonWebServiceRequest origRequest) {
    AmazonWebServiceRequest toReturn = origRequest;
    for (RequestHandler2 handler : inOrderRequestHandlers) {
        toReturn = handler.beforeMarshalling(toReturn);
    }
    return toReturn;
}
项目:ibm-cos-sdk-java    文件:CredentialUtils.java   
/**
 *  Returns the credentials provider that will be used to fetch the
 *  credentials when signing the request. Request specific credentials
 *  takes precedence over the credentials/credentials provider set in the
 *  client.
 */
public static AWSCredentialsProvider getCredentialsProvider(
        AmazonWebServiceRequest req,
        AWSCredentialsProvider base) {

    if (req != null && req.getRequestCredentialsProvider() != null) {
        return req.getRequestCredentialsProvider();
    }
    return base;
}
项目:ibm-cos-sdk-java    文件:RetryPolicyAdapter.java   
@Override
public long computeDelayBeforeNextRetry(RetryPolicyContext context) {
    return legacyRetryPolicy.getBackoffStrategy().delayBeforeNextRetry(
            (AmazonWebServiceRequest) context.originalRequest(),
            (AmazonClientException) context.exception(),
            context.retriesAttempted());
}
项目:ibm-cos-sdk-java    文件:RetryPolicyAdapter.java   
@Override
public boolean shouldRetry(RetryPolicyContext context) {
    if (context.retriesAttempted() >= getMaxErrorRetry()) {
        return false;
    }
    return legacyRetryPolicy.getRetryCondition().shouldRetry(
            (AmazonWebServiceRequest) context.originalRequest(),
            (AmazonClientException) context.exception(),
            context.retriesAttempted());
}
项目:ibm-cos-sdk-java    文件:PredefinedRetryPolicies.java   
@Override
public boolean shouldRetry(AmazonWebServiceRequest originalRequest,
                           AmazonClientException exception,
                           int retriesAttempted) {
    // Always retry on client exceptions caused by IOException
    if (exception.getCause() instanceof IOException) return true;

    // Only retry on a subset of service exceptions
    if (exception instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException)exception;

        /*
         * For 500 internal server errors and 503 service
         * unavailable errors, we want to retry, but we need to use
         * an exponential back-off strategy so that we don't overload
         * a server with a flood of retries.
         */
        if (RetryUtils.isRetryableServiceException(ase)) return true;

        /*
         * Throttling is reported as a 400 error from newer services. To try
         * and smooth out an occasional throttling error, we'll pause and
         * retry, hoping that the pause is long enough for the request to
         * get through the next time.
         */
        if (RetryUtils.isThrottlingException(ase)) return true;

        /*
         * Clock skew exception. If it is then we will get the time offset
         * between the device time and the server time to set the clock skew
         * and then retry the request.
         */
        if (RetryUtils.isClockSkewError(ase)) return true;
    }

    return false;
}
项目:ibm-cos-sdk-java    文件:V2CompatibleBackoffStrategyAdapter.java   
@Override
public long delayBeforeNextRetry(AmazonWebServiceRequest originalRequest,
                                 AmazonClientException exception,
                                 int retriesAttempted) {
    return computeDelayBeforeNextRetry(RetryPolicyContext.builder()
                                        .originalRequest(originalRequest)
                                        .exception(exception)
                                        .retriesAttempted(retriesAttempted)
                                        .build());
}
项目:ibm-cos-sdk-java    文件:AmazonWebServiceRequestAdapterTest.java   
@Test
public void timeoutsSetInBaseRequest_AreAdaptedToNonNullIntegers() {
    AmazonWebServiceRequest request = new EmptyAmazonWebServiceRequest();
    request.setSdkRequestTimeout(1000);
    request.setSdkClientExecutionTimeout(4000);
    AmazonWebServiceRequestAdapter adapter = new AmazonWebServiceRequestAdapter(request);

    assertEquals(Integer.valueOf(1000), adapter.getRequestTimeout());
    assertEquals(Integer.valueOf(4000), adapter.getClientExecutionTimeout());
}
项目:ibm-cos-sdk-java    文件:AmazonWebServiceRequestAdapterTest.java   
@Test
public void customHeadersSetInBaseRequest_AreAdaptedToMap() {
    AmazonWebServiceRequest request = new EmptyAmazonWebServiceRequest();
    request.putCustomRequestHeader("FooHeader", "FooValue");
    request.putCustomRequestHeader("BarHeader", "BarValue");
    AmazonWebServiceRequestAdapter adapter = new AmazonWebServiceRequestAdapter(request);

    assertThat(adapter.getCustomRequestHeaders(), hasEntry("FooHeader", "FooValue"));
    assertThat(adapter.getCustomRequestHeaders(), hasEntry("BarHeader", "BarValue"));
}
项目:ibm-cos-sdk-java    文件:AmazonWebServiceRequestAdapterTest.java   
@Test
public void customQueryParamsSetInBaseRequest_AreAdaptedToMap() {
    AmazonWebServiceRequest request = new EmptyAmazonWebServiceRequest();
    request.putCustomQueryParameter("FooParam", "FooValue");
    request.putCustomQueryParameter("BarParam", "BarValue");
    AmazonWebServiceRequestAdapter adapter = new AmazonWebServiceRequestAdapter(request);

    final Map<String, List<String>> params = adapter.getCustomQueryParameters();
    assertThat(params, hasEntry("FooParam", Arrays.asList("FooValue")));
    assertThat(params, hasEntry("BarParam", Arrays.asList("BarValue")));
}
项目:ibm-cos-sdk-java    文件:AmazonWebServiceRequestAdapterTest.java   
@Test
public void multipleValuesForSameQueryParamSet_IsAdaptedToMap() {
    AmazonWebServiceRequest request = new EmptyAmazonWebServiceRequest();
    request.putCustomQueryParameter("FooParam", "valOne");
    request.putCustomQueryParameter("FooParam", "valTwo");
    AmazonWebServiceRequestAdapter adapter = new AmazonWebServiceRequestAdapter(request);
    final Map<String, List<String>> params = adapter.getCustomQueryParameters();
    assertThat(params, hasEntry("FooParam", Arrays.asList("valOne", "valTwo")));
}
项目:ibm-cos-sdk-java    文件:ResponseMetadataCacheTest.java   
/** Tests that the cache correctly evicts the oldest entries.  */
@Test
public void testEviction() {
    ResponseMetadataCache cache = new ResponseMetadataCache(3);

    AmazonWebServiceRequest key1 = new TestRequest();
    AmazonWebServiceRequest key2 = new TestRequest();
    AmazonWebServiceRequest key3 = new TestRequest();
    AmazonWebServiceRequest key4 = new TestRequest();
    ResponseMetadata metadata1 = newResponseMetadata();
    ResponseMetadata metadata2 = newResponseMetadata();
    ResponseMetadata metadata3 = newResponseMetadata();
    ResponseMetadata metadata4 = newResponseMetadata();

    // Fill the cache
    cache.add(key1, metadata1);
    cache.add(key2, metadata2);
    cache.add(key3, metadata3);

    // Verify all entries are still there
    assertEquals(metadata1, cache.get(key1));
    assertEquals(metadata2, cache.get(key2));
    assertEquals(metadata3, cache.get(key3));

    // Add another and make sure the oldest is evicted
    cache.add(key4, metadata4);
    assertNull(cache.get(key1));
    assertEquals(metadata2, cache.get(key2));
    assertEquals(metadata3, cache.get(key3));
    assertEquals(metadata4, cache.get(key4));
}
项目:ibm-cos-sdk-java    文件:ResponseMetadataCacheTest.java   
/** Tests that the cache works correctly with size=0  */
@Test
public void TestEmpty() {
    ResponseMetadataCache cache = new ResponseMetadataCache(0);

    AmazonWebServiceRequest key = new TestRequest();
    ResponseMetadata metadata = newResponseMetadata();
    // Add item to the cache, it should be immediately evicted.
    cache.add(key, metadata);

    // get should return null
    assertNull(cache.get(key));
}
项目:ibm-cos-sdk-java    文件:CredentialUtilsTest.java   
@Test
public void base_credentials_returned_when_no_request_credentials_is_present() {
    final String awsAccessKeyId = "foo";
    final String awsSecretAccessKey = "bar";
    final StaticCredentialsProvider base = new StaticCredentialsProvider
            (new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey));

    AWSCredentialsProvider actual = CredentialUtils
            .getCredentialsProvider((AmazonWebServiceRequest) null, base);
    Assert.assertThat(actual, Matchers.instanceOf(StaticCredentialsProvider
                                                          .class));
    assertEquals(awsAccessKeyId, actual.getCredentials().getAWSAccessKeyId());
    assertEquals(awsSecretAccessKey, actual.getCredentials().getAWSSecretKey());
}
项目:ibm-cos-sdk-java    文件:ClientConfigurationMaxErrorRetryTest.java   
/**
 * -- Explicitly set maxErrorRetry in ClientConfiguration level;
 * -- Custom RetryPolicy's that want to override such setting.
 */
@Test
public void testRetryPolicyLevelMaxErrorRetry() {
    // This should be ignored
    clientConfiguration.setMaxErrorRetry(random.nextInt(3));

    // A custom policy that doesn't honor the ClientConfig level maxErrorRetry
    int RETRY_POLICY_LEVEL_MAX_ERROR_RETRY = 5;
    clientConfiguration.setRetryPolicy(new RetryPolicy(null, null, RETRY_POLICY_LEVEL_MAX_ERROR_RETRY, false));
    testActualRetries(RETRY_POLICY_LEVEL_MAX_ERROR_RETRY);

    // A custom policy that "honors" the ClientConfig level maxErrorRetry,
    // but actually denies any retry in its condition.
    clientConfiguration.setRetryPolicy(new RetryPolicy(
            new RetryPolicy.RetryCondition() {

                @Override
                public boolean shouldRetry(
                        AmazonWebServiceRequest originalRequest,
                        AmazonClientException exception,
                        int retriesAttempted) {
                    return false;
                }
            }, null, RETRY_POLICY_LEVEL_MAX_ERROR_RETRY, true)
    );
    // No retry is expected
    testActualRetries(0);
}
项目:ibm-cos-sdk-java    文件:RetryPolicyContexts.java   
public static RetryPolicyContext fromLegacy(AmazonClientException exception,
                                            AmazonWebServiceRequest origRequest,
                                            int retriesAttempted) {
    return RetryPolicyContext.builder()
            .exception(exception)
            .originalRequest(origRequest)
            .retriesAttempted(retriesAttempted)
            .build();
}
项目:ibm-cos-sdk-java    文件:RetryPolicyAdapterTest.java   
@Test
public void computeDelayBeforeNextRetry_DelegatesToLegacyPolicy() {
    final RetryPolicyContext context = RetryPolicyContexts.LEGACY;
    adapter.computeDelayBeforeNextRetry(context);

    verify(backoffStrategy).delayBeforeNextRetry(
            eq((AmazonWebServiceRequest) context.originalRequest()),
            eq((AmazonClientException) context.exception()),
            eq(context.retriesAttempted()));
}
项目:ibm-cos-sdk-java    文件:RetryPolicyAdapterTest.java   
@Test
public void shouldRetry_MaxErrorInClientConfigHonored_DoesNotUseMaxErrorInPolicy() {
    when(retryCondition.shouldRetry(any(AmazonWebServiceRequest.class), any(AmazonClientException.class), anyInt()))
            .thenReturn(true);
    legacyPolicy = new RetryPolicy(retryCondition, backoffStrategy, 3, true);
    adapter = new RetryPolicyAdapter(legacyPolicy, clientConfiguration);
    assertTrue(adapter.shouldRetry(RetryPolicyContexts.withRetriesAttempted(3)));
    assertFalse(adapter.shouldRetry(RetryPolicyContexts.withRetriesAttempted(10)));
}
项目:ibm-cos-sdk-java    文件:RetryPolicyAdapterTest.java   
@Test
public void shouldRetry_MaxErrorNotExceeded_DelegatesToLegacyRetryCondition() {
    final RetryPolicyContext context = RetryPolicyContexts.LEGACY;
    adapter.shouldRetry(context);

    verify(retryCondition).shouldRetry(
            eq((AmazonWebServiceRequest) context.originalRequest()),
            eq((AmazonClientException) context.exception()),
            eq(context.retriesAttempted()));
}
项目:ibm-cos-sdk-java    文件:RetryPolicyTestBase.java   
@SuppressWarnings("rawtypes")
public static Request<?> getSampleRequestWithRepeatableContent(AmazonWebServiceRequest amazonWebServiceRequest) {
    DefaultRequest<?> request = new DefaultRequest(
            amazonWebServiceRequest, "non-existent-service");
    request.setEndpoint(URI.create("http://non-existent-service.amazonaws.com"));
    // StringInputStream#markSupported() returns true
    try {
        request.setContent(new StringInputStream("Some content that could be read for multiple times."));
    } catch (UnsupportedEncodingException e) {
        Assert.fail("Unable to set up the request content");
    }
    return request;
}
项目:ibm-cos-sdk-java    文件:RetryPolicyTestBase.java   
@SuppressWarnings("rawtypes")
public static Request<?> getSampleRequestWithNonRepeatableContent(AmazonWebServiceRequest amazonWebServiceRequest) {
    DefaultRequest<?> request = new DefaultRequest(
            amazonWebServiceRequest, "non-existent-service");
    request.setEndpoint(URI.create("http://non-existent-service.amazonaws.com"));
    // NonRepeatableInputStream#markSupported() returns false
    request.setContent(new NonRepeatableInputStream("Some content that could only be read once."));
    return request;
}
项目:ibm-cos-sdk-java    文件:RetryPolicyTestBase.java   
@Override
public boolean shouldRetry(AmazonWebServiceRequest originalRequest,
                           AmazonClientException exception,
                           int retriesAttempted) {
    collect(originalRequest, exception, retriesAttempted);
    return true;
}
项目:ibm-cos-sdk-java    文件:RetryPolicyTestBase.java   
@Override
public long delayBeforeNextRetry(AmazonWebServiceRequest originalRequest,
                                 AmazonClientException exception,
                                 int retriesAttempted) {
    collect(originalRequest, exception, retriesAttempted);
    return 0; // immediately retry to speed-up the test
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
/**
 * Sets the access control headers for the request given.
 */
private static void addAclHeaders(Request<? extends AmazonWebServiceRequest> request, AccessControlList acl) {
    List<Grant> grants = acl.getGrantsAsList();
    Map<Permission, Collection<Grantee>> grantsByPermission = new HashMap<Permission, Collection<Grantee>>();
    for ( Grant grant : grants ) {
        if ( !grantsByPermission.containsKey(grant.getPermission()) ) {
            grantsByPermission.put(grant.getPermission(), new LinkedList<Grantee>());
        }
        grantsByPermission.get(grant.getPermission()).add(grant.getGrantee());
    }
    for ( Permission permission : Permission.values() ) {
        if ( grantsByPermission.containsKey(permission) ) {
            Collection<Grantee> grantees = grantsByPermission.get(permission);
            boolean seenOne = false;
            StringBuilder granteeString = new StringBuilder();
            for ( Grantee grantee : grantees ) {
                if ( !seenOne )
                    seenOne = true;
                else
                    granteeString.append(", ");
                granteeString.append(grantee.getTypeIdentifier()).append("=").append("\"")
                        .append(grantee.getIdentifier()).append("\"");
            }
            request.addHeader(permission.getHeaderName(), granteeString.toString());
        }
    }
}
项目:ibm-cos-sdk-java    文件:ContentCryptoMaterial.java   
/**
 * Recreates a new content crypto material from the current material given a
 * new KEK material-descriptions. The purpose is to re-encrypt the CEK under
 * a different KEK.
 *
 * Note network calls are involved if the CEK has been or is to be protected
 * by KMS.
 *
 * @param newKEKMatDesc
 *            material descriptions for the new KEK; never null
 * @param accessor
 *            used to retrieve the KEK given the corresponding material
 *            description
 * @param targetScheme
 *            the target crypto scheme to be used for key wrapping, etc.
 * @param p
 *            optional security provider; null means to use the default.
 * @throws SecurityException
 *             if the old and new material description are the same; or if
 *             the old and new KEK are the same
 */
ContentCryptoMaterial recreate(Map<String, String> newKEKMatDesc,
                               EncryptionMaterialsAccessor accessor, S3CryptoScheme targetScheme,
                               Provider p, AWSKMS kms, AmazonWebServiceRequest req) {
    if (!usesKMSKey() && newKEKMatDesc.equals(kekMaterialsDescription)) {
        throw new SecurityException(
            "Material description of the new KEK must differ from the current one");
    }
    final EncryptionMaterials origKEK;
    if (usesKMSKey()) {
        origKEK = new KMSEncryptionMaterials(kekMaterialsDescription.get(
            KMSEncryptionMaterials.CUSTOMER_MASTER_KEY_ID));
    } else {
        origKEK = accessor.getEncryptionMaterials(kekMaterialsDescription);
    }
    EncryptionMaterials newKEK = accessor.getEncryptionMaterials(newKEKMatDesc);
    if (newKEK == null) {
        throw new SdkClientException(
            "No material available with the description "
                + newKEKMatDesc
                + " from the encryption material provider");
    }
    SecretKey cek = cek(encryptedCEK, keyWrappingAlgorithm, origKEK, p,
            getContentCryptoScheme(), kms);
    ContentCryptoMaterial output = create(cek, cipherLite.getIV(), newKEK,
            getContentCryptoScheme(),  // must use same content crypto scheme
            targetScheme,
            p, kms, req);
    if (Arrays.equals(output.encryptedCEK, encryptedCEK)) {
        throw new SecurityException(
            "The new KEK must differ from the original");
    }
    return output;
}