Java Code Examples for software.amazon.awssdk.core.exception.SdkClientException#create()

The following examples show how to use software.amazon.awssdk.core.exception.SdkClientException#create() . 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: DefaultServiceEndpointBuilder.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public URI getServiceEndpoint() {
    ServiceMetadata serviceMetadata = ServiceMetadata.of(serviceName)
                                                     .reconfigure(c -> c.profileFile(() -> profileFile)
                                                                        .profileName(profileName));
    URI endpoint = addProtocolToServiceEndpoint(serviceMetadata.endpointFor(region));

    if (endpoint.getHost() == null) {
        String error = "Configured region (" + region + ") resulted in an invalid URI: " + endpoint;

        List<Region> exampleRegions = serviceMetadata.regions();
        if (!exampleRegions.isEmpty()) {
            error += " Valid region examples: " + exampleRegions;
        }

        throw SdkClientException.create(error);
    }

    return endpoint;
}
 
Example 2
Source File: EnvironmentAwsCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
        throw SdkClientException.create(
                "Unable to load AWS credentials from environment "
                        + "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and "
                        + SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null
            ? AwsBasicCredentials.create(accessKey, secretKey)
            : AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
 
Example 3
Source File: EndpointAddressInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                        ExecutionAttributes executionAttributes) {
    SdkHttpRequest request = context.httpRequest();

    if (!request.headers().containsKey(X_AMZ_ACCOUNT_ID)) {
        throw SdkClientException.create("Account ID must be specified for all requests");
    }

    String accountId = request.headers().get(X_AMZ_ACCOUNT_ID).get(0);

    S3ControlConfiguration config = (S3ControlConfiguration) executionAttributes.getAttribute(
        AwsSignerExecutionAttribute.SERVICE_CONFIG);

    String host = resolveHost(request, accountId, config);

    return request.toBuilder()
                  .host(host)
                  .build();
}
 
Example 4
Source File: ChecksumsEnabledValidator.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Client side validation for {@link PutObjectRequest}
 *
 * @param response the response
 * @param executionAttributes the execution attributes
 */
public static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes) {
    SdkChecksum checksum = executionAttributes.getAttribute(CHECKSUM);

    if (response.eTag() != null) {
        String contentMd5 = BinaryUtils.toBase64(checksum.getChecksumBytes());
        byte[] digest = BinaryUtils.fromBase64(contentMd5);
        byte[] ssHash = Base16Lower.decode(response.eTag().replace("\"", ""));

        if (!Arrays.equals(digest, ssHash)) {
            throw SdkClientException.create(
                String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s",
                              BinaryUtils.toHex(digest), BinaryUtils.toHex(ssHash)));
        }
    }
}
 
Example 5
Source File: JsonDomParser.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private SdkJsonNode parseToken(JsonParser parser, JsonToken token) throws IOException {
    if (token == null) {
        return null;
    }
    switch (token) {
        case VALUE_EMBEDDED_OBJECT:
            return SdkEmbeddedObject.create(parser.getEmbeddedObject());
        case VALUE_STRING:
            return SdkScalarNode.create(parser.getText());
        case VALUE_FALSE:
            return SdkScalarNode.create("false");
        case VALUE_TRUE:
            return SdkScalarNode.create("true");
        case VALUE_NULL:
            return SdkNullNode.instance();
        case VALUE_NUMBER_FLOAT:
        case VALUE_NUMBER_INT:
            return SdkScalarNode.create(parser.getNumberValue().toString());
        case START_OBJECT:
            return parseObject(parser);
        case START_ARRAY:
            return parseArray(parser);
        default:
            throw SdkClientException.create("Unexpected JSON token - " + token);
    }
}
 
Example 6
Source File: AbstractStreamingRequestMarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * This method will run certain validations for content-length and add
 * additional headers (like Transfer-Encoding) if necessary.
 *
 * If requiresLength and transferEncoding is not set to true and Content Length is missing,
 * SDK is not required to calculate the Content-Length and delegate that behavior to the underlying http client.
 *
 * @param marshalled A mutable builder for {@link SdkHttpFullRequest} representing a HTTP request.
 * @param contentLength Optional of content length
 * @param requiresLength True if Content-Length header is required on the request
 * @param transferEncoding True if "Transfer-Encoding: chunked" header should be set on request
 * @param useHttp2 True if the operation uses http2
 */
protected final void addHeaders(SdkHttpFullRequest.Builder marshalled,
                                Optional<Long> contentLength,
                                boolean requiresLength,
                                boolean transferEncoding,
                                boolean useHttp2) {

    if (marshalled.firstMatchingHeader(CONTENT_LENGTH).isPresent()) {
        return;
    }

    if (contentLength.isPresent()) {
        marshalled.putHeader(CONTENT_LENGTH, Long.toString(contentLength.get()));
        return;
    }

    if (requiresLength) {
        throw SdkClientException.create("This API requires Content-Length header to be set. "
                                        + "Please set the content length on the RequestBody.");
    } else if (transferEncoding && !useHttp2) {
        marshalled.putHeader(TRANSFER_ENCODING, CHUNKED);
    }
}
 
Example 7
Source File: InstantToString.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(Instant val, SdkField<Instant> sdkField) {
    if (val == null) {
        return null;
    }
    TimestampFormatTrait.Format format =
        sdkField.getOptionalTrait(TimestampFormatTrait.class)
                .map(TimestampFormatTrait::format)
                .orElseGet(() -> getDefaultTimestampFormat(sdkField.location(), defaultFormats));
    switch (format) {
        case ISO_8601:
            return DateUtils.formatIso8601Date(val);
        case RFC_822:
            return DateUtils.formatRfc1123Date(val);
        case UNIX_TIMESTAMP:
            return DateUtils.formatUnixTimestampInstant(val);
        default:
            throw SdkClientException.create("Unsupported timestamp format - " + format);
    }
}
 
Example 8
Source File: StringToInstant.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Instant convert(String value, SdkField<Instant> field) {
    if (value == null) {
        return null;
    }
    TimestampFormatTrait.Format format = resolveTimestampFormat(field);
    switch (format) {
        case ISO_8601:
            return DateUtils.parseIso8601Date(value);
        case UNIX_TIMESTAMP:
            return safeParseDate(DateUtils::parseUnixTimestampInstant).apply(value);
        case UNIX_TIMESTAMP_MILLIS:
            return safeParseDate(DateUtils::parseUnixTimestampMillisInstant).apply(value);
        case RFC_822:
            return DateUtils.parseRfc1123Date(value);
        default:
            throw SdkClientException.create("Unrecognized timestamp format - " + format);
    }
}
 
Example 9
Source File: LocalS3Client.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Override
public GetObjectResponse getObject(final GetObjectRequest getObjectRequest,
                                   final Path filePath) throws S3Exception {
    final Map<String, BucketItem> bucketItemMap = bucketsWithContents.get(getObjectRequest.bucket());
    final BucketItem bucketItem = bucketItemMap.get(getObjectRequest.key());

    try {
        Files.write(filePath, bucketItem.getData());
    } catch (IOException e) {
        throw SdkClientException.create("", e);
    }

    return GetObjectResponse.builder().build();
}
 
Example 10
Source File: AsyncClientHandlerExceptionTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void streamingRequest_marshallingException_shouldInvokeExceptionOccurred() throws Exception {
    AsyncResponseTransformer asyncResponseTransformer = mock(AsyncResponseTransformer.class);
    CompletableFuture<?> future = new CompletableFuture<>();
    when(asyncResponseTransformer.prepare()).thenReturn(future);

    SdkClientException exception = SdkClientException.create("Could not handle response");
    when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception);

    doVerify(() -> clientHandler.execute(executionParams, asyncResponseTransformer), exception);

    verify(asyncResponseTransformer, times(1)).prepare();
    verify(asyncResponseTransformer, times(1)).exceptionOccurred(exception);
}
 
Example 11
Source File: AsyncClientHandlerTransformerVerificationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void marshallerThrowsException_shouldTriggerExceptionOccurred() {
    SdkClientException exception = SdkClientException.create("Could not handle response");
    when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception);
    AtomicBoolean exceptionOccurred = new AtomicBoolean(false);
    executeAndWaitError(new TestTransformer<SdkResponse, Void>(){
        @Override
        public void exceptionOccurred(Throwable error) {
            exceptionOccurred.set(true);
            super.exceptionOccurred(error);
        }
    });

    assertThat(exceptionOccurred.get()).isTrue();
}
 
Example 12
Source File: RetryableStageHelper.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Update the {@link #getLastException()} value for this helper. This will be used to determine whether the request should
 * be retried.
 */
public void setLastException(Throwable lastException) {
    if (lastException instanceof CompletionException) {
        setLastException(lastException.getCause());
    } else if (lastException instanceof SdkException) {
        this.lastException = (SdkException) lastException;
    } else {
        this.lastException = SdkClientException.create("Unable to execute HTTP request: " + lastException.getMessage(),
                                                       lastException);
    }
}
 
Example 13
Source File: StringToInstant.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private TimestampFormatTrait.Format resolveTimestampFormat(SdkField<Instant> field) {
    TimestampFormatTrait trait = field.getTrait(TimestampFormatTrait.class);
    if (trait == null) {
        TimestampFormatTrait.Format format = defaultFormats.get(field.location());
        if (format == null) {
            throw SdkClientException.create(
                String.format("Timestamps are not supported for this location (%s)", field.location()));
        }
        return format;
    } else {
        return trait.format();
    }
}
 
Example 14
Source File: AbstractMarshallingRegistry.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Get a registered marshaller/unmarshaller by location and type.
 *
 * @param marshallLocation Location of registered (un)marshaller.
 * @param marshallingType Type of registered (un)marshaller.
 * @return Registered marshaller/unmarshaller.
 * @throws SdkClientException if no marshaller/unmarshaller is registered for the given location and type.
 */
protected Object get(MarshallLocation marshallLocation, MarshallingType<?> marshallingType) {
    Map<MarshallingType, Object> byLocation = registry.get(marshallLocation);
    if (byLocation == null) {
        throw SdkClientException.create("No marshaller/unmarshaller registered for location " + marshallLocation.name());
    }
    Object registered = byLocation.get(marshallingType);
    if (registered == null) {
        throw SdkClientException.create(String.format("No marshaller/unmarshaller of type %s registered for location %s.",
                                                      marshallingType,
                                                      marshallLocation.name()));
    }
    return registered;
}
 
Example 15
Source File: InstantToString.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private TimestampFormatTrait.Format getDefaultTimestampFormat(
    MarshallLocation location, Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {

    TimestampFormatTrait.Format format = defaultFormats.get(location);
    if (format == null) {
        throw SdkClientException.create("No default timestamp marshaller found for location - " + location);
    }
    return format;
}
 
Example 16
Source File: XmlDomParser.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static XmlElement parse(InputStream inputStream) {
    try {
        XMLEventReader reader = FACTORY.get().createXMLEventReader(inputStream);
        XMLEvent nextEvent;
        // Skip ahead to the first start element
        do {
            nextEvent = reader.nextEvent();
        } while (reader.hasNext() && !nextEvent.isStartElement());
        return parseElement(nextEvent.asStartElement(), reader);
    } catch (XMLStreamException e) {
        throw SdkClientException.create("Could not parse XML response.", e);
    }
}
 
Example 17
Source File: XmlElement.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a single child element by tag name. If more than one element is found then this method will throw an exception.
 *
 * @param tagName Tag name of element to get.
 * @return XmlElement with the matching tag name or null if no element exists.
 * @throws SdkClientException If more than one element with the given tag name is found.
 */
public XmlElement getElementByName(String tagName) {
    List<XmlElement> elementsByName = getElementsByName(tagName);
    if (elementsByName.size() > 1) {
        throw SdkClientException.create(
            String.format("Did not expect more than one element with the name %s in the XML event %s",
                          tagName, this.elementName));
    }
    return elementsByName.size() == 1 ? elementsByName.get(0) : null;
}
 
Example 18
Source File: S3AccessPointBuilder.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an endpoint URI with no path that maps to the Access Point information stored in this builder.
 */
public URI toUri() {
    validateHostnameCompliant(accountId, "accountId");
    validateHostnameCompliant(accessPointName, "accessPointName");

    String dualStackSegment = Boolean.TRUE.equals(dualstackEnabled) ? ".dualstack" : "";
    String uriString = String.format("%s://%s-%s.s3-accesspoint%s.%s.%s", protocol, urlEncode(accessPointName),
                                     accountId, dualStackSegment, region, domain);
    URI uri = URI.create(uriString);
    if (uri.getHost() == null) {
        throw SdkClientException.create("ARN region (" + region + ") resulted in an invalid URI:" + uri);
    }
    return uri;
}
 
Example 19
Source File: LocalS3Client.java    From synapse with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ResponseInputStream<GetObjectResponse> getObject(final GetObjectRequest getObjectRequest) throws S3Exception {
    final Map<String, BucketItem> bucketItemMap = bucketsWithContents.get(getObjectRequest.bucket());
    final BucketItem bucketItem = bucketItemMap.get(getObjectRequest.key());
    try {
        return new ResponseInputStream<>(GetObjectResponse.builder().build(), toAbortableInputStream(bucketItem));
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
        throw SdkClientException.create("", e);
    }

}
 
Example 20
Source File: AwsS3BucketScanner.java    From clouditor with Apache License 2.0 4 votes vote down vote up
@Override
public Asset transform(Bucket bucket) throws ScanException {
  var map = super.transform(bucket);

  this.api.listBuckets(ListBucketsRequest.builder().build());

  var client = this.api;
  try {
    this.api.headBucket(HeadBucketRequest.builder().bucket(bucket.name()).build());
  } catch (S3Exception ex) {
    var o = ex.awsErrorDetails().sdkHttpResponse().firstMatchingHeader("x-amz-bucket-region");

    if (o.isPresent()) {
      var region = o.get();

      // needed, as long as https://github.com/aws/aws-sdk-java-v2/issues/52 is not fixed
      LOGGER.info("Switching to region-specific S3 client ({})", region);

      var account = PersistenceManager.getInstance().getById(AwsAccount.class, "AWS");

      if (account == null) {
        throw SdkClientException.create("AWS account not configured");
      }

      client =
          regionClients.getOrDefault(
              region,
              S3Client.builder().credentialsProvider(account).region(Region.of(region)).build());
    }
  }

  enrich(
      map,
      "bucketEncryption",
      client::getBucketEncryption,
      GetBucketEncryptionResponse::serverSideEncryptionConfiguration,
      GetBucketEncryptionRequest.builder().bucket(bucket.name()).build());

  enrich(
      map,
      "publicAccessBlockConfiguration",
      client::getPublicAccessBlock,
      GetPublicAccessBlockResponse::publicAccessBlockConfiguration,
      GetPublicAccessBlockRequest.builder().bucket(bucket.name()).build());

  enrich(
      map,
      "bucketReplication",
      client::getBucketReplication,
      GetBucketReplicationResponse::replicationConfiguration,
      GetBucketReplicationRequest.builder().bucket(bucket.name()).build());

  enrichList(
      map,
      "lifecycleConfiguration",
      client::getBucketLifecycleConfiguration,
      GetBucketLifecycleConfigurationResponse::rules,
      GetBucketLifecycleConfigurationRequest.builder().bucket(bucket.name()).build());

  return map;
}