index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/document/DocumentUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.unmarshall.document; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; @SdkInternalApi public class DocumentUnmarshaller implements JsonNodeVisitor<Document> { @Override public Document visitNull() { return Document.fromNull(); } @Override public Document visitBoolean(boolean bool) { return Document.fromBoolean(bool); } @Override public Document visitNumber(String number) { return Document.fromNumber(number); } @Override public Document visitString(String string) { return Document.fromString(string); } @Override public Document visitArray(List<JsonNode> array) { return Document.fromList(array.stream() .map(node -> node.visit(this)) .collect(Collectors.toList())); } @Override public Document visitObject(Map<String, JsonNode> object) { return Document.fromMap(object.entrySet() .stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().visit(this), (left, right) -> left, LinkedHashMap::new))); } @Override public Document visitEmbeddedObject(Object embeddedObject) { throw new UnsupportedOperationException("Embedded objects are not supported within Document types."); } }
2,200
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; /** * Dependencies needed by implementations of {@link JsonMarshaller}. */ @SdkInternalApi public final class JsonMarshallerContext { private final StructuredJsonGenerator jsonGenerator; private final JsonProtocolMarshaller protocolHandler; private final JsonMarshallerRegistry marshallerRegistry; private final SdkHttpFullRequest.Builder request; private JsonMarshallerContext(Builder builder) { this.jsonGenerator = builder.jsonGenerator; this.protocolHandler = builder.protocolHandler; this.marshallerRegistry = builder.marshallerRegistry; this.request = builder.request; } /** * @return StructuredJsonGenerator used to produce the JSON document for a request. */ public StructuredJsonGenerator jsonGenerator() { return jsonGenerator; } /** * @return Implementation of {@link ProtocolMarshaller} that can be used to call back out to marshall structured data (i.e. * dlists of objects). */ public JsonProtocolMarshaller protocolHandler() { return protocolHandler; } /** * @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string * to string). */ public JsonMarshallerRegistry marshallerRegistry() { return marshallerRegistry; } /** * @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params, * modify request URI, etc. */ public SdkHttpFullRequest.Builder request() { return request; } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. */ public void marshall(MarshallLocation marshallLocation, Object val) { marshallerRegistry().getMarshaller(marshallLocation, val).marshall(val, this, null, null); } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. * @param paramName Name of parameter to marshall. */ public <T> void marshall(MarshallLocation marshallLocation, T val, String paramName) { marshallerRegistry().getMarshaller(marshallLocation, val).marshall(val, this, paramName, null); } /** * @return Builder instance to construct a {@link JsonMarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link JsonMarshallerContext}. */ public static final class Builder { private StructuredJsonGenerator jsonGenerator; private JsonProtocolMarshaller protocolHandler; private JsonMarshallerRegistry marshallerRegistry; private SdkHttpFullRequest.Builder request; private Builder() { } public Builder jsonGenerator(StructuredJsonGenerator jsonGenerator) { this.jsonGenerator = jsonGenerator; return this; } public Builder protocolHandler(JsonProtocolMarshaller protocolHandler) { this.protocolHandler = protocolHandler; return this; } public Builder marshallerRegistry(JsonMarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; return this; } public Builder request(SdkHttpFullRequest.Builder request) { this.request = request; return this; } /** * @return An immutable {@link JsonMarshallerContext} object. */ public JsonMarshallerContext build() { return new JsonMarshallerContext(this); } } }
2,201
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/SimpleTypePathMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.PathMarshaller; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class SimpleTypePathMarshaller { public static final JsonMarshaller<String> STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.NON_GREEDY); public static final JsonMarshaller<Integer> INTEGER = new SimplePathMarshaller<>(ValueToStringConverter.FROM_INTEGER, PathMarshaller.NON_GREEDY); public static final JsonMarshaller<Long> LONG = new SimplePathMarshaller<>(ValueToStringConverter.FROM_LONG, PathMarshaller.NON_GREEDY); public static final JsonMarshaller<Short> SHORT = new SimplePathMarshaller<>(ValueToStringConverter.FROM_SHORT, PathMarshaller.NON_GREEDY); /** * Marshallers for Strings bound to a greedy path param. No URL encoding is done on the string * so that it preserves the path structure. */ public static final JsonMarshaller<String> GREEDY_STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.GREEDY); public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); }; private SimpleTypePathMarshaller() { } private static class SimplePathMarshaller<T> implements JsonMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private final PathMarshaller pathMarshaller; private SimplePathMarshaller(ValueToStringConverter.ValueToString<T> converter, PathMarshaller pathMarshaller) { this.converter = converter; this.pathMarshaller = pathMarshaller; } @Override public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().encodedPath( pathMarshaller.marshall(context.request().encodedPath(), paramName, converter.convert(val, sdkField))); } } }
2,202
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/HeaderMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import static software.amazon.awssdk.utils.CollectionUtils.isNullOrEmpty; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.JsonValueTrait; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class HeaderMarshaller { public static final JsonMarshaller<String> STRING = new SimpleHeaderMarshaller<>( (val, field) -> field.containsTrait(JsonValueTrait.class) ? BinaryUtils.toBase64(val.getBytes(StandardCharsets.UTF_8)) : val); public static final JsonMarshaller<Integer> INTEGER = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final JsonMarshaller<Long> LONG = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_LONG); public static final JsonMarshaller<Short> SHORT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final JsonMarshaller<Double> DOUBLE = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final JsonMarshaller<Float> FLOAT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final JsonMarshaller<Boolean> BOOLEAN = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final JsonMarshaller<Instant> INSTANT = new SimpleHeaderMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> { // Null or empty lists cannot be meaningfully (or safely) represented in an HTTP header message since header-fields must // typically have a non-empty field-value. https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 if (isNullOrEmpty(list)) { return; } SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo(); for (Object listValue : list) { if (shouldSkipElement(listValue)) { continue; } JsonMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, listValue); marshaller.marshall(listValue, context, paramName, memberFieldInfo); } }; public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private HeaderMarshaller() { } private static boolean shouldSkipElement(Object element) { return element instanceof String && StringUtils.isBlank((String) element); } private static class SimpleHeaderMarshaller<T> implements JsonMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleHeaderMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().appendHeader(paramName, converter.convert(val, sdkField)); } } }
2,203
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonProtocolMarshallerBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.json.AwsJsonProtocolMetadata; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; /** * Builder to create an appropriate implementation of {@link ProtocolMarshaller} for JSON based services. */ @SdkInternalApi public final class JsonProtocolMarshallerBuilder { private URI endpoint; private StructuredJsonGenerator jsonGenerator; private String contentType; private OperationInfo operationInfo; private boolean sendExplicitNullForPayload; private AwsJsonProtocolMetadata protocolMetadata; private JsonProtocolMarshallerBuilder() { } /** * @return New instance of {@link JsonProtocolMarshallerBuilder}. */ public static JsonProtocolMarshallerBuilder create() { return new JsonProtocolMarshallerBuilder(); } /** * @param endpoint Endpoint to set on the marshalled request. * @return This builder for method chaining. */ public JsonProtocolMarshallerBuilder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * Sets the implementation of {@link StructuredJsonGenerator} which allows writing JSON or JSON like (i.e. CBOR and Ion) * data formats. * * @param jsonGenerator Generator to use. * @return This builder for method chaining. */ public JsonProtocolMarshallerBuilder jsonGenerator(StructuredJsonGenerator jsonGenerator) { this.jsonGenerator = jsonGenerator; return this; } /** * @param contentType The content type to set on the marshalled requests. * @return This builder for method chaining. */ public JsonProtocolMarshallerBuilder contentType(String contentType) { this.contentType = contentType; return this; } /** * @param operationInfo Metadata about the operation like URI, HTTP method, etc. * @return This builder for method chaining. */ public JsonProtocolMarshallerBuilder operationInfo(OperationInfo operationInfo) { this.operationInfo = operationInfo; return this; } /** * @param sendExplicitNullForPayload True if an explicit JSON null should be sent as the body when the * payload member is null. See {@link NullAsEmptyBodyProtocolRequestMarshaller}. */ public JsonProtocolMarshallerBuilder sendExplicitNullForPayload(boolean sendExplicitNullForPayload) { this.sendExplicitNullForPayload = sendExplicitNullForPayload; return this; } /** * @param protocolMetadata */ public JsonProtocolMarshallerBuilder protocolMetadata(AwsJsonProtocolMetadata protocolMetadata) { this.protocolMetadata = protocolMetadata; return this; } /** * @return New instance of {@link ProtocolMarshaller}. If {@link #sendExplicitNullForPayload} is true then the marshaller * will be wrapped with {@link NullAsEmptyBodyProtocolRequestMarshaller}. */ public ProtocolMarshaller<SdkHttpFullRequest> build() { ProtocolMarshaller<SdkHttpFullRequest> protocolMarshaller = new JsonProtocolMarshaller(endpoint, jsonGenerator, contentType, operationInfo, protocolMetadata); return sendExplicitNullForPayload ? protocolMarshaller : new NullAsEmptyBodyProtocolRequestMarshaller(protocolMarshaller); } }
2,204
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.Marshaller; /** * Interface to marshall data according to the JSON protocol specification. * * @param <T> Type to marshall. */ @FunctionalInterface @SdkInternalApi public interface JsonMarshaller<T> extends Marshaller<T> { JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { }; /** * Marshall the data into the request. * * @param val Data to marshall (may be null). * @param context Dependencies needed for marshalling. * @param paramName Optional param/field name. May be null in certain situations. */ void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField); }
2,205
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/NullAsEmptyBodyProtocolRequestMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; /** * AWS services expect an empty body when the payload member is null instead of an explicit JSON null. */ @SdkInternalApi public class NullAsEmptyBodyProtocolRequestMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { private final ProtocolMarshaller<SdkHttpFullRequest> delegate; public NullAsEmptyBodyProtocolRequestMarshaller(ProtocolMarshaller<SdkHttpFullRequest> delegate) { this.delegate = delegate; } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { return delegate.marshall(pojo); } }
2,206
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/QueryParamMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class QueryParamMarshaller { public static final JsonMarshaller<String> STRING = new SimpleQueryParamMarshaller<>( ValueToStringConverter.FROM_STRING); public static final JsonMarshaller<Integer> INTEGER = new SimpleQueryParamMarshaller<>( ValueToStringConverter.FROM_INTEGER); public static final JsonMarshaller<Long> LONG = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_LONG); public static final JsonMarshaller<Short> SHORT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final JsonMarshaller<Double> DOUBLE = new SimpleQueryParamMarshaller<>( ValueToStringConverter.FROM_DOUBLE); public static final JsonMarshaller<Float> FLOAT = new SimpleQueryParamMarshaller<>( ValueToStringConverter.FROM_FLOAT); public static final JsonMarshaller<Boolean> BOOLEAN = new SimpleQueryParamMarshaller<>( ValueToStringConverter.FROM_BOOLEAN); public static final JsonMarshaller<Instant> INSTANT = new SimpleQueryParamMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> { for (Object listVal : list) { context.marshall(MarshallLocation.QUERY_PARAM, listVal, paramName); } }; public static final JsonMarshaller<Map<String, ?>> MAP = (val, context, paramName, sdkField) -> { for (Map.Entry<String, ?> mapEntry : val.entrySet()) { context.marshall(MarshallLocation.QUERY_PARAM, mapEntry.getValue(), mapEntry.getKey()); } }; public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private QueryParamMarshaller() { } private static class SimpleQueryParamMarshaller<T> implements JsonMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleQueryParamMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().appendRawQueryParameter(paramName, converter.convert(val, sdkField)); } } }
2,207
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/DocumentTypeJsonMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.VoidDocumentVisitor; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; @SdkInternalApi public class DocumentTypeJsonMarshaller implements VoidDocumentVisitor { private final StructuredJsonGenerator jsonGenerator; public DocumentTypeJsonMarshaller(StructuredJsonGenerator jsonGenerator) { this.jsonGenerator = jsonGenerator; } @Override public void visitNull() { jsonGenerator.writeNull(); } @Override public void visitBoolean(Boolean document) { jsonGenerator.writeValue(document); } @Override public void visitString(String document) { jsonGenerator.writeValue(document); } @Override public void visitNumber(SdkNumber document) { jsonGenerator.writeNumber(document.stringValue()); } @Override public void visitMap(Map<String, Document> documentMap) { jsonGenerator.writeStartObject(); documentMap.entrySet().forEach(entry -> { jsonGenerator.writeFieldName(entry.getKey()); entry.getValue().accept(this); }); jsonGenerator.writeEndObject(); } @Override public void visitList(List<Document> documentList) { jsonGenerator.writeStartArray(); documentList.stream().forEach(document -> document.accept(this)); jsonGenerator.writeEndArray(); } }
2,208
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; /** * Marshaller registry for JSON based protocols. */ @SdkInternalApi public final class JsonMarshallerRegistry extends AbstractMarshallingRegistry { private JsonMarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> JsonMarshaller<T> getMarshaller(MarshallLocation marshallLocation, T val) { return (JsonMarshaller<T>) get(marshallLocation, toMarshallingType(val)); } @SuppressWarnings("unchecked") public <T> JsonMarshaller<Object> getMarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType, Object val) { return (JsonMarshaller<Object>) get(marshallLocation, val == null ? MarshallingType.NULL : marshallingType); } /** * @return Builder instance to construct a {@link JsonMarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link JsonMarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder payloadMarshaller(MarshallingType<T> marshallingType, JsonMarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } public <T> Builder headerMarshaller(MarshallingType<T> marshallingType, JsonMarshaller<T> marshaller) { register(MarshallLocation.HEADER, marshallingType, marshaller); return this; } public <T> Builder queryParamMarshaller(MarshallingType<T> marshallingType, JsonMarshaller<T> marshaller) { register(MarshallLocation.QUERY_PARAM, marshallingType, marshaller); return this; } public <T> Builder pathParamMarshaller(MarshallingType<T> marshallingType, JsonMarshaller<T> marshaller) { register(MarshallLocation.PATH, marshallingType, marshaller); return this; } public <T> Builder greedyPathParamMarshaller(MarshallingType<T> marshallingType, JsonMarshaller<T> marshaller) { register(MarshallLocation.GREEDY_PATH, marshallingType, marshaller); return this; } /** * @return An immutable {@link JsonMarshallerRegistry} object. */ public JsonMarshallerRegistry build() { return new JsonMarshallerRegistry(this); } } }
2,209
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonProtocolMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM; import static software.amazon.awssdk.http.Header.CHUNKED; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.InstantToString; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; import software.amazon.awssdk.protocols.core.ValueToStringConverter.ValueToString; import software.amazon.awssdk.protocols.json.AwsJsonProtocol; import software.amazon.awssdk.protocols.json.AwsJsonProtocolMetadata; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; /** * Implementation of {@link ProtocolMarshaller} for JSON based services. This includes JSON-RPC and REST-JSON. */ @SdkInternalApi public class JsonProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { public static final ValueToString<Instant> INSTANT_VALUE_TO_STRING = InstantToString.create(getDefaultTimestampFormats()); private static final JsonMarshallerRegistry MARSHALLER_REGISTRY = createMarshallerRegistry(); private final URI endpoint; private final StructuredJsonGenerator jsonGenerator; private final SdkHttpFullRequest.Builder request; private final String contentType; private final AwsJsonProtocolMetadata protocolMetadata; private final boolean hasExplicitPayloadMember; private final boolean hasImplicitPayloadMembers; private final boolean hasStreamingInput; private final JsonMarshallerContext marshallerContext; private final boolean hasEventStreamingInput; private final boolean hasEvent; JsonProtocolMarshaller(URI endpoint, StructuredJsonGenerator jsonGenerator, String contentType, OperationInfo operationInfo, AwsJsonProtocolMetadata protocolMetadata) { this.endpoint = endpoint; this.jsonGenerator = jsonGenerator; this.contentType = contentType; this.protocolMetadata = protocolMetadata; this.hasExplicitPayloadMember = operationInfo.hasExplicitPayloadMember(); this.hasImplicitPayloadMembers = operationInfo.hasImplicitPayloadMembers(); this.hasStreamingInput = operationInfo.hasStreamingInput(); this.hasEventStreamingInput = operationInfo.hasEventStreamingInput(); this.hasEvent = operationInfo.hasEvent(); this.request = fillBasicRequestParams(operationInfo); this.marshallerContext = JsonMarshallerContext.builder() .jsonGenerator(jsonGenerator) .marshallerRegistry(MARSHALLER_REGISTRY) .protocolHandler(this) .request(request) .build(); } private static JsonMarshallerRegistry createMarshallerRegistry() { return JsonMarshallerRegistry .builder() .payloadMarshaller(MarshallingType.STRING, SimpleTypeJsonMarshaller.STRING) .payloadMarshaller(MarshallingType.INTEGER, SimpleTypeJsonMarshaller.INTEGER) .payloadMarshaller(MarshallingType.LONG, SimpleTypeJsonMarshaller.LONG) .payloadMarshaller(MarshallingType.SHORT, SimpleTypeJsonMarshaller.SHORT) .payloadMarshaller(MarshallingType.DOUBLE, SimpleTypeJsonMarshaller.DOUBLE) .payloadMarshaller(MarshallingType.FLOAT, SimpleTypeJsonMarshaller.FLOAT) .payloadMarshaller(MarshallingType.BIG_DECIMAL, SimpleTypeJsonMarshaller.BIG_DECIMAL) .payloadMarshaller(MarshallingType.BOOLEAN, SimpleTypeJsonMarshaller.BOOLEAN) .payloadMarshaller(MarshallingType.INSTANT, SimpleTypeJsonMarshaller.INSTANT) .payloadMarshaller(MarshallingType.SDK_BYTES, SimpleTypeJsonMarshaller.SDK_BYTES) .payloadMarshaller(MarshallingType.SDK_POJO, SimpleTypeJsonMarshaller.SDK_POJO) .payloadMarshaller(MarshallingType.LIST, SimpleTypeJsonMarshaller.LIST) .payloadMarshaller(MarshallingType.MAP, SimpleTypeJsonMarshaller.MAP) .payloadMarshaller(MarshallingType.NULL, SimpleTypeJsonMarshaller.NULL) .payloadMarshaller(MarshallingType.DOCUMENT, SimpleTypeJsonMarshaller.DOCUMENT) .headerMarshaller(MarshallingType.STRING, HeaderMarshaller.STRING) .headerMarshaller(MarshallingType.INTEGER, HeaderMarshaller.INTEGER) .headerMarshaller(MarshallingType.LONG, HeaderMarshaller.LONG) .headerMarshaller(MarshallingType.SHORT, HeaderMarshaller.SHORT) .headerMarshaller(MarshallingType.DOUBLE, HeaderMarshaller.DOUBLE) .headerMarshaller(MarshallingType.FLOAT, HeaderMarshaller.FLOAT) .headerMarshaller(MarshallingType.BOOLEAN, HeaderMarshaller.BOOLEAN) .headerMarshaller(MarshallingType.INSTANT, HeaderMarshaller.INSTANT) .headerMarshaller(MarshallingType.LIST, HeaderMarshaller.LIST) .headerMarshaller(MarshallingType.NULL, HeaderMarshaller.NULL) .queryParamMarshaller(MarshallingType.STRING, QueryParamMarshaller.STRING) .queryParamMarshaller(MarshallingType.INTEGER, QueryParamMarshaller.INTEGER) .queryParamMarshaller(MarshallingType.LONG, QueryParamMarshaller.LONG) .queryParamMarshaller(MarshallingType.SHORT, QueryParamMarshaller.SHORT) .queryParamMarshaller(MarshallingType.DOUBLE, QueryParamMarshaller.DOUBLE) .queryParamMarshaller(MarshallingType.FLOAT, QueryParamMarshaller.FLOAT) .queryParamMarshaller(MarshallingType.BOOLEAN, QueryParamMarshaller.BOOLEAN) .queryParamMarshaller(MarshallingType.INSTANT, QueryParamMarshaller.INSTANT) .queryParamMarshaller(MarshallingType.LIST, QueryParamMarshaller.LIST) .queryParamMarshaller(MarshallingType.MAP, QueryParamMarshaller.MAP) .queryParamMarshaller(MarshallingType.NULL, QueryParamMarshaller.NULL) .pathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.STRING) .pathParamMarshaller(MarshallingType.INTEGER, SimpleTypePathMarshaller.INTEGER) .pathParamMarshaller(MarshallingType.LONG, SimpleTypePathMarshaller.LONG) .pathParamMarshaller(MarshallingType.SHORT, SimpleTypePathMarshaller.SHORT) .pathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .greedyPathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.GREEDY_STRING) .greedyPathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .build(); } private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); // TODO the default is supposedly rfc822. See JAVA-2949 // We are using ISO_8601 in v1. Investigate which is the right format formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP); formats.put(MarshallLocation.QUERY_PARAM, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } private SdkHttpFullRequest.Builder fillBasicRequestParams(OperationInfo operationInfo) { return ProtocolUtils.createSdkHttpRequest(operationInfo, endpoint) .applyMutation(b -> { if (operationInfo.operationIdentifier() != null) { b.putHeader("X-Amz-Target", operationInfo.operationIdentifier()); } }); } /** * If there is not an explicit payload member then we need to start the implicit JSON request object. All * members bound to the payload will be added as fields to this object. */ private void startMarshalling() { // Create the implicit request object if needed. if (needTopLevelJsonObject()) { jsonGenerator.writeStartObject(); } } void doMarshall(SdkPojo pojo) { for (SdkField<?> field : pojo.sdkFields()) { Object val = field.getValueOrDefault(pojo); if (isExplicitBinaryPayload(field)) { if (val != null) { request.contentStreamProvider(((SdkBytes) val)::asInputStream); } } else if (isExplicitStringPayload(field)) { if (val != null) { byte[] content = ((String) val).getBytes(StandardCharsets.UTF_8); request.contentStreamProvider(() -> new ByteArrayInputStream(content)); } } else if (isExplicitPayloadMember(field)) { marshallExplicitJsonPayload(field, val); } else { marshallField(field, val); } } } private boolean isExplicitBinaryPayload(SdkField<?> field) { return isExplicitPayloadMember(field) && MarshallingType.SDK_BYTES.equals(field.marshallingType()); } private boolean isExplicitStringPayload(SdkField<?> field) { return isExplicitPayloadMember(field) && MarshallingType.STRING.equals(field.marshallingType()); } private boolean isExplicitPayloadMember(SdkField<?> field) { return field.containsTrait(PayloadTrait.class); } private void marshallExplicitJsonPayload(SdkField<?> field, Object val) { // Explicit JSON payloads are always marshalled as an object, // even if they're null, in which case it's an empty object. jsonGenerator.writeStartObject(); if (val != null) { if (MarshallingType.DOCUMENT.equals(field.marshallingType())) { marshallField(field, val); } else { doMarshall((SdkPojo) val); } } jsonGenerator.writeEndObject(); } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { startMarshalling(); doMarshall(pojo); return finishMarshalling(); } private SdkHttpFullRequest finishMarshalling() { // Content may already be set if the payload is binary data. if (request.contentStreamProvider() == null) { // End the implicit request object if needed. if (needTopLevelJsonObject()) { jsonGenerator.writeEndObject(); } byte[] content = jsonGenerator.getBytes(); if (content != null) { request.contentStreamProvider(() -> new ByteArrayInputStream(content)); if (content.length > 0) { request.putHeader(CONTENT_LENGTH, Integer.toString(content.length)); } } } // We skip setting the default content type if the request is streaming as // content-type is determined based on the body of the stream // TODO: !request.headers().containsKey(CONTENT_TYPE) does not work because request is created from line 77 // and not from the original request if (!request.firstMatchingHeader(CONTENT_TYPE).isPresent() && !hasEvent) { if (hasEventStreamingInput) { AwsJsonProtocol protocol = protocolMetadata.protocol(); if (protocol == AwsJsonProtocol.AWS_JSON) { // For RPC formats, this content type will later be pushed down into the `initial-event` in the body request.putHeader(CONTENT_TYPE, contentType); } else if (protocol == AwsJsonProtocol.REST_JSON) { request.putHeader(CONTENT_TYPE, MIMETYPE_EVENT_STREAM); } else { throw new IllegalArgumentException("Unknown AwsJsonProtocol: " + protocol); } request.removeHeader(CONTENT_LENGTH); request.putHeader(TRANSFER_ENCODING, CHUNKED); } else if (contentType != null && !hasStreamingInput && request.firstMatchingHeader(CONTENT_LENGTH).isPresent()) { request.putHeader(CONTENT_TYPE, contentType); } } return request.build(); } private void marshallField(SdkField<?> field, Object val) { MARSHALLER_REGISTRY.getMarshaller(field.location(), field.marshallingType(), val) .marshall(val, marshallerContext, field.locationName(), (SdkField<Object>) field); } private boolean needTopLevelJsonObject() { return AwsJsonProtocol.AWS_JSON.equals(protocolMetadata.protocol()) || (!hasExplicitPayloadMember && hasImplicitPayloadMembers); } }
2,210
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/SimpleTypeJsonMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.json.internal.marshall; import java.math.BigDecimal; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; import software.amazon.awssdk.utils.DateUtils; @SdkInternalApi public final class SimpleTypeJsonMarshaller { public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", Optional.ofNullable(paramName) .orElseGet(() -> "paramName null"))); } // If paramName is non null then we are emitting a field of an object, in that // we just don't write the field. If param name is null then we are either in a container // or the thing being marshalled is the payload itself in which case we want to preserve // the JSON null. if (paramName == null) { context.jsonGenerator().writeNull(); } }; public static final JsonMarshaller<String> STRING = new BaseJsonMarshaller<String>() { @Override public void marshall(String val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Integer> INTEGER = new BaseJsonMarshaller<Integer>() { @Override public void marshall(Integer val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Long> LONG = new BaseJsonMarshaller<Long>() { @Override public void marshall(Long val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Short> SHORT = new BaseJsonMarshaller<Short>() { @Override public void marshall(Short val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Float> FLOAT = new BaseJsonMarshaller<Float>() { @Override public void marshall(Float val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<BigDecimal> BIG_DECIMAL = new BaseJsonMarshaller<BigDecimal>() { @Override public void marshall(BigDecimal val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Double> DOUBLE = new BaseJsonMarshaller<Double>() { @Override public void marshall(Double val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Boolean> BOOLEAN = new BaseJsonMarshaller<Boolean>() { @Override public void marshall(Boolean val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<Instant> INSTANT = (val, context, paramName, sdkField) -> { StructuredJsonGenerator jsonGenerator = context.jsonGenerator(); if (paramName != null) { jsonGenerator.writeFieldName(paramName); } TimestampFormatTrait trait = sdkField != null ? sdkField.getTrait(TimestampFormatTrait.class) : null; if (trait != null) { switch (trait.format()) { case UNIX_TIMESTAMP: jsonGenerator.writeNumber(DateUtils.formatUnixTimestampInstant(val)); break; case RFC_822: jsonGenerator.writeValue(DateUtils.formatRfc822Date(val)); break; case ISO_8601: jsonGenerator.writeValue(DateUtils.formatIso8601Date(val)); break; default: throw SdkClientException.create("Unrecognized timestamp format - " + trait.format()); } } else { // Important to fallback to the jsonGenerator implementation as that may differ per wire format, // irrespective of protocol. I.E. CBOR would default to unix timestamp as milliseconds while JSON // will default to unix timestamp as seconds with millisecond decimal precision. jsonGenerator.writeValue(val); } }; public static final JsonMarshaller<SdkBytes> SDK_BYTES = new BaseJsonMarshaller<SdkBytes>() { @Override public void marshall(SdkBytes val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeValue(val.asByteBuffer()); } }; public static final JsonMarshaller<SdkPojo> SDK_POJO = new BaseJsonMarshaller<SdkPojo>() { @Override public void marshall(SdkPojo val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeStartObject(); context.protocolHandler().doMarshall(val); jsonGenerator.writeEndObject(); } }; public static final JsonMarshaller<List<?>> LIST = new BaseJsonMarshaller<List<?>>() { @Override public void marshall(List<?> list, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeStartArray(); for (Object listValue : list) { context.marshall(MarshallLocation.PAYLOAD, listValue); } jsonGenerator.writeEndArray(); } @Override protected boolean shouldEmit(List list) { return !list.isEmpty() || !(list instanceof SdkAutoConstructList); } }; /** * Marshalls a Map as a JSON object where each key becomes a field. */ public static final JsonMarshaller<Map<String, ?>> MAP = new BaseJsonMarshaller<Map<String, ?>>() { @Override public void marshall(Map<String, ?> map, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { jsonGenerator.writeStartObject(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (entry.getValue() != null) { Object value = entry.getValue(); jsonGenerator.writeFieldName(entry.getKey()); context.marshall(MarshallLocation.PAYLOAD, value); } } jsonGenerator.writeEndObject(); } @Override protected boolean shouldEmit(Map<String, ?> map) { return !map.isEmpty() || !(map instanceof SdkAutoConstructMap); } }; /** * Marshalls Document type members by visiting the document using DocumentTypeJsonMarshaller. */ public static final JsonMarshaller<Document> DOCUMENT = new BaseJsonMarshaller<Document>() { @Override public void marshall(Document document, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) { document.accept(new DocumentTypeJsonMarshaller(jsonGenerator)); } }; private SimpleTypeJsonMarshaller() { } /** * Base marshaller that emits the field name if present. The field name may be null in cases like * marshalling something inside a list or if the object is the explicit payload member. * * @param <T> Type to marshall. */ private abstract static class BaseJsonMarshaller<T> implements JsonMarshaller<T> { @Override public final void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) { if (!shouldEmit(val)) { return; } if (paramName != null) { context.jsonGenerator().writeFieldName(paramName); } marshall(val, context.jsonGenerator(), context); } public abstract void marshall(T val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context); protected boolean shouldEmit(T val) { return true; } } }
2,211
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/test/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/test/java/software/amazon/awssdk/protocols/cbor/AwsCborProtocolFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.cbor; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.core.SdkSystemSetting.CBOR_ENABLED; import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.RFC_822; import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.UNIX_TIMESTAMP; import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS; import java.util.Map; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.TimestampFormatTrait; public class AwsCborProtocolFactoryTest { private static AwsCborProtocolFactory factory; @BeforeAll public static void setup() { factory = AwsCborProtocolFactory.builder().build(); } @Test public void defaultTimestampFormats_cborEnabled() { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP_MILLIS); } @Test public void defaultTimestampFormats_cborDisabled() { System.setProperty(CBOR_ENABLED.property(), "false"); try { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP); } finally { System.clearProperty(CBOR_ENABLED.property()); } } }
2,212
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/AwsCborProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.cbor; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.protocols.cbor.internal.AwsStructuredCborFactory; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory; import software.amazon.awssdk.protocols.json.DefaultJsonContentTypeResolver; import software.amazon.awssdk.protocols.json.JsonContentTypeResolver; import software.amazon.awssdk.protocols.json.StructuredJsonFactory; /** * Protocol factory for AWS/CBOR protocols. Supports both JSON RPC and REST JSON versions of CBOR. Defaults to * the CBOR wire format but can fallback to standard JSON if the {@link SdkSystemSetting#CBOR_ENABLED} is * set to false. */ @SdkProtectedApi public final class AwsCborProtocolFactory extends BaseAwsJsonProtocolFactory { /** * Content type resolver implementation for AWS_CBOR enabled services. */ private static final JsonContentTypeResolver AWS_CBOR = new DefaultJsonContentTypeResolver("application/x-amz-cbor-"); private AwsCborProtocolFactory(Builder builder) { super(builder); } /** * @return Content type resolver implementation to use. */ @Override protected JsonContentTypeResolver getContentTypeResolver() { if (isCborEnabled()) { return AWS_CBOR; } else { return AwsJsonProtocolFactory.AWS_JSON; } } /** * @return Instance of {@link StructuredJsonFactory} to use in creating handlers. */ @Override protected StructuredJsonFactory getSdkFactory() { if (isCborEnabled()) { return AwsStructuredCborFactory.SDK_CBOR_FACTORY; } else { return super.getSdkFactory(); } } /** * CBOR uses epoch millis for timestamps rather than epoch seconds with millisecond decimal precision like JSON protocols. */ @Override protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { // If Cbor is disabled, getting the default timestamp format from parent class if (!isCborEnabled()) { return super.getDefaultTimestampFormats(); } Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS); return Collections.unmodifiableMap(formats); } private boolean isCborEnabled() { return SdkSystemSetting.CBOR_ENABLED.getBooleanValueOrThrow(); } public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsJsonProtocolFactory}. */ public static final class Builder extends BaseAwsJsonProtocolFactory.Builder<Builder> { private Builder() { } public AwsCborProtocolFactory build() { return new AwsCborProtocolFactory(this); } } }
2,213
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkCborGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.cbor.internal; import java.io.IOException; import java.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.json.SdkJsonGenerator; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory; import software.amazon.awssdk.thirdparty.jackson.dataformat.cbor.CBORGenerator; /** * Thin wrapper around Jackson's JSON generator for CBOR. */ @SdkInternalApi public final class SdkCborGenerator extends SdkJsonGenerator { private static final int CBOR_TAG_TIMESTAMP = 1; SdkCborGenerator(JsonFactory factory, String contentType) { super(factory, contentType); } /** * Jackson doesn't have native support for timestamp. As per the RFC 7049 * (https://tools.ietf.org/html/rfc7049#section-2.4.1) we will need to * write a tag and write the epoch. */ @Override public StructuredJsonGenerator writeValue(Instant instant) { if (!(getGenerator() instanceof CBORGenerator)) { throw new IllegalStateException("SdkCborGenerator is not created with a CBORGenerator."); } CBORGenerator generator = (CBORGenerator) getGenerator(); try { generator.writeTag(CBOR_TAG_TIMESTAMP); generator.writeNumber(instant.toEpochMilli()); } catch (IOException e) { throw new JsonGenerationException(e); } return this; } }
2,214
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkStructuredCborFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.cbor.internal; import java.util.function.BiFunction; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory; import software.amazon.awssdk.thirdparty.jackson.dataformat.cbor.CBORFactory; /** * Creates generators and protocol handlers for CBOR wire format. */ @SdkInternalApi public abstract class SdkStructuredCborFactory { protected static final JsonFactory CBOR_FACTORY = new CBORFactory(); protected static final CborGeneratorSupplier CBOR_GENERATOR_SUPPLIER = SdkCborGenerator::new; SdkStructuredCborFactory() { } @FunctionalInterface protected interface CborGeneratorSupplier extends BiFunction<JsonFactory, String, StructuredJsonGenerator> { @Override StructuredJsonGenerator apply(JsonFactory jsonFactory, String contentType); } }
2,215
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor
Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/AwsStructuredCborFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.cbor.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.json.BaseAwsStructuredJsonFactory; import software.amazon.awssdk.protocols.json.StructuredJsonGenerator; import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory; /** * Creates generators and protocol handlers for CBOR wire format. */ @SdkInternalApi public final class AwsStructuredCborFactory extends SdkStructuredCborFactory { public static final BaseAwsStructuredJsonFactory SDK_CBOR_FACTORY = new BaseAwsStructuredJsonFactory(CBOR_FACTORY) { @Override protected StructuredJsonGenerator createWriter(JsonFactory jsonFactory, String contentType) { return CBOR_GENERATOR_SUPPLIER.apply(jsonFactory, contentType); } @Override public JsonFactory getJsonFactory() { return CBOR_FACTORY; } }; protected AwsStructuredCborFactory() { } }
2,216
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/test/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/test/java/software/amazon/awssdk/protocols/query/XmlDomParserTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import javax.xml.stream.XMLStreamException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.utils.StringInputStream; public class XmlDomParserTest { @Test public void simpleXmlDocument_ParsedCorrectly() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Struct>" + " <stringMember>stringVal</stringMember>" + " <integerMember>42</integerMember>" + "</Struct>"; XmlElement element = XmlDomParser.parse(new StringInputStream(xml)); assertThat(element.elementName()).isEqualTo("Struct"); assertThat(element.children()).hasSize(2); assertThat(element.getElementsByName("stringMember")) .hasSize(1); assertThat(element.getElementsByName("stringMember").get(0).textContent()) .isEqualTo("stringVal"); assertThat(element.getElementsByName("integerMember")) .hasSize(1); assertThat(element.getElementsByName("integerMember").get(0).textContent()) .isEqualTo("42"); } @Test public void xmlWithAttributes_ParsedCorrectly() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Struct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"foo\" xsi:nil=\"bar\">" + " <stringMember>stringVal</stringMember>" + "</Struct>"; XmlElement element = XmlDomParser.parse(new StringInputStream(xml)); assertThat(element.elementName()).isEqualTo("Struct"); assertThat(element.children()).hasSize(1); assertThat(element.getElementsByName("stringMember")) .hasSize(1); assertThat(element.attributes()).hasSize(2); assertThat(element.getOptionalAttributeByName("xsi:type").get()).isEqualTo("foo"); assertThat(element.getOptionalAttributeByName("xsi:nil").get()).isEqualTo("bar"); } @Test public void multipleElementsWithSameName_ParsedCorrectly() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Struct>" + " <member>valOne</member>" + " <member>valTwo</member>" + "</Struct>"; XmlElement element = XmlDomParser.parse(new StringInputStream(xml)); assertThat(element.getElementsByName("member")) .hasSize(2); assertThat(element.getElementsByName("member").get(0).textContent()) .isEqualTo("valOne"); assertThat(element.getElementsByName("member").get(1).textContent()) .isEqualTo("valTwo"); } @Test public void invalidXml_ThrowsException() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Struct>" + " <member>valOne" + " <member>valTwo</member>" + "</Struct>"; assertThatThrownBy(() -> XmlDomParser.parse(new StringInputStream(xml))) .isInstanceOf(SdkClientException.class) .hasCauseInstanceOf(XMLStreamException.class); } }
2,217
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/AwsQueryProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.internal.marshall.QueryProtocolMarshaller; import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsQueryResponseHandler; import software.amazon.awssdk.protocols.query.internal.unmarshall.QueryProtocolUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Protocol factory for the AWS/Query protocol. */ @SdkProtectedApi public class AwsQueryProtocolFactory { private final SdkClientConfiguration clientConfiguration; private final List<ExceptionMetadata> modeledExceptions; private final Supplier<SdkPojo> defaultServiceExceptionSupplier; private final MetricCollectingHttpResponseHandler<AwsServiceException> errorUnmarshaller; AwsQueryProtocolFactory(Builder<?> builder) { this.clientConfiguration = builder.clientConfiguration; this.modeledExceptions = unmodifiableList(builder.modeledExceptions); this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier; this.errorUnmarshaller = timeUnmarshalling(AwsXmlErrorProtocolUnmarshaller .builder() .defaultExceptionSupplier(defaultServiceExceptionSupplier) .exceptions(modeledExceptions) // We don't set result wrapper since that's handled by the errorRootExtractor .errorUnmarshaller(QueryProtocolUnmarshaller.builder().build()) .errorRootExtractor(this::getErrorRoot) .build()); } /** * Creates a new marshaller for the given request. * * @param operationInfo Object containing metadata about the operation. * @return New {@link ProtocolMarshaller}. */ public final ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller( OperationInfo operationInfo) { return QueryProtocolMarshaller.builder() .endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)) .operationInfo(operationInfo) .isEc2(isEc2()) .build(); } /** * Creates the success response handler to unmarshall the response into a POJO. * * @param pojoSupplier Supplier of the POJO builder we are unmarshalling into. * @param <T> Type being unmarshalled. * @return New {@link HttpResponseHandler} for success responses. */ public final <T extends AwsResponse> HttpResponseHandler<T> createResponseHandler(Supplier<SdkPojo> pojoSupplier) { return timeUnmarshalling(new AwsQueryResponseHandler<>(QueryProtocolUnmarshaller.builder() .hasResultWrapper(!isEc2()) .build(), r -> pojoSupplier.get())); } /** * @return A {@link HttpResponseHandler} that will unmarshall the service exceptional response into * a modeled exception or the service base exception. */ public final HttpResponseHandler<AwsServiceException> createErrorResponseHandler() { return errorUnmarshaller; } private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) { return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate); } /** * Extracts the <Error/> element from the root XML document. Method is protected as EC2 has a slightly * different location. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ Optional<XmlElement> getErrorRoot(XmlElement document) { return document.getOptionalElementByName("Error"); } /** * EC2 has a few distinct differences from query so we wire things up a bit differently. */ boolean isEc2() { return false; } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsQueryProtocolFactory}. * * @param <SubclassT> Subclass of Builder for fluent method chaining. */ public static class Builder<SubclassT extends Builder> { private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>(); private SdkClientConfiguration clientConfiguration; private Supplier<SdkPojo> defaultServiceExceptionSupplier; Builder() { } /** * Sets the {@link SdkClientConfiguration} which contains the service endpoint. * * @param clientConfiguration Configuration of the client. * @return This builder for method chaining. */ public final SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; return getSubclass(); } /** * Registers a new modeled exception by the error code. * * @param errorMetadata metadata for unmarshalling the exceptions * @return This builder for method chaining. */ public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) { modeledExceptions.add(errorMetadata); return getSubclass(); } /** * A supplier for the services base exception builder. This is used when we can't identify any modeled * exception to unmarshall into. * * @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder. * @return This builder for method chaining. */ public final SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) { this.defaultServiceExceptionSupplier = exceptionBuilderSupplier; return getSubclass(); } @SuppressWarnings("unchecked") private SubclassT getSubclass() { return (SubclassT) this; } /** * @return New instance of {@link AwsQueryProtocolFactory}. */ public AwsQueryProtocolFactory build() { return new AwsQueryProtocolFactory(this); } } }
2,218
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/AwsEc2ProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Protocol factory for the AWS/EC2 protocol. */ @SdkProtectedApi public final class AwsEc2ProtocolFactory extends AwsQueryProtocolFactory { private AwsEc2ProtocolFactory(Builder builder) { super(builder); } @Override boolean isEc2() { return true; } /** * EC2 has a slightly different location for the <Error/> element than traditional AWS/Query. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ @Override Optional<XmlElement> getErrorRoot(XmlElement document) { return document.getOptionalElementByName("Errors") .flatMap(e -> e.getOptionalElementByName("Error")); } /** * @return New builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsEc2ProtocolFactory}. */ public static final class Builder extends AwsQueryProtocolFactory.Builder<Builder> { private Builder() { } @Override public AwsEc2ProtocolFactory build() { return new AwsEc2ProtocolFactory(this); } } }
2,219
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/MapQueryUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import static java.util.Collections.singletonList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class MapQueryUnmarshaller implements QueryUnmarshaller<Map<String, ?>> { @Override public Map<String, ?> unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<Map<String, ?>> field) { Map<String, Object> map = new HashMap<>(); MapTrait mapTrait = field.getTrait(MapTrait.class); SdkField mapValueSdkField = mapTrait.valueFieldInfo(); getEntries(content, mapTrait).forEach(entry -> { XmlElement key = entry.getElementByName(mapTrait.keyLocationName()); XmlElement value = entry.getElementByName(mapTrait.valueLocationName()); QueryUnmarshaller unmarshaller = context.getUnmarshaller(mapValueSdkField.location(), mapValueSdkField.marshallingType()); map.put(key.textContent(), unmarshaller.unmarshall(context, singletonList(value), mapValueSdkField)); }); return map; } private List<XmlElement> getEntries(List<XmlElement> content, MapTrait mapTrait) { return mapTrait.isFlattened() ? content : content.get(0).getElementsByName("entry"); } }
2,220
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; /** * Registry of {@link QueryUnmarshaller} implementations by location and type. */ @SdkInternalApi public final class QueryUnmarshallerRegistry extends AbstractMarshallingRegistry { private QueryUnmarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> QueryUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return (QueryUnmarshaller<Object>) super.get(marshallLocation, marshallingType); } /** * @return Builder instance to construct a {@link QueryUnmarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link QueryUnmarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder unmarshaller(MarshallingType<T> marshallingType, QueryUnmarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } /** * @return An immutable {@link QueryUnmarshallerRegistry} object. */ public QueryUnmarshallerRegistry build() { return new QueryUnmarshallerRegistry(this); } } }
2,221
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public interface QueryUnmarshaller<T> { /** * @param context Context containing dependencies and unmarshaller registry. * @param content Parsed JSON content of body. May be null for REST JSON based services that don't have payload members. * @param field {@link SdkField} of member being unmarshalled. * @return Unmarshalled value. */ T unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<T> field); }
2,222
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/AwsXmlErrorUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; /** * Unmarshalls an AWS XML exception from parsed XML. */ @SdkInternalApi public final class AwsXmlErrorUnmarshaller { private static final String X_AMZ_ID_2_HEADER = "x-amz-id-2"; private final List<ExceptionMetadata> exceptions; private final Supplier<SdkPojo> defaultExceptionSupplier; private final XmlErrorUnmarshaller errorUnmarshaller; private AwsXmlErrorUnmarshaller(Builder builder) { this.exceptions = builder.exceptions; this.errorUnmarshaller = builder.errorUnmarshaller; this.defaultExceptionSupplier = builder.defaultExceptionSupplier; } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Unmarshal an AWS XML exception * @param documentRoot The parsed payload document * @param errorRoot The specific element of the parsed payload document that contains the error to be marshalled * or empty if it could not be located. * @param documentBytes The raw bytes of the original payload document if they are available * @param response The HTTP response object * @param executionAttributes {@link ExecutionAttributes} for the current execution * @return An {@link AwsServiceException} unmarshalled from the XML. */ public AwsServiceException unmarshall(XmlElement documentRoot, Optional<XmlElement> errorRoot, Optional<SdkBytes> documentBytes, SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { String errorCode = getErrorCode(errorRoot); AwsServiceException.Builder builder = errorRoot .map(e -> invokeSafely(() -> unmarshallFromErrorCode(response, e, errorCode))) .orElseGet(this::defaultException); AwsErrorDetails awsErrorDetails = AwsErrorDetails.builder() .errorCode(errorCode) .errorMessage(builder.message()) .rawResponse(documentBytes.orElse(null)) .sdkHttpResponse(response) .serviceName(executionAttributes.getAttribute(AwsExecutionAttribute.SERVICE_NAME)) .build(); builder.requestId(getRequestId(response, documentRoot)) .extendedRequestId(getExtendedRequestId(response)) .statusCode(response.statusCode()) .clockSkew(getClockSkew(executionAttributes)) .awsErrorDetails(awsErrorDetails); return builder.build(); } private Duration getClockSkew(ExecutionAttributes executionAttributes) { Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET); return timeOffset == null ? null : Duration.ofSeconds(timeOffset); } /** * @return Builder for the default service exception. Used when the error code doesn't match * any known modeled exception or when we can't determine the error code. */ private AwsServiceException.Builder defaultException() { return (AwsServiceException.Builder) defaultExceptionSupplier.get(); } /** * Unmarshalls the XML into the appropriate modeled exception based on the error code. If the error code * is not present or does not match any known exception we unmarshall into the base service exception. * * @param errorRoot Root of <Error/> element. Contains any modeled fields of the exception. * @param errorCode Error code identifying the modeled exception. * @return Unmarshalled exception builder. */ private AwsServiceException.Builder unmarshallFromErrorCode(SdkHttpFullResponse response, XmlElement errorRoot, String errorCode) { SdkPojo sdkPojo = exceptions.stream() .filter(e -> e.errorCode().equals(errorCode)) .map(ExceptionMetadata::exceptionBuilderSupplier) .findAny() .orElse(defaultExceptionSupplier) .get(); AwsServiceException.Builder builder = ((AwsServiceException) errorUnmarshaller.unmarshall(sdkPojo, errorRoot, response)).toBuilder(); builder.message(getMessage(errorRoot)); return builder; } /** * Extracts the error code (used to identify the modeled exception) from the <Error/> * element. * * @param errorRoot Error element root. * @return Error code or null if not present. */ private String getErrorCode(Optional<XmlElement> errorRoot) { return errorRoot.map(e -> e.getOptionalElementByName("Code") .map(XmlElement::textContent) .orElse(null)) .orElse(null); } /** * Extracts the error message from the XML document. The message is in the <Error/> * element for all services. * * @param errorRoot Error element root. * @return Error message or null if not present. */ private String getMessage(XmlElement errorRoot) { return errorRoot.getOptionalElementByName("Message") .map(XmlElement::textContent) .orElse(null); } /** * Extracts the request ID from the XML document. Request ID is a top level element * for all protocols, it may be RequestId or RequestID depending on the service. * * @param document Root XML document. * @return Request ID string or null if not present. */ private String getRequestId(SdkHttpFullResponse response, XmlElement document) { XmlElement requestId = document.getOptionalElementByName("RequestId") .orElseGet(() -> document.getElementByName("RequestID")); return requestId != null ? requestId.textContent() : matchRequestIdHeaders(response); } private String matchRequestIdHeaders(SdkHttpFullResponse response) { return HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS.stream() .map(h -> response.firstMatchingHeader(h)) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .orElse(null); } /** * Extracts the extended request ID from the response headers. * * @param response The HTTP response object. * @return Extended Request ID string or null if not present. */ private String getExtendedRequestId(SdkHttpFullResponse response) { return response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(null); } /** * Builder for {@link AwsXmlErrorUnmarshaller}. */ public static final class Builder { private List<ExceptionMetadata> exceptions; private Supplier<SdkPojo> defaultExceptionSupplier; private XmlErrorUnmarshaller errorUnmarshaller; private Builder() { } /** * List of {@link ExceptionMetadata} to represent the modeled exceptions for the service. * For AWS services the error type is a string representing the type of the modeled exception. * * @return This builder for method chaining. */ public Builder exceptions(List<ExceptionMetadata> exceptions) { this.exceptions = exceptions; return this; } /** * Default exception type if "error code" does not match any known modeled exception. This is the generated * base exception for the service (i.e. DynamoDbException). * * @return This builder for method chaining. */ public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) { this.defaultExceptionSupplier = defaultExceptionSupplier; return this; } /** * The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception, * additional metadata is extracted by {@link AwsXmlErrorUnmarshaller}. * * @param errorUnmarshaller Error unmarshaller to use. * @return This builder for method chaining. */ public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) { this.errorUnmarshaller = errorUnmarshaller; return this; } /** * @return New instance of {@link AwsXmlErrorUnmarshaller}. */ public AwsXmlErrorUnmarshaller build() { return new AwsXmlErrorUnmarshaller(this); } } }
2,223
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/ListQueryUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class ListQueryUnmarshaller implements QueryUnmarshaller<List<?>> { @Override public List<?> unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<List<?>> field) { ListTrait listTrait = field.getTrait(ListTrait.class); List<Object> list = new ArrayList<>(); getMembers(content, listTrait).forEach(member -> { QueryUnmarshaller unmarshaller = context.getUnmarshaller(listTrait.memberFieldInfo().location(), listTrait.memberFieldInfo().marshallingType()); list.add(unmarshaller.unmarshall(context, singletonList(member), listTrait.memberFieldInfo())); }); return list; } private List<XmlElement> getMembers(List<XmlElement> content, ListTrait listTrait) { return listTrait.isFlattened() ? content : // There have been cases in EC2 where the member name is not modeled correctly so we just grab all // direct children instead and don't care about member name. See TT0124273367 for more information. content.get(0).children(); } }
2,224
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryProtocolUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import static software.amazon.awssdk.protocols.query.internal.marshall.SimpleTypeQueryMarshaller.defaultTimestampFormats; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.StringToInstant; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.builder.Buildable; /** * Unmarshaller implementation for AWS/Query and EC2 services. */ @SdkInternalApi public final class QueryProtocolUnmarshaller implements XmlErrorUnmarshaller { private static final QueryUnmarshallerRegistry UNMARSHALLER_REGISTRY = QueryUnmarshallerRegistry .builder() .unmarshaller(MarshallingType.STRING, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_STRING)) .unmarshaller(MarshallingType.INTEGER, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_INTEGER)) .unmarshaller(MarshallingType.LONG, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_LONG)) .unmarshaller(MarshallingType.SHORT, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_SHORT)) .unmarshaller(MarshallingType.FLOAT, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_FLOAT)) .unmarshaller(MarshallingType.DOUBLE, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_DOUBLE)) .unmarshaller(MarshallingType.BOOLEAN, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_BOOLEAN)) .unmarshaller(MarshallingType.DOUBLE, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_DOUBLE)) .unmarshaller(MarshallingType.INSTANT, new SimpleTypeQueryUnmarshaller<>(StringToInstant.create(defaultTimestampFormats()))) .unmarshaller(MarshallingType.SDK_BYTES, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_SDK_BYTES)) .unmarshaller(MarshallingType.LIST, new ListQueryUnmarshaller()) .unmarshaller(MarshallingType.MAP, new MapQueryUnmarshaller()) .unmarshaller(MarshallingType.NULL, (context, content, field) -> null) .unmarshaller(MarshallingType.SDK_POJO, (context, content, field) -> context.protocolUnmarshaller().unmarshall(context, field.constructor().get(), content.get(0))) .build(); private final boolean hasResultWrapper; private QueryProtocolUnmarshaller(Builder builder) { this.hasResultWrapper = builder.hasResultWrapper; } public <TypeT extends SdkPojo> Pair<TypeT, Map<String, String>> unmarshall(SdkPojo sdkPojo, SdkHttpFullResponse response) { if (responsePayloadIsBlob(sdkPojo)) { XmlElement document = XmlElement.builder() .textContent(response.content() .map(s -> invokeSafely(() -> IoUtils.toUtf8String(s))) .orElse("")) .build(); return Pair.of(unmarshall(sdkPojo, document, response), new HashMap<>()); } XmlElement document = response.content().map(XmlDomParser::parse).orElseGet(XmlElement::empty); XmlElement resultRoot = hasResultWrapper ? document.getFirstChild() : document; return Pair.of(unmarshall(sdkPojo, resultRoot, response), parseMetadata(document)); } private boolean responsePayloadIsBlob(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .anyMatch(field -> field.marshallingType() == MarshallingType.SDK_BYTES && field.containsTrait(PayloadTrait.class)); } /** * This method is also used to unmarshall exceptions. We use this since we've already parsed the XML * and the result root is in a different location depending on the protocol/service. */ @Override public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, XmlElement resultRoot, SdkHttpFullResponse response) { QueryUnmarshallerContext unmarshallerContext = QueryUnmarshallerContext.builder() .registry(UNMARSHALLER_REGISTRY) .protocolUnmarshaller(this) .build(); return (TypeT) unmarshall(unmarshallerContext, sdkPojo, resultRoot); } private Map<String, String> parseMetadata(XmlElement document) { XmlElement responseMetadata = document.getElementByName("ResponseMetadata"); Map<String, String> metadata = new HashMap<>(); if (responseMetadata != null) { responseMetadata.children().forEach(c -> metadata.put(metadataKeyName(c), c.textContent())); } XmlElement requestId = document.getElementByName("requestId"); if (requestId != null) { metadata.put(AWS_REQUEST_ID, requestId.textContent()); } return metadata; } private String metadataKeyName(XmlElement c) { return c.elementName().equals("RequestId") ? AWS_REQUEST_ID : c.elementName(); } private SdkPojo unmarshall(QueryUnmarshallerContext context, SdkPojo sdkPojo, XmlElement root) { if (root != null) { for (SdkField<?> field : sdkPojo.sdkFields()) { if (field.containsTrait(PayloadTrait.class) && field.marshallingType() == MarshallingType.SDK_BYTES) { field.set(sdkPojo, SdkBytes.fromUtf8String(root.textContent())); } List<XmlElement> element = root.getElementsByName(field.unmarshallLocationName()); if (!CollectionUtils.isNullOrEmpty(element)) { QueryUnmarshaller<Object> unmarshaller = UNMARSHALLER_REGISTRY.getUnmarshaller(field.location(), field.marshallingType()); Object unmarshalled = unmarshaller.unmarshall(context, element, (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } } } return (SdkPojo) ((Buildable) sdkPojo).build(); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link QueryProtocolUnmarshaller}. */ public static final class Builder { private boolean hasResultWrapper; private Builder() { } /** * <h3>Example response with result wrapper</h3> * <pre> * {@code * <ListQueuesResponse> * <ListQueuesResult> * <QueueUrl>https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue</QueueUrl> * </ListQueuesResult> * <ResponseMetadata> * <RequestId>725275ae-0b9b-4762-b238-436d7c65a1ac</RequestId> * </ResponseMetadata> * </ListQueuesResponse> * } * </pre> * * <h3>Example response without result wrapper</h3> * <pre> * {@code * <DescribeAddressesResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"> * <requestId>f7de5e98-491a-4c19-a92d-908d6EXAMPLE</requestId> * <addressesSet> * <item> * <publicIp>203.0.113.41</publicIp> * <allocationId>eipalloc-08229861</allocationId> * <domain>vpc</domain> * <instanceId>i-0598c7d356eba48d7</instanceId> * <associationId>eipassoc-f0229899</associationId> * <networkInterfaceId>eni-ef229886</networkInterfaceId> * <networkInterfaceOwnerId>053230519467</networkInterfaceOwnerId> * <privateIpAddress>10.0.0.228</privateIpAddress> * </item> * </addressesSet> * </DescribeAddressesResponse> * } * </pre> * * @param hasResultWrapper True if the response has a result wrapper, false if the result is in the top level * XML document. * @return This builder for method chaining. */ public Builder hasResultWrapper(boolean hasResultWrapper) { this.hasResultWrapper = hasResultWrapper; return this; } /** * @return New instance of {@link QueryProtocolUnmarshaller}. */ public QueryProtocolUnmarshaller build() { return new QueryProtocolUnmarshaller(this); } } }
2,225
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; /** * Container for dependencies used during AWS/Query unmarshalling. */ @SdkInternalApi public final class QueryUnmarshallerContext { private final QueryUnmarshallerRegistry registry; private final QueryProtocolUnmarshaller protocolUnmarshaller; private QueryUnmarshallerContext(Builder builder) { this.registry = builder.registry; this.protocolUnmarshaller = builder.protocolUnmarshaller; } /** * @return Protocol unmarshaller used for unmarshalling nested structs. */ public QueryProtocolUnmarshaller protocolUnmarshaller() { return protocolUnmarshaller; } /** * Conveience method to get an unmarshaller from the registry. * * @param marshallLocation Location of field being unmarshalled. * @param marshallingType Type of field being unmarshalled. * @param <T> Type of field being unmarshalled. * @return Unmarshaller implementation. */ public <T> QueryUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return registry.getUnmarshaller(marshallLocation, marshallingType); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link QueryUnmarshallerContext}. */ public static final class Builder { private QueryUnmarshallerRegistry registry; private QueryProtocolUnmarshaller protocolUnmarshaller; private Builder() { } public Builder registry(QueryUnmarshallerRegistry registry) { this.registry = registry; return this; } public Builder protocolUnmarshaller(QueryProtocolUnmarshaller protocolUnmarshaller) { this.protocolUnmarshaller = protocolUnmarshaller; return this; } public QueryUnmarshallerContext build() { return new QueryUnmarshallerContext(this); } } }
2,226
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/AwsQueryResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.io.IOException; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; /** * Response handler for AWS/Query services and Amazon EC2 which is a dialect of the Query protocol. * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class AwsQueryResponseHandler<T extends AwsResponse> implements HttpResponseHandler<T> { private static final Logger log = Logger.loggerFor(AwsQueryResponseHandler.class); private final QueryProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; public AwsQueryResponseHandler(QueryProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { try { return unmarshallResponse(response); } finally { response.content().ifPresent(i -> { try { i.close(); } catch (IOException e) { log.warn(() -> "Error closing HTTP content.", e); } }); } } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response) throws Exception { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response XML."); Pair<T, Map<String, String>> result = unmarshaller.unmarshall(pojoSupplier.apply(response), response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response."); AwsResponseMetadata responseMetadata = generateResponseMetadata(response, result.right()); return (T) result.left().toBuilder().responseMetadata(responseMetadata).build(); } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response, Map<String, String> metadata) { if (!metadata.containsKey(AWS_REQUEST_ID)) { metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null)); } response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } @Override public boolean needsConnectionLeftOpen() { // Query doesn't support streaming so this is always false return false; } }
2,227
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/SimpleTypeQueryUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.unmarshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Unmarshaller implementation for simple, scalar values. * * @param <T> Type being unmarshalled. */ @SdkInternalApi public final class SimpleTypeQueryUnmarshaller<T> implements QueryUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> stringToValue; public SimpleTypeQueryUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) { this.stringToValue = stringToValue; } @Override public T unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { if (content == null) { return null; } return stringToValue.convert(content.get(0).textContent(), field); } }
2,228
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/SimpleTypeQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.protocols.core.InstantToString; import software.amazon.awssdk.protocols.core.StringToValueConverter.StringToValue; import software.amazon.awssdk.protocols.core.ValueToStringConverter; /** * Simple implementation of {@link QueryMarshaller} that converts a given value to a string using * {@link StringToValue} and emits it as a query param. * * @param <T> Type being marshalled. */ @SdkInternalApi public final class SimpleTypeQueryMarshaller<T> implements QueryMarshaller<T> { public static final QueryMarshaller<String> STRING = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_STRING); public static final QueryMarshaller<Integer> INTEGER = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final QueryMarshaller<Float> FLOAT = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final QueryMarshaller<Boolean> BOOLEAN = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final QueryMarshaller<Double> DOUBLE = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final QueryMarshaller<Long> LONG = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_LONG); public static final QueryMarshaller<Short> SHORT = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final QueryMarshaller<Instant> INSTANT = new SimpleTypeQueryMarshaller<>(InstantToString.create(defaultTimestampFormats())); public static final QueryMarshaller<SdkBytes> SDK_BYTES = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_SDK_BYTES); public static final QueryMarshaller<Void> NULL = (request, path, val, sdkField) -> { }; private final ValueToStringConverter.ValueToString<T> valueToString; private SimpleTypeQueryMarshaller(ValueToStringConverter.ValueToString<T> valueToString) { this.valueToString = valueToString; } @Override public void marshall(QueryMarshallerContext context, String path, T val, SdkField<T> sdkField) { context.request().putRawQueryParameter(path, valueToString.convert(val, sdkField)); } /** * @return Default timestamp formats for each location supported by the Query protocol. */ public static Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); // Query doesn't support location traits formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } }
2,229
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.internal.unmarshall.QueryProtocolUnmarshaller; /** * Dependencies needed by {@link QueryProtocolUnmarshaller}. */ @SdkInternalApi public final class QueryMarshallerContext { private final QueryProtocolMarshaller protocolHandler; private final QueryMarshallerRegistry marshallerRegistry; private final SdkHttpFullRequest.Builder request; private QueryMarshallerContext(Builder builder) { this.protocolHandler = builder.protocolHandler; this.marshallerRegistry = builder.marshallerRegistry; this.request = builder.request; } /** * @return Implementation of {@link ProtocolMarshaller} that can be used to call back out to marshall structured data (i.e. * lists of objects). */ public QueryProtocolMarshaller protocolHandler() { return protocolHandler; } /** * @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string * to string). */ public QueryMarshallerRegistry marshallerRegistry() { return marshallerRegistry; } /** * @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params, * modify request URI, etc. */ public SdkHttpFullRequest.Builder request() { return request; } /** * @return Builder instance to construct a {@link QueryMarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link QueryMarshallerContext}. */ public static final class Builder { private QueryProtocolMarshaller protocolHandler; private QueryMarshallerRegistry marshallerRegistry; private SdkHttpFullRequest.Builder request; private Builder() { } public Builder protocolHandler(QueryProtocolMarshaller protocolHandler) { this.protocolHandler = protocolHandler; return this; } public Builder marshallerRegistry(QueryMarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; return this; } public Builder request(SdkHttpFullRequest.Builder request) { this.request = request; return this; } /** * @return An immutable {@link QueryMarshallerContext} object. */ public QueryMarshallerContext build() { return new QueryMarshallerContext(this); } } }
2,230
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.Marshaller; /** * Interface for marshallers for AWS/Query protocol. * * @param <T> Type being marshalled. */ @FunctionalInterface @SdkInternalApi public interface QueryMarshaller<T> extends Marshaller<T> { void marshall(QueryMarshallerContext context, String path, T val, SdkField<T> sdkField); }
2,231
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/ListQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.util.SdkAutoConstructList; /** * Marshaller for list types. */ @SdkInternalApi public class ListQueryMarshaller implements QueryMarshaller<List<?>> { private final PathResolver pathResolver; private ListQueryMarshaller(PathResolver pathResolver) { this.pathResolver = pathResolver; } @Override public void marshall(QueryMarshallerContext context, String path, List<?> val, SdkField<List<?>> sdkField) { // Explicitly empty lists are marshalled as a query param with empty value in AWS/Query if (val.isEmpty() && !(val instanceof SdkAutoConstructList)) { context.request().putRawQueryParameter(path, ""); return; } for (int i = 0; i < val.size(); i++) { ListTrait listTrait = sdkField.getTrait(ListTrait.class); String listPath = pathResolver.resolve(path, i, listTrait); QueryMarshaller<Object> marshaller = context.marshallerRegistry().getMarshaller( ((SdkField<?>) listTrait.memberFieldInfo()).marshallingType(), val); marshaller.marshall(context, listPath, val.get(i), listTrait.memberFieldInfo()); } } @FunctionalInterface private interface PathResolver { String resolve(String path, int i, ListTrait listTrait); } /** * Wires up the {@link ListQueryMarshaller} with a {@link PathResolver} that respects the flattened trait. * * @return ListQueryMarshaller. */ public static ListQueryMarshaller awsQuery() { return new ListQueryMarshaller((path, i, listTrait) -> listTrait.isFlattened() ? String.format("%s.%d", path, i + 1) : String.format("%s.%s.%d", path, listTrait.memberFieldInfo().locationName(), i + 1)); } /** * Wires up the {@link ListQueryMarshaller} with a {@link PathResolver} that always flattens lists. The EC2 protocol * always flattens lists for inputs even when the 'flattened' trait is not present. * * @return ListQueryMarshaller. */ public static ListQueryMarshaller ec2Query() { return new ListQueryMarshaller((path, i, listTrait) -> String.format("%s.%d", path, i + 1)); } }
2,232
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; /** * Marshaller registry for the AWS Query protocol. */ @SdkInternalApi public final class QueryMarshallerRegistry extends AbstractMarshallingRegistry { private QueryMarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> QueryMarshaller<Object> getMarshaller(T val) { MarshallingType<T> marshallingType = toMarshallingType(val); return (QueryMarshaller<Object>) get(MarshallLocation.PAYLOAD, marshallingType); } @SuppressWarnings("unchecked") public <T> QueryMarshaller<Object> getMarshaller(MarshallingType<T> marshallingType, Object val) { return (QueryMarshaller<Object>) get(MarshallLocation.PAYLOAD, val == null ? MarshallingType.NULL : marshallingType); } /** * @return Builder instance to construct a {@link AbstractMarshallingRegistry}. */ public static Builder builder() { return new Builder(); } public static class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } /** * Registers a marshaller of the given type. Since the Query protocol doesn't support location * constraints this uses the location 'PAYLOAD' to register. * * @param marshallingType Type of marshaller * @param marshaller Marshaller implementation. * @param <T> Type of marshaller being registered. * @return This builder for method chaining. */ public <T> Builder marshaller(MarshallingType<T> marshallingType, QueryMarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } /** * @return An immutable {@link QueryMarshallerRegistry} object. */ public QueryMarshallerRegistry build() { return new QueryMarshallerRegistry(this); } } }
2,233
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/MapQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.MapTrait; @SdkInternalApi public class MapQueryMarshaller implements QueryMarshaller<Map<String, ?>> { @Override public void marshall(QueryMarshallerContext context, String path, Map<String, ?> val, SdkField<Map<String, ?>> sdkField) { MapTrait mapTrait = sdkField.getTrait(MapTrait.class); AtomicInteger entryNum = new AtomicInteger(1); val.forEach((key, value) -> { String mapKeyPath = resolveMapPath(path, mapTrait, entryNum, mapTrait.keyLocationName()); context.request().putRawQueryParameter(mapKeyPath, key); String mapValuePath = resolveMapPath(path, mapTrait, entryNum, mapTrait.valueLocationName()); QueryMarshaller<Object> marshaller = context.marshallerRegistry() .getMarshaller(((SdkField<?>) mapTrait.valueFieldInfo()).marshallingType(), val); marshaller.marshall(context, mapValuePath, value, mapTrait.valueFieldInfo()); entryNum.incrementAndGet(); }); } private static String resolveMapPath(String path, MapTrait mapTrait, AtomicInteger entryNum, String s) { return mapTrait.isFlattened() ? String.format("%s.%d.%s", path, entryNum.get(), s) : String.format("%s.entry.%d.%s", path, entryNum.get(), s); } }
2,234
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryProtocolMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.internal.marshall; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; /** * Implementation of {@link ProtocolMarshaller} for AWS Query services. */ @SdkInternalApi public final class QueryProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { private static final QueryMarshallerRegistry AWS_QUERY_MARSHALLER_REGISTRY = commonRegistry() .marshaller(MarshallingType.LIST, ListQueryMarshaller.awsQuery()) .build(); private static final QueryMarshallerRegistry EC2_QUERY_MARSHALLER_REGISTRY = commonRegistry() .marshaller(MarshallingType.LIST, ListQueryMarshaller.ec2Query()) .build(); private final SdkHttpFullRequest.Builder request; private final QueryMarshallerRegistry registry; private final URI endpoint; private QueryProtocolMarshaller(Builder builder) { this.endpoint = builder.endpoint; this.request = fillBasicRequestParams(builder.operationInfo); this.registry = builder.isEc2 ? EC2_QUERY_MARSHALLER_REGISTRY : AWS_QUERY_MARSHALLER_REGISTRY; } private SdkHttpFullRequest.Builder fillBasicRequestParams(OperationInfo operationInfo) { return ProtocolUtils.createSdkHttpRequest(operationInfo, endpoint) .encodedPath("") .putRawQueryParameter("Action", operationInfo.operationIdentifier()) .putRawQueryParameter("Version", operationInfo.apiVersion()); } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { QueryMarshallerContext context = QueryMarshallerContext.builder() .request(request) .protocolHandler(this) .marshallerRegistry(registry) .build(); doMarshall(null, context, pojo); return request.build(); } private void doMarshall(String path, QueryMarshallerContext context, SdkPojo pojo) { for (SdkField<?> sdkField : pojo.sdkFields()) { Object val = sdkField.getValueOrDefault(pojo); QueryMarshaller<Object> marshaller = registry.getMarshaller(sdkField.marshallingType(), val); marshaller.marshall(context, resolvePath(path, sdkField), val, (SdkField<Object>) sdkField); } } private static String resolvePath(String path, SdkField<?> sdkField) { return path == null ? sdkField.locationName() : path + "." + sdkField.locationName(); } private static QueryMarshallerRegistry.Builder commonRegistry() { return QueryMarshallerRegistry .builder() .marshaller(MarshallingType.STRING, SimpleTypeQueryMarshaller.STRING) .marshaller(MarshallingType.INTEGER, SimpleTypeQueryMarshaller.INTEGER) .marshaller(MarshallingType.FLOAT, SimpleTypeQueryMarshaller.FLOAT) .marshaller(MarshallingType.BOOLEAN, SimpleTypeQueryMarshaller.BOOLEAN) .marshaller(MarshallingType.DOUBLE, SimpleTypeQueryMarshaller.DOUBLE) .marshaller(MarshallingType.LONG, SimpleTypeQueryMarshaller.LONG) .marshaller(MarshallingType.SHORT, SimpleTypeQueryMarshaller.SHORT) .marshaller(MarshallingType.INSTANT, SimpleTypeQueryMarshaller.INSTANT) .marshaller(MarshallingType.SDK_BYTES, SimpleTypeQueryMarshaller.SDK_BYTES) .marshaller(MarshallingType.NULL, SimpleTypeQueryMarshaller.NULL) .marshaller(MarshallingType.MAP, new MapQueryMarshaller()) .marshaller(MarshallingType.SDK_POJO, (context, path, val, sdkField) -> context.protocolHandler().doMarshall(path, context, val)); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link QueryProtocolMarshaller}. */ public static final class Builder { private OperationInfo operationInfo; private boolean isEc2; private URI endpoint; /** * @param operationInfo Metadata about the operation like URI, HTTP method, etc. * @return This builder for method chaining. */ public Builder operationInfo(OperationInfo operationInfo) { this.operationInfo = operationInfo; return this; } /** * @param ec2 True if the service is EC2. EC2 has some slightly different behavior so we wire things up * a bit differently for it. * @return This builder for method chaining. */ public Builder isEc2(boolean ec2) { isEc2 = ec2; return this; } /** * @param endpoint Endpoint to set on the marshalled request. * @return This builder for method chaining. */ public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * @return New instance of {@link QueryProtocolMarshaller}. */ public QueryProtocolMarshaller build() { return new QueryProtocolMarshaller(this); } } }
2,235
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/AwsXmlErrorProtocolUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.unmarshall; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller; import software.amazon.awssdk.utils.Pair; /** * Error unmarshaller for Query/EC2/XML based protocols. Some examples of error responses from * the various protocols are below. * * <h3>Legacy Query (SimpleDB/EC2)</h3> * <pre> * {@code * <Response> * <Errors> * <Error> * <Code>MissingParameter</Code> * <Message>The request must contain the parameter DomainName</Message> * <BoxUsage>0.0055590278</BoxUsage> * </Error> * </Errors> * <RequestID>ad3280dd-5ac1-efd1-b9b0-a86969a9234d</RequestID> * </Response> * } * </pre> * * <h3>Traditional Query/Rest-XML (Cloudfront)</h3> * <pre> * {@code * <ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2017-10-30/"> * <Error> * <Type>Sender</Type> * <Code>MalformedInput</Code> * <Message>Invalid XML document</Message> * </Error> * <RequestId>7c8da4af-de44-11e8-a60e-1b2014315455</RequestId> * </ErrorResponse> * } * </pre> * * <h3>Amazon S3</h3> * <pre> * {@code * <Error> * <Code>NoSuchBucket</Code> * <Message>The specified bucket does not exist</Message> * <BucketName>flajdfadjfladjf</BucketName> * <RequestId>D9DBB9F267849CA3</RequestId> * <HostId>fn8B1fUvWzg7I3CIeMT4UMqCZDF4+QO1JlbOJlQAVOosACZsLWv/K2dapVncz34a2mArhp11PjI=</HostId> * </Error> * } * </pre> */ @SdkProtectedApi public final class AwsXmlErrorProtocolUnmarshaller implements HttpResponseHandler<AwsServiceException> { private final AwsXmlErrorUnmarshaller awsXmlErrorUnmarshaller; private final Function<XmlElement, Optional<XmlElement>> errorRootExtractor; private AwsXmlErrorProtocolUnmarshaller(Builder builder) { this.errorRootExtractor = builder.errorRootExtractor; this.awsXmlErrorUnmarshaller = AwsXmlErrorUnmarshaller.builder() .defaultExceptionSupplier(builder.defaultExceptionSupplier) .exceptions(builder.exceptions) .errorUnmarshaller(builder.errorUnmarshaller) .build(); } @Override public AwsServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { Pair<XmlElement, SdkBytes> xmlAndBytes = parseXml(response); XmlElement document = xmlAndBytes.left(); Optional<XmlElement> errorRoot = errorRootExtractor.apply(document); return awsXmlErrorUnmarshaller.unmarshall(document, errorRoot, Optional.of(xmlAndBytes.right()), response, executionAttributes); } /** * Parse the response content into an XML document. If we fail to read the content or the XML is malformed * we still return an empty {@link XmlElement} so that unmarshalling can proceed. In those failure * cases we can't parse out the error code so we'd unmarshall into a generic service exception. * * @param response HTTP response. * @return Pair of the parsed {@link XmlElement} and the raw bytes of the response. */ private Pair<XmlElement, SdkBytes> parseXml(SdkHttpFullResponse response) { SdkBytes bytes = getResponseBytes(response); try { return Pair.of(XmlDomParser.parse(bytes.asInputStream()), bytes); } catch (Exception e) { return Pair.of(XmlElement.empty(), bytes); } } /** * Buffers the response content into an {@link SdkBytes} object. Used to fill the {@link AwsErrorDetails}. If * an {@link IOException} occurs then this will return {@link #emptyXmlBytes()} so that unmarshalling can proceed. * * @param response HTTP response. * @return Raw bytes of response. */ private SdkBytes getResponseBytes(SdkHttpFullResponse response) { try { return response.content() .map(SdkBytes::fromInputStream) .orElseGet(this::emptyXmlBytes); } catch (Exception e) { return emptyXmlBytes(); } } /** * @return Dummy XML document to allow unmarshalling when response can't be read/parsed. */ private SdkBytes emptyXmlBytes() { return SdkBytes.fromUtf8String("<eof/>"); } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlErrorProtocolUnmarshaller}. */ public static final class Builder { private List<ExceptionMetadata> exceptions; private Supplier<SdkPojo> defaultExceptionSupplier; private Function<XmlElement, Optional<XmlElement>> errorRootExtractor; private XmlErrorUnmarshaller errorUnmarshaller; private Builder() { } /** * List of {@link ExceptionMetadata} to represent the modeled exceptions for the service. * For AWS services the error type is a string representing the type of the modeled exception. * * @return This builder for method chaining. */ public Builder exceptions(List<ExceptionMetadata> exceptions) { this.exceptions = exceptions; return this; } /** * Default exception type if "error code" does not match any known modeled exception. This is the generated * base exception for the service (i.e. DynamoDbException). * * @return This builder for method chaining. */ public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) { this.defaultExceptionSupplier = defaultExceptionSupplier; return this; } /** * Extracts the <Error/> element from the top level XML document. Different protocols have slightly * different formats for where the Error element is located. The error root of the XML document contains * the code, message and any modeled fields of the exception. See javadocs of * {@link AwsXmlErrorProtocolUnmarshaller} for examples. * * @param errorRootExtractor Function that extracts the <Error/> element from the root XML document. * @return This builder for method chaining. */ public Builder errorRootExtractor(Function<XmlElement, Optional<XmlElement>> errorRootExtractor) { this.errorRootExtractor = errorRootExtractor; return this; } /** * The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception, * additional metadata is extracted by {@link AwsXmlErrorProtocolUnmarshaller}. * * @param errorUnmarshaller Error unmarshaller to use. * @return This builder for method chaining. */ public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) { this.errorUnmarshaller = errorUnmarshaller; return this; } /** * @return New instance of {@link AwsXmlErrorProtocolUnmarshaller}. */ public AwsXmlErrorProtocolUnmarshaller build() { return new AwsXmlErrorProtocolUnmarshaller(this); } } }
2,236
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlElement.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.unmarshall; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; /** * Represents an element in an XML document. */ @SdkProtectedApi public final class XmlElement { private static final XmlElement EMPTY = XmlElement.builder().elementName("eof").build(); private final String elementName; private final HashMap<String, List<XmlElement>> childrenByElement; private final List<XmlElement> children; private final String textContent; private final Map<String, String> attributes; private XmlElement(Builder builder) { this.elementName = builder.elementName; this.childrenByElement = new HashMap<>(builder.childrenByElement); this.children = Collections.unmodifiableList(new ArrayList<>(builder.children)); this.textContent = builder.textContent; this.attributes = Collections.unmodifiableMap(new HashMap<>(builder.attributes)); } /** * @return Tag name of the element. */ public String elementName() { return elementName; } /** * @return The list of direct children of this element. May be empty. */ public List<XmlElement> children() { return children; } /** * @return The first child element of this element. Null if this element has no children. */ public XmlElement getFirstChild() { return children.isEmpty() ? null : children.get(0); } /** * Get all child elements by the given tag name. This only returns direct children elements. * * @param tagName Tag name of elements to retrieve. * @return List of elements or empty list of no elements found with given name. */ public List<XmlElement> getElementsByName(String tagName) { return childrenByElement.getOrDefault(tagName, Collections.emptyList()); } /** * 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; } /** * 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 Fulfilled {@link Optional} of XmlElement with the matching tag name or empty {@link Optional} if no element exists. * @throws SdkClientException If more than one element with the given tag name is found. */ public Optional<XmlElement> getOptionalElementByName(String tagName) { return Optional.ofNullable(getElementByName(tagName)); } /** * @return Text content of this element. */ public String textContent() { return textContent; } /** * Retrieves an optional attribute by attribute name. */ public Optional<String> getOptionalAttributeByName(String attribute) { return Optional.ofNullable(attributes.get(attribute)); } /** * Retrieves the attributes associated with the element */ public Map<String, String> attributes() { return attributes; } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * @return An empty {@link XmlElement} (<eof/>). */ public static XmlElement empty() { return EMPTY; } /** * Builder for {@link XmlElement}. */ public static final class Builder { private String elementName; private final Map<String, List<XmlElement>> childrenByElement = new HashMap<>(); private final List<XmlElement> children = new ArrayList<>(); private String textContent = ""; private Map<String, String> attributes = new HashMap<>(); private Builder() { } public Builder elementName(String elementName) { this.elementName = elementName; return this; } public Builder addChildElement(XmlElement childElement) { this.childrenByElement.computeIfAbsent(childElement.elementName(), s -> new ArrayList<>()); this.childrenByElement.get(childElement.elementName()).add(childElement); this.children.add(childElement); return this; } public Builder textContent(String textContent) { this.textContent = textContent; return this; } public Builder attributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public XmlElement build() { return new XmlElement(this); } } }
2,237
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlErrorUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.unmarshall; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Interface to unmarshall a AWS/QUERY or REST/XML error response. */ @SdkProtectedApi public interface XmlErrorUnmarshaller { /** * @param sdkPojo Builder for exception class to unmarshall. * @param resultRoot Parsed XML document of response. * @param response HTTP response. * @param <TypeT> Type being unmarshalled. * @return Unmarshalled exception */ <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, XmlElement resultRoot, SdkHttpFullResponse response); }
2,238
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlDomParser.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.query.unmarshall; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.LookaheadInputStream; /** * Parses an XML document into a simple DOM like structure, {@link XmlElement}. */ @SdkProtectedApi public final class XmlDomParser { private static final ThreadLocal<XMLInputFactory> FACTORY = ThreadLocal.withInitial(XmlDomParser::createXmlInputFactory); private XmlDomParser() { } public static XmlElement parse(InputStream inputStream) { LookaheadInputStream stream = new LookaheadInputStream(inputStream); try { if (stream.peek() == -1) { return XmlElement.empty(); } XMLEventReader reader = FACTORY.get().createXMLEventReader(stream); XMLEvent nextEvent; // Skip ahead to the first start element do { nextEvent = reader.nextEvent(); } while (reader.hasNext() && !nextEvent.isStartElement()); return parseElement(nextEvent.asStartElement(), reader); } catch (IOException | XMLStreamException e) { throw SdkClientException.create("Could not parse XML response.", e); } } /** * Parse an XML elemnt and any nested elements by recursively calling this method. * * @param startElement Start element object containing element name. * @param reader XML reader to get more events. * @return Parsed {@link XmlElement}. */ private static XmlElement parseElement(StartElement startElement, XMLEventReader reader) throws XMLStreamException { XmlElement.Builder elementBuilder = XmlElement.builder() .elementName(startElement.getName().getLocalPart()); if (startElement.getAttributes().hasNext()) { parseAttributes(startElement, elementBuilder); } XMLEvent nextEvent; do { nextEvent = reader.nextEvent(); if (nextEvent.isStartElement()) { elementBuilder.addChildElement(parseElement(nextEvent.asStartElement(), reader)); } else if (nextEvent.isCharacters()) { elementBuilder.textContent(readText(reader, nextEvent.asCharacters().getData())); } } while (!nextEvent.isEndElement()); return elementBuilder.build(); } /** * Parse the attributes of the element. */ @SuppressWarnings("unchecked") private static void parseAttributes(StartElement startElement, XmlElement.Builder elementBuilder) { Iterator<Attribute> iterator = startElement.getAttributes(); Map<String, String> attributes = new HashMap<>(); iterator.forEachRemaining(a -> { String key = a.getName().getPrefix() + ":" + a.getName().getLocalPart(); attributes.put(key, a.getValue()); }); elementBuilder.attributes(attributes); } /** * Reads all characters until the next end element event. * * @param eventReader Reader to read from. * @param firstChunk Initial character data that's already been read. * @return String with all character data concatenated. */ private static String readText(XMLEventReader eventReader, String firstChunk) throws XMLStreamException { StringBuilder sb = new StringBuilder(firstChunk); while (true) { XMLEvent event = eventReader.peek(); if (event.isCharacters()) { eventReader.nextEvent(); sb.append(event.asCharacters().getData()); } else { return sb.toString(); } } } /** * Disables certain dangerous features that attempt to automatically fetch DTDs * * See <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet">OWASP XXE Cheat Sheet</a> */ private static XMLInputFactory createXmlInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); return factory; } }
2,239
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlUnmarshallingContextTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @RunWith(MockitoJUnitRunner.class) public class AwsXmlUnmarshallingContextTest { private static final XmlElement XML_ELEMENT_1 = XmlElement.builder().elementName("one").build(); private static final XmlElement XML_ELEMENT_2 = XmlElement.builder().elementName("two").build(); private static final XmlElement XML_ERROR_ELEMENT_1 = XmlElement.builder().elementName("error-one").build(); private static final XmlElement XML_ERROR_ELEMENT_2 = XmlElement.builder().elementName("error-two").build(); private static final ExecutionAttributes EXECUTION_ATTRIBUTES_1 = new ExecutionAttributes().putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1); private static final ExecutionAttributes EXECUTION_ATTRIBUTES_2 = new ExecutionAttributes().putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 2); @Mock private SdkHttpFullResponse mockSdkHttpFullResponse; private AwsXmlUnmarshallingContext minimal() { return AwsXmlUnmarshallingContext.builder().build(); } private AwsXmlUnmarshallingContext maximal() { return AwsXmlUnmarshallingContext.builder() .parsedXml(XML_ELEMENT_1) .parsedErrorXml(XML_ERROR_ELEMENT_1) .isResponseSuccess(true) .sdkHttpFullResponse(mockSdkHttpFullResponse) .executionAttributes(EXECUTION_ATTRIBUTES_1) .build(); } @Test public void builder_minimal() { AwsXmlUnmarshallingContext result = minimal(); assertThat(result.isResponseSuccess()).isNull(); assertThat(result.sdkHttpFullResponse()).isNull(); assertThat(result.parsedRootXml()).isNull(); assertThat(result.executionAttributes()).isNull(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void builder_maximal() { AwsXmlUnmarshallingContext result = maximal(); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.sdkHttpFullResponse()).isEqualTo(mockSdkHttpFullResponse); assertThat(result.parsedRootXml()).isEqualTo(XML_ELEMENT_1); assertThat(result.executionAttributes()).isEqualTo(EXECUTION_ATTRIBUTES_1); assertThat(result.parsedErrorXml()).isEqualTo(XML_ERROR_ELEMENT_1); } @Test public void toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); } @Test public void toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); } @Test public void equals_maximal_positive() { assertThat(maximal()).isEqualTo(maximal()); } @Test public void equals_minimal() { assertThat(minimal()).isEqualTo(minimal()); } @Test public void equals_maximal_negative() { assertThat(maximal().toBuilder().isResponseSuccess(false).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().sdkHttpFullResponse(mock(SdkHttpFullResponse.class)).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().parsedXml(XML_ELEMENT_2).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().parsedErrorXml(XML_ERROR_ELEMENT_2).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().executionAttributes(EXECUTION_ATTRIBUTES_2).build()).isNotEqualTo(maximal()); } @Test public void hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); } @Test public void hashcode_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); } @Test public void hashcode_maximal_negative() { assertThat(maximal().toBuilder().isResponseSuccess(false).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().sdkHttpFullResponse(mock(SdkHttpFullResponse.class)).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().parsedXml(XML_ELEMENT_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().parsedErrorXml(XML_ERROR_ELEMENT_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().executionAttributes(EXECUTION_ATTRIBUTES_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); } }
2,240
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.ImmutableMap; public class AwsXmlResponseHandlerTest { @Test public void handleResponse_awsResponse_shouldAddResponseMetadata() throws Exception { HttpResponseHandler<FakeResponse> delegate = Mockito.mock(HttpResponseHandler.class); AwsXmlResponseHandler<FakeResponse> responseHandler = new AwsXmlResponseHandler<>(delegate); SdkHttpFullResponse response = new TestSdkHttpFullResponse(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); FakeResponse fakeResponse = FakeResponse.builder().build(); Mockito.when(delegate.handle(response, executionAttributes)).thenReturn(fakeResponse); assertThat(responseHandler.handle(response, executionAttributes) .responseMetadata().requestId()).isEqualTo("1234"); } @Test public void handleResponse_nonAwsResponse_shouldReturnDirectly() throws Exception { HttpResponseHandler<SdkPojo> delegate = Mockito.mock(HttpResponseHandler.class); AwsXmlResponseHandler<SdkPojo> responseHandler = new AwsXmlResponseHandler<>(delegate); SdkHttpFullResponse response = new TestSdkHttpFullResponse(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); FakeSdkPojo fakeResponse = new FakeSdkPojo(); Mockito.when(delegate.handle(response, executionAttributes)).thenReturn(fakeResponse); assertThat(responseHandler.handle(response, executionAttributes)).isEqualTo(fakeResponse); } private static final class FakeSdkPojo implements SdkPojo { @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } } private static final class FakeResponse extends AwsResponse { private FakeResponse(Builder builder) { super(builder); } @Override public Builder toBuilder() { return new Builder(); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public static Builder builder() { return new Builder(); } private static final class Builder extends AwsResponse.BuilderImpl { @Override public FakeResponse build() { return new FakeResponse(this); } } } private static class TestSdkHttpFullResponse implements SdkHttpFullResponse { @Override public Builder toBuilder() { return null; } @Override public Optional<AbortableInputStream> content() { return Optional.empty(); } @Override public Optional<String> statusText() { return Optional.empty(); } @Override public int statusCode() { return 0; } @Override public Map<String, List<String>> headers() { return ImmutableMap.of(AWS_REQUEST_ID, Collections.singletonList("1234")); } } }
2,241
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/DecorateErrorFromResponseBodyUnmarshallerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import java.util.function.Function; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; public class DecorateErrorFromResponseBodyUnmarshallerTest { private static final Function<XmlElement, Optional<XmlElement>> FAIL_TEST_ERROR_ROOT_LOCATOR = ignored -> { throw new RuntimeException("This function should not have been called"); }; @Test public void status200_noBody() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status200_bodyWithNoError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); XmlElement parsedBody = XmlElement.builder() .elementName("ValidResponse") .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status200_bodyWithError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); XmlElement parsedError = XmlElement.builder() .elementName("test-error") .build(); XmlElement parsedBody = XmlElement.builder() .elementName("Error") .addChildElement(parsedError) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isSameAs(parsedBody); } @Test public void status500_noBody() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status500_bodyWithNoError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); XmlElement parsedBody = XmlElement.builder() .elementName("ValidResponse") .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status500_bodyWithError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); XmlElement parsedError = XmlElement.builder() .elementName("test-error") .build(); XmlElement parsedBody = XmlElement.builder() .elementName("Error") .addChildElement(parsedError) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isSameAs(parsedError); } }
2,242
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/AwsS3ProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler; import software.amazon.awssdk.protocols.xml.internal.unmarshall.DecorateErrorFromResponseBodyUnmarshaller; /** * Factory to generate the various protocol handlers and generators to be used for communicating with * Amazon S3. S3 has some unique differences from typical REST/XML that warrant a custom protocol factory. */ @SdkProtectedApi public final class AwsS3ProtocolFactory extends AwsXmlProtocolFactory { private AwsS3ProtocolFactory(Builder builder) { super(builder); } /** * For Amazon S3, the Code, Message, and modeled fields are in the top level document. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ @Override Optional<XmlElement> getErrorRoot(XmlElement document) { return Optional.of(document); } public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsS3ProtocolFactory}. */ public static final class Builder extends AwsXmlProtocolFactory.Builder<Builder> { private Builder() { } @Override public AwsS3ProtocolFactory build() { return new AwsS3ProtocolFactory(this); } } @Override public <T extends AwsResponse> HttpResponseHandler<Response<T>> createCombinedResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return createErrorCouldBeInBodyResponseHandler(pojoSupplier, staxOperationMetadata); } private <T extends AwsResponse> HttpResponseHandler<Response<T>> createErrorCouldBeInBodyResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return new AwsXmlPredicatedResponseHandler<>(r -> pojoSupplier.get(), createResponseTransformer(pojoSupplier), createErrorTransformer(), DecorateErrorFromResponseBodyUnmarshaller.of(this::getErrorRoot), staxOperationMetadata.isHasStreamingSuccessResponse()); } }
2,243
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/AwsXmlProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler; import software.amazon.awssdk.core.internal.http.CombinedResponseHandler; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.OperationMetadataAttribute; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.xml.internal.marshall.XmlGenerator; import software.amazon.awssdk.protocols.xml.internal.marshall.XmlProtocolMarshaller; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlErrorTransformer; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseHandler; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseTransformer; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlUnmarshallingContext; import software.amazon.awssdk.protocols.xml.internal.unmarshall.XmlProtocolUnmarshaller; import software.amazon.awssdk.protocols.xml.internal.unmarshall.XmlResponseHandler; /** * Factory to generate the various protocol handlers and generators to be used for * communicating with REST/XML services. */ @SdkProtectedApi public class AwsXmlProtocolFactory { /** * Attribute for configuring the XML namespace to include in the xmlns attribute of the root element. */ public static final OperationMetadataAttribute<String> XML_NAMESPACE_ATTRIBUTE = new OperationMetadataAttribute<>(String.class); /** * Some services like Route53 specifies the location for the request shape. This should be the root of the * generated xml document. * * Other services Cloudfront, s3 don't specify location param for the request shape. For them, this value will be null. */ public static final OperationMetadataAttribute<String> ROOT_MARSHALL_LOCATION_ATTRIBUTE = new OperationMetadataAttribute<>(String.class); private static final XmlProtocolUnmarshaller XML_PROTOCOL_UNMARSHALLER = XmlProtocolUnmarshaller.create(); private final List<ExceptionMetadata> modeledExceptions; private final Supplier<SdkPojo> defaultServiceExceptionSupplier; private final HttpResponseHandler<AwsServiceException> errorUnmarshaller; private final SdkClientConfiguration clientConfiguration; AwsXmlProtocolFactory(Builder<?> builder) { this.modeledExceptions = unmodifiableList(builder.modeledExceptions); this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier; this.clientConfiguration = builder.clientConfiguration; this.errorUnmarshaller = timeUnmarshalling( AwsXmlErrorProtocolUnmarshaller.builder() .defaultExceptionSupplier(defaultServiceExceptionSupplier) .exceptions(modeledExceptions) .errorUnmarshaller(XML_PROTOCOL_UNMARSHALLER) .errorRootExtractor(this::getErrorRoot) .build()); } /** * Creates an instance of {@link XmlProtocolMarshaller} to be used for marshalling the request. * * @param operationInfo Info required to marshall the request */ public ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller(OperationInfo operationInfo) { return XmlProtocolMarshaller.builder() .endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)) .xmlGenerator(createGenerator(operationInfo)) .operationInfo(operationInfo) .build(); } public <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return createResponseHandler(r -> pojoSupplier.get(), staxOperationMetadata); } public <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return timeUnmarshalling( new AwsXmlResponseHandler<>( new XmlResponseHandler<>( XML_PROTOCOL_UNMARSHALLER, pojoSupplier, staxOperationMetadata.isHasStreamingSuccessResponse()))); } protected <T extends AwsResponse> Function<AwsXmlUnmarshallingContext, T> createResponseTransformer( Supplier<SdkPojo> pojoSupplier) { return new AwsXmlResponseTransformer<>( XML_PROTOCOL_UNMARSHALLER, r -> pojoSupplier.get()); } protected Function<AwsXmlUnmarshallingContext, AwsServiceException> createErrorTransformer() { return AwsXmlErrorTransformer.builder() .defaultExceptionSupplier(defaultServiceExceptionSupplier) .exceptions(modeledExceptions) .errorUnmarshaller(XML_PROTOCOL_UNMARSHALLER) .build(); } public HttpResponseHandler<AwsServiceException> createErrorResponseHandler() { return errorUnmarshaller; } private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) { return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate); } public <T extends AwsResponse> HttpResponseHandler<Response<T>> createCombinedResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return new CombinedResponseHandler<>(createResponseHandler(pojoSupplier, staxOperationMetadata), createErrorResponseHandler()); } /** * Extracts the <Error/> element from the root XML document. This method is protected as S3 has * a slightly different location. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ Optional<XmlElement> getErrorRoot(XmlElement document) { return document.getOptionalElementByName("Error"); } private XmlGenerator createGenerator(OperationInfo operationInfo) { return operationInfo.hasPayloadMembers() ? XmlGenerator.create(operationInfo.addtionalMetadata(XML_NAMESPACE_ATTRIBUTE)) : null; } public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlProtocolFactory}. */ public static class Builder<SubclassT extends Builder> { private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>(); private Supplier<SdkPojo> defaultServiceExceptionSupplier; private SdkClientConfiguration clientConfiguration; Builder() { } /** * Registers a new modeled exception by the error code. * * @param errorMetadata metadata for unmarshalling the exceptions * @return This builder for method chaining. */ public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) { modeledExceptions.add(errorMetadata); return getSubclass(); } /** * A supplier for the services base exception builder. This is used when we can't identify any modeled * exception to unmarshall into. * * @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder. * @return This builder for method chaining. */ public SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) { this.defaultServiceExceptionSupplier = exceptionBuilderSupplier; return getSubclass(); } /** * Sets the {@link SdkClientConfiguration} which contains the service endpoint. * * @param clientConfiguration Configuration of the client. * @return This builder for method chaining. */ public SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; return getSubclass(); } @SuppressWarnings("unchecked") private SubclassT getSubclass() { return (SubclassT) this; } public AwsXmlProtocolFactory build() { return new AwsXmlProtocolFactory(this); } } }
2,244
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/XmlOperationMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseHandler; /** * Contains information needed to create a {@link AwsXmlResponseHandler} for the client. */ @NotThreadSafe @SdkProtectedApi public final class XmlOperationMetadata { private boolean hasStreamingSuccessResponse; public XmlOperationMetadata() { } private XmlOperationMetadata(Builder b) { this.hasStreamingSuccessResponse = b.hasStreamingSuccessResponse; } public boolean isHasStreamingSuccessResponse() { return hasStreamingSuccessResponse; } public XmlOperationMetadata withHasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) { this.hasStreamingSuccessResponse = hasStreamingSuccessResponse; return this; } public static Builder builder() { return new Builder(); } public static class Builder { private boolean hasStreamingSuccessResponse; public Builder hasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) { this.hasStreamingSuccessResponse = hasStreamingSuccessResponse; return this; } public XmlOperationMetadata build() { return new XmlOperationMetadata(this); } } }
2,245
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlPredicatedResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static software.amazon.awssdk.core.SdkStandardLogger.logRequestId; import java.util.Optional; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.utils.IoUtils; /** * Unmarshalls an HTTP response into either a successful response POJO, or into a (possibly modeled) exception based * on a predicate that the unmarshalled response can be tested against. Returns a wrapper {@link Response} object which * may contain either the unmarshalled success POJO, or the unmarshalled exception. * * @param <OutputT> Type of successful unmarshalled POJO. */ @SdkInternalApi public class AwsXmlPredicatedResponseHandler<OutputT> implements HttpResponseHandler<Response<OutputT>> { private static final Logger log = LoggerFactory.getLogger(AwsXmlPredicatedResponseHandler.class); private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; private final Function<AwsXmlUnmarshallingContext, OutputT> successResponseTransformer; private final Function<AwsXmlUnmarshallingContext, ? extends SdkException> errorResponseTransformer; private final Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> decorateContextWithError; private final boolean needsConnectionLeftOpen; /** * Standard constructor * @param pojoSupplier A method that supplies an empty builder of the correct type * @param successResponseTransformer A function that can unmarshall a response object from parsed XML * @param errorResponseTransformer A function that can unmarshall an exception object from parsed XML * @param decorateContextWithError A function that determines if the response was an error or not * @param needsConnectionLeftOpen true if the underlying connection should not be closed once parsed */ public AwsXmlPredicatedResponseHandler( Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, Function<AwsXmlUnmarshallingContext, OutputT> successResponseTransformer, Function<AwsXmlUnmarshallingContext, ? extends SdkException> errorResponseTransformer, Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> decorateContextWithError, boolean needsConnectionLeftOpen) { this.pojoSupplier = pojoSupplier; this.successResponseTransformer = successResponseTransformer; this.errorResponseTransformer = errorResponseTransformer; this.decorateContextWithError = decorateContextWithError; this.needsConnectionLeftOpen = needsConnectionLeftOpen; } /** * Handle a response * @param httpResponse The HTTP response object * @param executionAttributes The attributes attached to this particular execution. * @return A wrapped response object with the unmarshalled result in it. */ @Override public Response<OutputT> handle(SdkHttpFullResponse httpResponse, ExecutionAttributes executionAttributes) { boolean didRequestFail = true; try { Response<OutputT> response = handleResponse(httpResponse, executionAttributes); didRequestFail = !response.isSuccess(); return response; } finally { closeInputStreamIfNeeded(httpResponse, didRequestFail); } } private Response<OutputT> handleResponse(SdkHttpFullResponse httpResponse, ExecutionAttributes executionAttributes) { AwsXmlUnmarshallingContext parsedResponse = parseResponse(httpResponse, executionAttributes); parsedResponse = decorateContextWithError.apply(parsedResponse); logRequestId(httpResponse); if (parsedResponse.isResponseSuccess()) { OutputT response = handleSuccessResponse(parsedResponse); return Response.<OutputT>builder().httpResponse(httpResponse) .response(response) .isSuccess(true) .build(); } else { return Response.<OutputT>builder().httpResponse(httpResponse) .exception(handleErrorResponse(parsedResponse)) .isSuccess(false) .build(); } } private AwsXmlUnmarshallingContext parseResponse(SdkHttpFullResponse httpFullResponse, ExecutionAttributes executionAttributes) { XmlElement document = XmlResponseParserUtils.parse(pojoSupplier.apply(httpFullResponse), httpFullResponse); return AwsXmlUnmarshallingContext.builder() .parsedXml(document) .executionAttributes(executionAttributes) .sdkHttpFullResponse(httpFullResponse) .build(); } /** * Handles a successful response from a service call by unmarshalling the results using the * specified response handler. * * @return The contents of the response, unmarshalled using the specified response handler. */ private OutputT handleSuccessResponse(AwsXmlUnmarshallingContext parsedResponse) { try { return successResponseTransformer.apply(parsedResponse); } catch (RetryableException e) { throw e; } catch (Exception e) { if (e instanceof SdkException && ((SdkException) e).retryable()) { throw (SdkException) e; } String errorMessage = "Unable to unmarshall response (" + e.getMessage() + "). Response Code: " + parsedResponse.sdkHttpFullResponse().statusCode() + ", Response Text: " + parsedResponse.sdkHttpFullResponse().statusText().orElse(null); throw SdkClientException.builder().message(errorMessage).cause(e).build(); } } /** * Responsible for handling an error response, including unmarshalling the error response * into the most specific exception type possible, and throwing the exception. */ private SdkException handleErrorResponse(AwsXmlUnmarshallingContext parsedResponse) { try { SdkException exception = errorResponseTransformer.apply(parsedResponse); exception.fillInStackTrace(); return exception; } catch (Exception e) { String errorMessage = String.format("Unable to unmarshall error response (%s). " + "Response Code: %d, Response Text: %s", e.getMessage(), parsedResponse.sdkHttpFullResponse().statusCode(), parsedResponse.sdkHttpFullResponse().statusText().orElse("null")); throw SdkClientException.builder().message(errorMessage).cause(e).build(); } } /** * Close the input stream if required. */ private void closeInputStreamIfNeeded(SdkHttpFullResponse httpResponse, boolean didRequestFail) { // Always close on failed requests. Close on successful requests unless it needs connection left open if (didRequestFail || !needsConnectionLeftOpen) { Optional.ofNullable(httpResponse) .flatMap(SdkHttpFullResponse::content) // If no content, no need to close .ifPresent(s -> IoUtils.closeQuietly(s, log)); } } }
2,246
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/DecorateErrorFromResponseBodyUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import java.util.Optional; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A function that decorates a {@link AwsXmlUnmarshallingContext} that already contains the parsed XML of the * response body with parsed error XML if the HTTP response status indicates failure or a serialized error is found * in the XML body of a 'successful' response. This is a non-standard error handling behavior that is used by some * non-streaming S3 operations. */ @SdkInternalApi public class DecorateErrorFromResponseBodyUnmarshaller implements Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> { private static final String ERROR_IN_SUCCESS_BODY_ELEMENT_NAME = "Error"; private final Function<XmlElement, Optional<XmlElement>> errorRootLocationFunction; private DecorateErrorFromResponseBodyUnmarshaller(Function<XmlElement, Optional<XmlElement>> errorRootLocationFunction) { this.errorRootLocationFunction = errorRootLocationFunction; } /** * Constructs a function that can be used to decorate a parsed error from a response if one is found. * @param errorRootFunction A function that can be used to locate the root of the serialized error in the XML * body if the HTTP status code of the response indicates an error. This function is not * applied for HTTP responses that indicate success, instead the root of the document * will always be checked for an element tagged 'Error'. * @return An unmarshalling function that will decorate the unmarshalling context with a parsed error if one is * found in the response. */ public static DecorateErrorFromResponseBodyUnmarshaller of(Function<XmlElement, Optional<XmlElement>> errorRootFunction) { return new DecorateErrorFromResponseBodyUnmarshaller(errorRootFunction); } @Override public AwsXmlUnmarshallingContext apply(AwsXmlUnmarshallingContext context) { Optional<XmlElement> parsedRootXml = Optional.ofNullable(context.parsedRootXml()); if (!context.sdkHttpFullResponse().isSuccessful()) { // Request was non-2xx, defer to protocol handler for error root Optional<XmlElement> parsedErrorXml = parsedRootXml.flatMap(errorRootLocationFunction); return context.toBuilder().isResponseSuccess(false).parsedErrorXml(parsedErrorXml.orElse(null)).build(); } // Check body to see if an error turned up there Optional<XmlElement> parsedErrorXml = parsedRootXml.isPresent() ? getErrorRootFromSuccessBody(context.parsedRootXml()) : Optional.empty(); // Request had an HTTP success code, but an error was found in the body return parsedErrorXml.map(xmlElement -> context.toBuilder() .isResponseSuccess(false) .parsedErrorXml(xmlElement) .build()) // Otherwise the response can be considered successful .orElseGet(() -> context.toBuilder() .isResponseSuccess(true) .build()); } private static Optional<XmlElement> getErrorRootFromSuccessBody(XmlElement document) { return ERROR_IN_SUCCESS_BODY_ELEMENT_NAME.equals(document.elementName()) ? Optional.of(document) : Optional.empty(); } }
2,247
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Interface to unmarshall response fields for Xml service * * @param <T> Type to unmarshall into */ @SdkInternalApi public interface XmlUnmarshaller<T> { T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field); }
2,248
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Response handler that adds {@link AwsResponseMetadata} to the response. * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class AwsXmlResponseHandler<T> implements HttpResponseHandler<T> { private final HttpResponseHandler<T> delegate; public AwsXmlResponseHandler(HttpResponseHandler<T> responseHandler) { this.delegate = responseHandler; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { T result = delegate.handle(response, executionAttributes); if (result instanceof AwsResponse) { AwsResponseMetadata responseMetadata = generateResponseMetadata(response); return (T) ((AwsResponse) result).toBuilder().responseMetadata(responseMetadata).build(); } return result; } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) { Map<String, String> metadata = new HashMap<>(); metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null)); response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } @Override public boolean needsConnectionLeftOpen() { return delegate.needsConnectionLeftOpen(); } }
2,249
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; @SdkInternalApi public final class XmlUnmarshallerRegistry extends AbstractMarshallingRegistry { private XmlUnmarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> XmlUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return (XmlUnmarshaller<Object>) get(marshallLocation, marshallingType); } /** * @return Builder instance to construct a {@link XmlUnmarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlUnmarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder payloadUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } public <T> Builder headerUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.HEADER, marshallingType, marshaller); return this; } public <T> Builder statusCodeUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.STATUS_CODE, marshallingType, marshaller); return this; } /** * @return An immutable {@link XmlUnmarshallerRegistry} object. */ public XmlUnmarshallerRegistry build() { return new XmlUnmarshallerRegistry(this); } } }
2,250
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/HeaderUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static software.amazon.awssdk.utils.StringUtils.replacePrefixIgnoreCase; import static software.amazon.awssdk.utils.StringUtils.startsWithIgnoreCase; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class HeaderUnmarshaller { public static final XmlUnmarshaller<String> STRING = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_STRING); public static final XmlUnmarshaller<Integer> INTEGER = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_INTEGER); public static final XmlUnmarshaller<Long> LONG = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_LONG); public static final XmlUnmarshaller<Short> SHORT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_SHORT); public static final XmlUnmarshaller<Float> FLOAT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_FLOAT); public static final XmlUnmarshaller<Double> DOUBLE = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_DOUBLE); public static final XmlUnmarshaller<Boolean> BOOLEAN = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_BOOLEAN); public static final XmlUnmarshaller<Instant> INSTANT = new SimpleHeaderUnmarshaller<>(XmlProtocolUnmarshaller.INSTANT_STRING_TO_VALUE); // Only supports string value type public static final XmlUnmarshaller<Map<String, ?>> MAP = ((context, content, field) -> { Map<String, String> result = new HashMap<>(); context.response().forEachHeader((name, value) -> { if (startsWithIgnoreCase(name, field.locationName())) { result.put(replacePrefixIgnoreCase(name, field.locationName(), ""), String.join(",", value)); } }); return result; }); // Only supports string value type public static final XmlUnmarshaller<List<?>> LIST = (context, content, field) -> context.response().matchingHeaders(field.locationName()); private HeaderUnmarshaller() { } private static class SimpleHeaderUnmarshaller<T> implements XmlUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> stringToValue; private SimpleHeaderUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) { this.stringToValue = stringToValue; } @Override public T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { return context.response().firstMatchingHeader(field.locationName()) .map(s -> stringToValue.convert(s, field)) .orElse(null); } } }
2,251
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A transformer function that takes a parsed XML response and converts it into an {@link AwsResponse}. Used * as a component in the {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public final class AwsXmlResponseTransformer<T extends AwsResponse> implements Function<AwsXmlUnmarshallingContext, T> { private static final String X_AMZN_REQUEST_ID_HEADER = "x-amzn-RequestId"; private final XmlProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; public AwsXmlResponseTransformer(XmlProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; } @Override public T apply(AwsXmlUnmarshallingContext context) { return unmarshallResponse(context.sdkHttpFullResponse(), context.parsedRootXml()); } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response, XmlElement parsedXml) { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Unmarshalling parsed service response XML."); T result = unmarshaller.unmarshall(pojoSupplier.apply(response), parsedXml, response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done unmarshalling parsed service response."); AwsResponseMetadata responseMetadata = generateResponseMetadata(response); return (T) result.toBuilder().responseMetadata(responseMetadata).build(); } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) { Map<String, String> metadata = new HashMap<>(); metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER).orElse(null)); response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } }
2,252
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlPayloadUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static java.util.Collections.singletonList; import java.math.BigDecimal; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class XmlPayloadUnmarshaller { public static final XmlUnmarshaller<String> STRING = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_STRING); public static final XmlUnmarshaller<Integer> INTEGER = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_INTEGER); public static final XmlUnmarshaller<Long> LONG = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_LONG); public static final XmlUnmarshaller<Short> SHORT = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_SHORT); public static final XmlUnmarshaller<Float> FLOAT = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_FLOAT); public static final XmlUnmarshaller<Double> DOUBLE = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_DOUBLE); public static final XmlUnmarshaller<BigDecimal> BIG_DECIMAL = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_BIG_DECIMAL); public static final XmlUnmarshaller<Boolean> BOOLEAN = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_BOOLEAN); public static final XmlUnmarshaller<Instant> INSTANT = new SimpleTypePayloadUnmarshaller<>(XmlProtocolUnmarshaller.INSTANT_STRING_TO_VALUE); public static final XmlUnmarshaller<SdkBytes> SDK_BYTES = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_SDK_BYTES); private XmlPayloadUnmarshaller() { } public static SdkPojo unmarshallSdkPojo(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<SdkPojo> field) { return context.protocolUnmarshaller() .unmarshall(context, field.constructor().get(), content.get(0)); } public static List<?> unmarshallList(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<List<?>> field) { ListTrait listTrait = field.getTrait(ListTrait.class); List<Object> list = new ArrayList<>(); getMembers(content, listTrait).forEach(member -> { XmlUnmarshaller unmarshaller = context.getUnmarshaller(listTrait.memberFieldInfo().location(), listTrait.memberFieldInfo().marshallingType()); list.add(unmarshaller.unmarshall(context, singletonList(member), listTrait.memberFieldInfo())); }); return list; } private static List<XmlElement> getMembers(List<XmlElement> content, ListTrait listTrait) { String memberLocation = listTrait.memberLocationName() != null ? listTrait.memberLocationName() : listTrait.memberFieldInfo().locationName(); return listTrait.isFlattened() ? content : content.get(0).getElementsByName(memberLocation); } public static Map<String, ?> unmarshallMap(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<Map<String, ?>> field) { Map<String, Object> map = new HashMap<>(); MapTrait mapTrait = field.getTrait(MapTrait.class); SdkField mapValueSdkField = mapTrait.valueFieldInfo(); getEntries(content, mapTrait).forEach(entry -> { XmlElement key = entry.getElementByName(mapTrait.keyLocationName()); XmlElement value = entry.getElementByName(mapTrait.valueLocationName()); XmlUnmarshaller unmarshaller = context.getUnmarshaller(mapValueSdkField.location(), mapValueSdkField.marshallingType()); map.put(key.textContent(), unmarshaller.unmarshall(context, singletonList(value), mapValueSdkField)); }); return map; } private static List<XmlElement> getEntries(List<XmlElement> content, MapTrait mapTrait) { return mapTrait.isFlattened() ? content : content.get(0).getElementsByName("entry"); } /** * Base payload unmarshaller for simple types of xml protocol * @param <T> Type to unmarshall */ private static class SimpleTypePayloadUnmarshaller<T> implements XmlUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> converter; private SimpleTypePayloadUnmarshaller(StringToValueConverter.StringToValue<T> converter) { this.converter = converter; } @Override public T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { if (content == null) { return null; } return converter.convert(content.get(0).textContent(), field); } } }
2,253
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlResponseParserUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.utils.LookaheadInputStream; /** * Static methods to assist with parsing the response of AWS XML requests. */ @SdkInternalApi public final class XmlResponseParserUtils { private XmlResponseParserUtils() { } /** * Parse an XML response if one is expected and available. If we are not expecting a payload, but the HTTP response * code shows an error then we will parse it anyway, as it should contain a serialized error. * @param sdkPojo the SDK builder object associated with the final response * @param response the HTTP response * @return A parsed XML document or an empty XML document if no payload/contents were found in the response. */ public static XmlElement parse(SdkPojo sdkPojo, SdkHttpFullResponse response) { try { Optional<AbortableInputStream> responseContent = response.content(); if (!responseContent.isPresent() || (response.isSuccessful() && !hasPayloadMembers(sdkPojo)) || getBlobTypePayloadMemberToUnmarshal(sdkPojo).isPresent()) { return XmlElement.empty(); } // Make sure there is content in the stream before passing it to the parser. LookaheadInputStream content = new LookaheadInputStream(responseContent.get()); if (content.peek() == -1) { return XmlElement.empty(); } return XmlDomParser.parse(content); } catch (IOException e) { throw new UncheckedIOException(e); } catch (RuntimeException e) { if (response.isSuccessful()) { throw e; } return XmlElement.empty(); } } /** * Gets the Member which is a Payload and which is of Blob Type. * @param sdkPojo * @return Optional of SdkField member if member is Blob type payload else returns Empty. */ public static Optional<SdkField<?>> getBlobTypePayloadMemberToUnmarshal(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .filter(e -> isExplicitPayloadMember(e)) .filter(f -> f.marshallingType() == MarshallingType.SDK_BYTES).findFirst(); } private static boolean isExplicitPayloadMember(SdkField<?> f) { return f.containsTrait(PayloadTrait.class); } private static boolean hasPayloadMembers(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .anyMatch(f -> f.location() == MarshallLocation.PAYLOAD); } }
2,254
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlProtocolUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import static java.util.Collections.singletonList; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.core.traits.XmlAttributeTrait; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.StringToInstant; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.builder.Buildable; @SdkInternalApi public final class XmlProtocolUnmarshaller implements XmlErrorUnmarshaller { public static final StringToValueConverter.StringToValue<Instant> INSTANT_STRING_TO_VALUE = StringToInstant.create(getDefaultTimestampFormats()); private static final XmlUnmarshallerRegistry REGISTRY = createUnmarshallerRegistry(); private XmlProtocolUnmarshaller() { } public static XmlProtocolUnmarshaller create() { return new XmlProtocolUnmarshaller(); } public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, SdkHttpFullResponse response) { XmlElement document = hasXmlPayload(sdkPojo, response) ? XmlResponseParserUtils.parse(sdkPojo, response) : null; return unmarshall(sdkPojo, document, response); } /** * This method is also used to unmarshall exceptions. We use this since we've already parsed the XML * and the result root is in a different location depending on the protocol/service. */ @Override public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, XmlElement resultRoot, SdkHttpFullResponse response) { XmlUnmarshallerContext unmarshallerContext = XmlUnmarshallerContext.builder() .response(response) .registry(REGISTRY) .protocolUnmarshaller(this) .build(); return (TypeT) unmarshall(unmarshallerContext, sdkPojo, resultRoot); } SdkPojo unmarshall(XmlUnmarshallerContext context, SdkPojo sdkPojo, XmlElement root) { for (SdkField<?> field : sdkPojo.sdkFields()) { XmlUnmarshaller<Object> unmarshaller = REGISTRY.getUnmarshaller(field.location(), field.marshallingType()); if (field.location() != MarshallLocation.PAYLOAD) { Object unmarshalled = unmarshaller.unmarshall(context, null, (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); continue; } if (isExplicitPayloadMember(field)) { InputStream content = context.response().content().orElse(null); if (field.marshallingType() == MarshallingType.SDK_BYTES) { SdkBytes value = content == null ? SdkBytes.fromByteArrayUnsafe(new byte[0]) : SdkBytes.fromInputStream(content); field.set(sdkPojo, value); continue; } if (field.marshallingType() == MarshallingType.STRING) { // TODO: If we ever break protected APIs, just parse this as a string and remove XML-wrapping // compatibility for S3. if (content == null) { field.set(sdkPojo, ""); } else { setExplicitStringPayload(unmarshaller, context, sdkPojo, root, field); } continue; } if (root != null && !isAttribute(field)) { Object unmarshalled = unmarshaller.unmarshall(context, singletonList(root), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); continue; } } if (root == null) { continue; } if (isAttribute(field)) { root.getOptionalAttributeByName(field.unmarshallLocationName()) .ifPresent(e -> field.set(sdkPojo, e)); continue; } List<XmlElement> element = root.getElementsByName(field.unmarshallLocationName()); if (!CollectionUtils.isNullOrEmpty(element)) { Object unmarshalled = unmarshaller.unmarshall(context, element, (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } } if (!(sdkPojo instanceof Buildable)) { throw new RuntimeException("The sdkPojo passed to the unmarshaller is not buildable (must implement " + "Buildable)"); } return (SdkPojo) ((Buildable) sdkPojo).build(); } private void setExplicitStringPayload(XmlUnmarshaller<Object> unmarshaller, XmlUnmarshallerContext context, SdkPojo sdkPojo, XmlElement element, SdkField<?> field) { SdkBytes sdkBytes = SdkBytes.fromInputStream(context.response().content().get()); String stringPayload = sdkBytes.asUtf8String(); if (hasS3XmlEnvelopePrefix(stringPayload)) { InputStream inputStream = new ByteArrayInputStream(sdkBytes.asByteArray()); XmlElement document = XmlDomParser.parse(inputStream); Object unmarshalled = unmarshaller.unmarshall(context, singletonList(document), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } else { if (stringPayload.isEmpty()) { if (element == null) { // User passed in empty String field.set(sdkPojo, ""); } else { // InputStream may have already been read Object unmarshalled = unmarshaller.unmarshall(context, singletonList(element), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } } else { field.set(sdkPojo, stringPayload); } } } // Handle S3 GetBucketPolicy(), which returns JSON so we wrap with XML private boolean hasS3XmlEnvelopePrefix(String payload) { String s3XmlEnvelopePrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Policy><![CDATA["; return payload.startsWith(s3XmlEnvelopePrefix); } private boolean isAttribute(SdkField<?> field) { return field.containsTrait(XmlAttributeTrait.class); } private boolean isExplicitPayloadMember(SdkField<?> field) { return field.containsTrait(PayloadTrait.class); } private boolean hasXmlPayload(SdkPojo sdkPojo, SdkHttpFullResponse response) { return sdkPojo.sdkFields() .stream() .anyMatch(f -> isPayloadMemberOnUnmarshall(f) && !isExplicitBlobPayloadMember(f) && !isExplicitStringPayloadMember(f)) && response.content().isPresent(); } private boolean isExplicitBlobPayloadMember(SdkField<?> f) { return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.SDK_BYTES; } private boolean isExplicitStringPayloadMember(SdkField<?> f) { return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.STRING; } private boolean isPayloadMemberOnUnmarshall(SdkField<?> f) { return f.location() == MarshallLocation.PAYLOAD || isInUri(f.location()); } private static boolean isInUri(MarshallLocation location) { switch (location) { case PATH: case QUERY_PARAM: return true; default: return false; } } private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } private static XmlUnmarshallerRegistry createUnmarshallerRegistry() { return XmlUnmarshallerRegistry .builder() .statusCodeUnmarshaller(MarshallingType.INTEGER, (context, content, field) -> context.response().statusCode()) .headerUnmarshaller(MarshallingType.STRING, HeaderUnmarshaller.STRING) .headerUnmarshaller(MarshallingType.INTEGER, HeaderUnmarshaller.INTEGER) .headerUnmarshaller(MarshallingType.LONG, HeaderUnmarshaller.LONG) .headerUnmarshaller(MarshallingType.SHORT, HeaderUnmarshaller.SHORT) .headerUnmarshaller(MarshallingType.DOUBLE, HeaderUnmarshaller.DOUBLE) .headerUnmarshaller(MarshallingType.BOOLEAN, HeaderUnmarshaller.BOOLEAN) .headerUnmarshaller(MarshallingType.INSTANT, HeaderUnmarshaller.INSTANT) .headerUnmarshaller(MarshallingType.FLOAT, HeaderUnmarshaller.FLOAT) .headerUnmarshaller(MarshallingType.MAP, HeaderUnmarshaller.MAP) .headerUnmarshaller(MarshallingType.LIST, HeaderUnmarshaller.LIST) .payloadUnmarshaller(MarshallingType.STRING, XmlPayloadUnmarshaller.STRING) .payloadUnmarshaller(MarshallingType.INTEGER, XmlPayloadUnmarshaller.INTEGER) .payloadUnmarshaller(MarshallingType.LONG, XmlPayloadUnmarshaller.LONG) .payloadUnmarshaller(MarshallingType.SHORT, XmlPayloadUnmarshaller.SHORT) .payloadUnmarshaller(MarshallingType.FLOAT, XmlPayloadUnmarshaller.FLOAT) .payloadUnmarshaller(MarshallingType.DOUBLE, XmlPayloadUnmarshaller.DOUBLE) .payloadUnmarshaller(MarshallingType.BIG_DECIMAL, XmlPayloadUnmarshaller.BIG_DECIMAL) .payloadUnmarshaller(MarshallingType.BOOLEAN, XmlPayloadUnmarshaller.BOOLEAN) .payloadUnmarshaller(MarshallingType.INSTANT, XmlPayloadUnmarshaller.INSTANT) .payloadUnmarshaller(MarshallingType.SDK_BYTES, XmlPayloadUnmarshaller.SDK_BYTES) .payloadUnmarshaller(MarshallingType.SDK_POJO, XmlPayloadUnmarshaller::unmarshallSdkPojo) .payloadUnmarshaller(MarshallingType.LIST, XmlPayloadUnmarshaller::unmarshallList) .payloadUnmarshaller(MarshallingType.MAP, XmlPayloadUnmarshaller::unmarshallMap) .build(); } }
2,255
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlUnmarshallingContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A data class to hold all the context of an unmarshalling stage for the AWS XML protocol as orchestrated by * {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public class AwsXmlUnmarshallingContext { private final SdkHttpFullResponse sdkHttpFullResponse; private final XmlElement parsedXml; private final ExecutionAttributes executionAttributes; private final Boolean isResponseSuccess; private final XmlElement parsedErrorXml; private AwsXmlUnmarshallingContext(Builder builder) { this.sdkHttpFullResponse = builder.sdkHttpFullResponse; this.parsedXml = builder.parsedXml; this.executionAttributes = builder.executionAttributes; this.isResponseSuccess = builder.isResponseSuccess; this.parsedErrorXml = builder.parsedErrorXml; } public static Builder builder() { return new Builder(); } /** * The HTTP response. */ public SdkHttpFullResponse sdkHttpFullResponse() { return sdkHttpFullResponse; } /** * The parsed XML of the body, or null if there was no body. */ public XmlElement parsedRootXml() { return parsedXml; } /** * The {@link ExecutionAttributes} associated with this request. */ public ExecutionAttributes executionAttributes() { return executionAttributes; } /** * true if the response indicates success; false if not; null if that has not been determined yet */ public Boolean isResponseSuccess() { return isResponseSuccess; } /** * The parsed XML of just the error. null if not found or determined yet. */ public XmlElement parsedErrorXml() { return parsedErrorXml; } public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsXmlUnmarshallingContext that = (AwsXmlUnmarshallingContext) o; if (sdkHttpFullResponse != null ? ! sdkHttpFullResponse.equals(that.sdkHttpFullResponse) : that.sdkHttpFullResponse != null) { return false; } if (parsedXml != null ? ! parsedXml.equals(that.parsedXml) : that.parsedXml != null) { return false; } if (executionAttributes != null ? ! executionAttributes.equals(that.executionAttributes) : that.executionAttributes != null) { return false; } if (isResponseSuccess != null ? ! isResponseSuccess.equals(that.isResponseSuccess) : that.isResponseSuccess != null) { return false; } return parsedErrorXml != null ? parsedErrorXml.equals(that.parsedErrorXml) : that.parsedErrorXml == null; } @Override public int hashCode() { int result = sdkHttpFullResponse != null ? sdkHttpFullResponse.hashCode() : 0; result = 31 * result + (parsedXml != null ? parsedXml.hashCode() : 0); result = 31 * result + (executionAttributes != null ? executionAttributes.hashCode() : 0); result = 31 * result + (isResponseSuccess != null ? isResponseSuccess.hashCode() : 0); result = 31 * result + (parsedErrorXml != null ? parsedErrorXml.hashCode() : 0); return result; } public static final class Builder { private SdkHttpFullResponse sdkHttpFullResponse; private XmlElement parsedXml; private ExecutionAttributes executionAttributes; private Boolean isResponseSuccess; private XmlElement parsedErrorXml; private Builder() { } public Builder sdkHttpFullResponse(SdkHttpFullResponse sdkHttpFullResponse) { this.sdkHttpFullResponse = sdkHttpFullResponse; return this; } public Builder parsedXml(XmlElement parsedXml) { this.parsedXml = parsedXml; return this; } public Builder executionAttributes(ExecutionAttributes executionAttributes) { this.executionAttributes = executionAttributes; return this; } public Builder isResponseSuccess(Boolean isResponseSuccess) { this.isResponseSuccess = isResponseSuccess; return this; } public Builder parsedErrorXml(XmlElement parsedErrorXml) { this.parsedErrorXml = parsedErrorXml; return this; } public AwsXmlUnmarshallingContext build() { return new AwsXmlUnmarshallingContext(this); } } }
2,256
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.http.SdkHttpFullResponse; @SdkInternalApi public final class XmlUnmarshallerContext { private final SdkHttpFullResponse response; private final XmlUnmarshallerRegistry registry; private final XmlProtocolUnmarshaller protocolUnmarshaller; private XmlUnmarshallerContext(Builder builder) { this.response = builder.response; this.registry = builder.registry; this.protocolUnmarshaller = builder.protocolUnmarshaller; } /** * @return The {@link SdkHttpFullResponse} of the API call. */ public SdkHttpFullResponse response() { return response; } public XmlProtocolUnmarshaller protocolUnmarshaller() { return protocolUnmarshaller; } public <T> XmlUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return registry.getUnmarshaller(marshallLocation, marshallingType); } /** * @return Builder instance to construct a {@link XmlUnmarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlUnmarshallerContext}. */ public static final class Builder { private SdkHttpFullResponse response; private XmlUnmarshallerRegistry registry; private XmlProtocolUnmarshaller protocolUnmarshaller; private Builder() { } public Builder response(SdkHttpFullResponse response) { this.response = response; return this; } public Builder registry(XmlUnmarshallerRegistry registry) { this.registry = registry; return this; } public Builder protocolUnmarshaller(XmlProtocolUnmarshaller protocolUnmarshaller) { this.protocolUnmarshaller = protocolUnmarshaller; return this; } /** * @return An immutable {@link XmlUnmarshallerContext} object. */ public XmlUnmarshallerContext build() { return new XmlUnmarshallerContext(this); } } }
2,257
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import java.io.IOException; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.Logger; /** * Response handler for REST-XML services (Cloudfront, Route53, and S3). * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class XmlResponseHandler<T extends SdkPojo> implements HttpResponseHandler<T> { private static final Logger log = Logger.loggerFor(XmlResponseHandler.class); private final XmlProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; private final boolean needsConnectionLeftOpen; public XmlResponseHandler(XmlProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, boolean needsConnectionLeftOpen) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; this.needsConnectionLeftOpen = needsConnectionLeftOpen; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { try { return unmarshallResponse(response); } finally { if (!needsConnectionLeftOpen) { closeStream(response); } } } private void closeStream(SdkHttpFullResponse response) { response.content().ifPresent(i -> { try { i.close(); } catch (IOException e) { log.warn(() -> "Error closing HTTP content.", e); } }); } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response) throws Exception { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response XML."); T result = unmarshaller.unmarshall(pojoSupplier.apply(response), response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response."); return result; } @Override public boolean needsConnectionLeftOpen() { return needsConnectionLeftOpen; } }
2,258
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlErrorTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.unmarshall; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; /** * A transformer function that takes a parsed XML response and converts it into an {@link AwsServiceException}. Used * as a component in the {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public final class AwsXmlErrorTransformer implements Function<AwsXmlUnmarshallingContext, AwsServiceException> { private final AwsXmlErrorUnmarshaller awsXmlErrorUnmarshaller; private AwsXmlErrorTransformer(Builder builder) { this.awsXmlErrorUnmarshaller = AwsXmlErrorUnmarshaller.builder() .defaultExceptionSupplier(builder.defaultExceptionSupplier) .exceptions(builder.exceptions) .errorUnmarshaller(builder.errorUnmarshaller) .build(); } @Override public AwsServiceException apply(AwsXmlUnmarshallingContext context) { return awsXmlErrorUnmarshaller.unmarshall(context.parsedRootXml(), Optional.ofNullable(context.parsedErrorXml()), Optional.empty(), context.sdkHttpFullResponse(), context.executionAttributes()); } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlErrorTransformer}. */ public static final class Builder { private List<ExceptionMetadata> exceptions; private Supplier<SdkPojo> defaultExceptionSupplier; private XmlErrorUnmarshaller errorUnmarshaller; private Builder() { } /** * List of {@link ExceptionMetadata} to represent the modeled exceptions for the service. * For AWS services the error type is a string representing the type of the modeled exception. * * @return This builder for method chaining. */ public Builder exceptions(List<ExceptionMetadata> exceptions) { this.exceptions = exceptions; return this; } /** * Default exception type if "error code" does not match any known modeled exception. This is the generated * base exception for the service (i.e. DynamoDbException). * * @return This builder for method chaining. */ public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) { this.defaultExceptionSupplier = defaultExceptionSupplier; return this; } /** * The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception, * additional metadata is extracted by {@link AwsXmlErrorTransformer}. * * @param errorUnmarshaller Error unmarshaller to use. * @return This builder for method chaining. */ public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) { this.errorUnmarshaller = errorUnmarshaller; return this; } /** * @return New instance of {@link AwsXmlErrorTransformer}. */ public AwsXmlErrorTransformer build() { return new AwsXmlErrorTransformer(this); } } }
2,259
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlPayloadMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import java.math.BigDecimal; import java.time.Instant; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.core.traits.XmlAttributeTrait; import software.amazon.awssdk.core.traits.XmlAttributesTrait; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public class XmlPayloadMarshaller { public static final XmlMarshaller<String> STRING = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Float> FLOAT = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Double> DOUBLE = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<BigDecimal> BIG_DECIMAL = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_BIG_DECIMAL); public static final XmlMarshaller<Boolean> BOOLEAN = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new BasePayloadMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<SdkBytes> SDK_BYTES = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_SDK_BYTES); public static final XmlMarshaller<SdkPojo> SDK_POJO = new BasePayloadMarshaller<SdkPojo>(null) { @Override public void marshall(SdkPojo val, XmlMarshallerContext context, String paramName, SdkField<SdkPojo> sdkField, ValueToStringConverter.ValueToString<SdkPojo> converter) { context.protocolMarshaller().doMarshall(val); } }; public static final XmlMarshaller<List<?>> LIST = new BasePayloadMarshaller<List<?>>(null) { @Override public void marshall(List<?> val, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField) { if (!shouldEmit(val, paramName)) { return; } marshall(val, context, paramName, sdkField, null); } @Override public void marshall(List<?> list, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField, ValueToStringConverter.ValueToString<List<?>> converter) { ListTrait listTrait = sdkField.getRequiredTrait(ListTrait.class); if (!listTrait.isFlattened()) { context.xmlGenerator().startElement(paramName); } SdkField memberField = listTrait.memberFieldInfo(); String memberLocationName = listMemberLocationName(listTrait, paramName); for (Object listMember : list) { context.marshall(MarshallLocation.PAYLOAD, listMember, memberLocationName, memberField); } if (!listTrait.isFlattened()) { context.xmlGenerator().endElement(); } } private String listMemberLocationName(ListTrait listTrait, String listLocationName) { String locationName = listTrait.memberLocationName(); if (locationName == null) { locationName = listTrait.isFlattened() ? listLocationName : "member"; } return locationName; } @Override protected boolean shouldEmit(List list, String paramName) { return super.shouldEmit(list, paramName) && (!list.isEmpty() || !(list instanceof SdkAutoConstructList)); } }; // We ignore flattened trait for maps. For rest-xml, none of the services have flattened maps public static final XmlMarshaller<Map<String, ?>> MAP = new BasePayloadMarshaller<Map<String, ?>>(null) { @Override public void marshall(Map<String, ?> map, XmlMarshallerContext context, String paramName, SdkField<Map<String, ?>> sdkField, ValueToStringConverter.ValueToString<Map<String, ?>> converter) { MapTrait mapTrait = sdkField.getRequiredTrait(MapTrait.class); for (Map.Entry<String, ?> entry : map.entrySet()) { context.xmlGenerator().startElement("entry"); context.marshall(MarshallLocation.PAYLOAD, entry.getKey(), mapTrait.keyLocationName(), null); context.marshall(MarshallLocation.PAYLOAD, entry.getValue(), mapTrait.valueLocationName(), mapTrait.valueFieldInfo()); context.xmlGenerator().endElement(); } } @Override protected boolean shouldEmit(Map map, String paramName) { return super.shouldEmit(map, paramName) && (!map.isEmpty() || !(map instanceof SdkAutoConstructMap)); } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private XmlPayloadMarshaller() { } /** * Base payload marshaller for xml protocol. Marshalling happens only when both element name and value are present. * * Marshalling for simple types is done in the base class. * Complex types should override the * {@link #marshall(Object, XmlMarshallerContext, String, SdkField, ValueToStringConverter.ValueToString)} method. * * @param <T> Type to marshall */ private static class BasePayloadMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private BasePayloadMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { if (!shouldEmit(val, paramName)) { return; } // Should ignore marshalling for xml attribute if (isXmlAttribute(sdkField)) { return; } if (sdkField != null && sdkField.getOptionalTrait(XmlAttributesTrait.class).isPresent()) { XmlAttributesTrait attributeTrait = sdkField.getTrait(XmlAttributesTrait.class); Map<String, String> attributes = attributeTrait.attributes() .entrySet() .stream() .collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue() .attributeGetter() .apply(val)), HashMap::putAll); context.xmlGenerator().startElement(paramName, attributes); } else { context.xmlGenerator().startElement(paramName); } marshall(val, context, paramName, sdkField, converter); context.xmlGenerator().endElement(); } void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField, ValueToStringConverter.ValueToString<T> converter) { context.xmlGenerator().xmlWriter().value(converter.convert(val, sdkField)); } protected boolean shouldEmit(T val, String paramName) { return val != null && paramName != null; } private boolean isXmlAttribute(SdkField<T> sdkField) { return sdkField != null && sdkField.getOptionalTrait(XmlAttributeTrait.class).isPresent(); } } }
2,260
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; @SdkInternalApi public final class XmlMarshallerRegistry extends AbstractMarshallingRegistry { private XmlMarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> XmlMarshaller<T> getMarshaller(MarshallLocation marshallLocation, T val) { return (XmlMarshaller<T>) get(marshallLocation, toMarshallingType(val)); } @SuppressWarnings("unchecked") public <T> XmlMarshaller<Object> getMarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType, Object val) { return (XmlMarshaller<Object>) get(marshallLocation, val == null ? MarshallingType.NULL : marshallingType); } /** * @return Builder instance to construct a {@link XmlMarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlMarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder payloadMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } public <T> Builder headerMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.HEADER, marshallingType, marshaller); return this; } public <T> Builder queryParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.QUERY_PARAM, marshallingType, marshaller); return this; } public <T> Builder pathParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.PATH, marshallingType, marshaller); return this; } public <T> Builder greedyPathParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.GREEDY_PATH, marshallingType, marshaller); return this; } /** * @return An immutable {@link XmlMarshallerRegistry} object. */ public XmlMarshallerRegistry build() { return new XmlMarshallerRegistry(this); } } }
2,261
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/SimpleTypePathMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.PathMarshaller; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class SimpleTypePathMarshaller { public static final XmlMarshaller<String> STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Integer> INTEGER = new SimplePathMarshaller<>(ValueToStringConverter.FROM_INTEGER, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Long> LONG = new SimplePathMarshaller<>(ValueToStringConverter.FROM_LONG, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Short> SHORT = new SimplePathMarshaller<>(ValueToStringConverter.FROM_SHORT, PathMarshaller.NON_GREEDY); /** * Marshallers for Strings bound to a greedy path param. No URL encoding is done on the string * so that it preserves the path structure. */ public static final XmlMarshaller<String> GREEDY_STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.GREEDY_WITH_SLASHES); public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); }; private SimpleTypePathMarshaller() { } private static class SimplePathMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private final PathMarshaller pathMarshaller; private SimplePathMarshaller(ValueToStringConverter.ValueToString<T> converter, PathMarshaller pathMarshaller) { this.converter = converter; this.pathMarshaller = pathMarshaller; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().encodedPath( pathMarshaller.marshall(context.request().encodedPath(), paramName, converter.convert(val, sdkField))); } } }
2,262
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/HeaderMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import static software.amazon.awssdk.utils.CollectionUtils.isNullOrEmpty; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class HeaderMarshaller { public static final XmlMarshaller<String> STRING = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Double> DOUBLE = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<Float> FLOAT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Boolean> BOOLEAN = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new SimpleHeaderMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<Map<String, ?>> MAP = new SimpleHeaderMarshaller<Map<String, ?>>(null) { @Override public void marshall(Map<String, ?> map, XmlMarshallerContext context, String paramName, SdkField<Map<String, ?>> sdkField) { if (!shouldEmit(map)) { return; } for (Map.Entry<String, ?> entry : map.entrySet()) { String key = entry.getKey().startsWith(paramName) ? entry.getKey() : paramName + entry.getKey(); XmlMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, entry.getValue()); marshaller.marshall(entry.getValue(), context, key, null); } } @Override protected boolean shouldEmit(Map map) { return !isNullOrEmpty(map); } }; public static final XmlMarshaller<List<?>> LIST = new SimpleHeaderMarshaller<List<?>>(null) { @Override public void marshall(List<?> list, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField) { if (!shouldEmit(list)) { return; } SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo(); for (Object listValue : list) { if (shouldSkipElement(listValue)) { continue; } XmlMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, listValue); marshaller.marshall(listValue, context, paramName, memberFieldInfo); } } private boolean shouldSkipElement(Object element) { return element instanceof String && StringUtils.isBlank((String) element); } @Override protected boolean shouldEmit(List list) { // Null or empty lists cannot be meaningfully (or safely) represented in an HTTP header message since header-fields // must typically have a non-empty field-value. https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 return !isNullOrEmpty(list); } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private HeaderMarshaller() { } private static class SimpleHeaderMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleHeaderMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { if (!shouldEmit(val)) { return; } context.request().appendHeader(paramName, converter.convert(val, sdkField)); } protected boolean shouldEmit(T val) { return val != null; } } }
2,263
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import java.io.StringWriter; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Wrapper around the {@link XmlWriter} for marshalling requests for XML protocol */ @SdkInternalApi public final class XmlGenerator { private final StringWriter stringWriter; private final XmlWriter xmlWriter; private XmlGenerator(StringWriter stringWriter, XmlWriter xmlWriter) { this.stringWriter = stringWriter; this.xmlWriter = xmlWriter; } public static XmlGenerator create(String xmlns) { StringWriter stringWriter = new StringWriter(); return new XmlGenerator(stringWriter, new XmlWriter(stringWriter, xmlns)); } public XmlWriter xmlWriter() { return xmlWriter; } public StringWriter stringWriter() { return stringWriter; } public void startElement(String element) { xmlWriter.startElement(element); } /** * Start to write the element * * @param element the element to write * @param attributes the attributes */ public void startElement(String element, Map<String, String> attributes) { xmlWriter.startElement(element, attributes); } public void endElement() { xmlWriter.endElement(); } }
2,264
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.http.SdkHttpFullRequest; @SdkInternalApi public final class XmlMarshallerContext { private final XmlGenerator xmlGenerator; private final XmlProtocolMarshaller protocolMarshaller; private final XmlMarshallerRegistry marshallerRegistry; private final SdkHttpFullRequest.Builder request; public XmlMarshallerContext(Builder builder) { this.xmlGenerator = builder.xmlGenerator; this.protocolMarshaller = builder.protocolMarshaller; this.marshallerRegistry = builder.marshallerRegistry; this.request = builder.request; } public XmlGenerator xmlGenerator() { return xmlGenerator; } public XmlProtocolMarshaller protocolMarshaller() { return protocolMarshaller; } /** * @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string * to string). */ public XmlMarshallerRegistry marshallerRegistry() { return marshallerRegistry; } /** * @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params, * modify request URI, etc. */ public SdkHttpFullRequest.Builder request() { return request; } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. */ public void marshall(MarshallLocation marshallLocation, Object val) { marshallerRegistry.getMarshaller(marshallLocation, val).marshall(val, this, null, null); } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. * @param paramName Name of parameter to marshall. * @param sdkField {@link SdkField} containing metadata about the member being marshalled. */ public <T> void marshall(MarshallLocation marshallLocation, T val, String paramName, SdkField<T> sdkField) { marshallerRegistry.getMarshaller(marshallLocation, val).marshall(val, this, paramName, sdkField); } /** * @return Builder instance to construct a {@link XmlMarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlMarshallerContext}. */ public static final class Builder { private XmlGenerator xmlGenerator; private XmlProtocolMarshaller protocolMarshaller; private XmlMarshallerRegistry marshallerRegistry; private SdkHttpFullRequest.Builder request; private Builder() { } public Builder xmlGenerator(XmlGenerator xmlGenerator) { this.xmlGenerator = xmlGenerator; return this; } public Builder protocolMarshaller(XmlProtocolMarshaller protocolMarshaller) { this.protocolMarshaller = protocolMarshaller; return this; } public Builder marshallerRegistry(XmlMarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; return this; } public Builder request(SdkHttpFullRequest.Builder request) { this.request = request; return this; } public XmlMarshallerContext build() { return new XmlMarshallerContext(this); } } }
2,265
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlProtocolMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.InstantToString; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; import software.amazon.awssdk.protocols.core.ValueToStringConverter; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.utils.StringInputStream; /** * Implementation of {@link ProtocolMarshaller} for REST-XML services. This is currently only Cloudfront, Route53, * and S3. */ @SdkInternalApi public final class XmlProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { public static final ValueToStringConverter.ValueToString<Instant> INSTANT_VALUE_TO_STRING = InstantToString.create(getDefaultTimestampFormats()); private static final XmlMarshallerRegistry MARSHALLER_REGISTRY = createMarshallerRegistry(); private final URI endpoint; private final SdkHttpFullRequest.Builder request; private final String rootElement; private final XmlMarshallerContext marshallerContext; private XmlProtocolMarshaller(Builder builder) { this.endpoint = builder.endpoint; this.request = ProtocolUtils.createSdkHttpRequest(builder.operationInfo, this.endpoint); this.rootElement = builder.operationInfo.addtionalMetadata(AwsXmlProtocolFactory.ROOT_MARSHALL_LOCATION_ATTRIBUTE); this.marshallerContext = XmlMarshallerContext.builder() .xmlGenerator(builder.xmlGenerator) .marshallerRegistry(MARSHALLER_REGISTRY) .protocolMarshaller(this) .request(request) .build(); } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { if (rootElement != null) { marshallerContext.xmlGenerator().startElement(rootElement); } doMarshall(pojo); if (rootElement != null) { marshallerContext.xmlGenerator().endElement(); } return finishMarshalling(pojo); } void doMarshall(SdkPojo pojo) { for (SdkField<?> field : pojo.sdkFields()) { Object val = field.getValueOrDefault(pojo); if (isBinary(field, val)) { request.contentStreamProvider(((SdkBytes) val)::asInputStream); setContentTypeHeaderIfNeeded("binary/octet-stream"); } else if (isExplicitPayloadMember(field) && val instanceof String) { byte[] content = ((String) val).getBytes(StandardCharsets.UTF_8); request.contentStreamProvider(() -> new ByteArrayInputStream(content)); request.putHeader(CONTENT_LENGTH, Integer.toString(content.length)); } else { MARSHALLER_REGISTRY.getMarshaller(field.location(), field.marshallingType(), val) .marshall(val, marshallerContext, field.locationName(), (SdkField<Object>) field); } } } private SdkHttpFullRequest finishMarshalling(SdkPojo pojo) { // Content may already be set if the payload is binary data. if (hasPayloadMembers(pojo) && request.contentStreamProvider() == null && marshallerContext.xmlGenerator() != null) { String content = marshallerContext.xmlGenerator().stringWriter().getBuffer().toString(); if (!content.isEmpty()) { request.contentStreamProvider(() -> new StringInputStream(content)); request.putHeader("Content-Length", Integer.toString(content.getBytes(StandardCharsets.UTF_8).length)); setContentTypeHeaderIfNeeded("application/xml"); } } return request.build(); } private boolean isBinary(SdkField<?> field, Object val) { return isExplicitPayloadMember(field) && val instanceof SdkBytes; } private boolean isExplicitPayloadMember(SdkField<?> field) { return field.containsTrait(PayloadTrait.class); } private boolean hasPayloadMembers(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .anyMatch(f -> f.location() == MarshallLocation.PAYLOAD); } private void setContentTypeHeaderIfNeeded(String contentType) { if (contentType != null && !request.firstMatchingHeader(CONTENT_TYPE).isPresent()) { request.putHeader(CONTENT_TYPE, contentType); } } private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); formats.put(MarshallLocation.QUERY_PARAM, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } private static XmlMarshallerRegistry createMarshallerRegistry() { return XmlMarshallerRegistry .builder() .payloadMarshaller(MarshallingType.STRING, XmlPayloadMarshaller.STRING) .payloadMarshaller(MarshallingType.INTEGER, XmlPayloadMarshaller.INTEGER) .payloadMarshaller(MarshallingType.LONG, XmlPayloadMarshaller.LONG) .payloadMarshaller(MarshallingType.SHORT, XmlPayloadMarshaller.SHORT) .payloadMarshaller(MarshallingType.FLOAT, XmlPayloadMarshaller.FLOAT) .payloadMarshaller(MarshallingType.DOUBLE, XmlPayloadMarshaller.DOUBLE) .payloadMarshaller(MarshallingType.BIG_DECIMAL, XmlPayloadMarshaller.BIG_DECIMAL) .payloadMarshaller(MarshallingType.BOOLEAN, XmlPayloadMarshaller.BOOLEAN) .payloadMarshaller(MarshallingType.INSTANT, XmlPayloadMarshaller.INSTANT) .payloadMarshaller(MarshallingType.SDK_BYTES, XmlPayloadMarshaller.SDK_BYTES) .payloadMarshaller(MarshallingType.SDK_POJO, XmlPayloadMarshaller.SDK_POJO) .payloadMarshaller(MarshallingType.LIST, XmlPayloadMarshaller.LIST) .payloadMarshaller(MarshallingType.MAP, XmlPayloadMarshaller.MAP) .payloadMarshaller(MarshallingType.NULL, XmlPayloadMarshaller.NULL) .headerMarshaller(MarshallingType.STRING, HeaderMarshaller.STRING) .headerMarshaller(MarshallingType.INTEGER, HeaderMarshaller.INTEGER) .headerMarshaller(MarshallingType.LONG, HeaderMarshaller.LONG) .headerMarshaller(MarshallingType.SHORT, HeaderMarshaller.SHORT) .headerMarshaller(MarshallingType.DOUBLE, HeaderMarshaller.DOUBLE) .headerMarshaller(MarshallingType.FLOAT, HeaderMarshaller.FLOAT) .headerMarshaller(MarshallingType.BOOLEAN, HeaderMarshaller.BOOLEAN) .headerMarshaller(MarshallingType.INSTANT, HeaderMarshaller.INSTANT) .headerMarshaller(MarshallingType.MAP, HeaderMarshaller.MAP) .headerMarshaller(MarshallingType.LIST, HeaderMarshaller.LIST) .headerMarshaller(MarshallingType.NULL, HeaderMarshaller.NULL) .queryParamMarshaller(MarshallingType.STRING, QueryParamMarshaller.STRING) .queryParamMarshaller(MarshallingType.INTEGER, QueryParamMarshaller.INTEGER) .queryParamMarshaller(MarshallingType.LONG, QueryParamMarshaller.LONG) .queryParamMarshaller(MarshallingType.SHORT, QueryParamMarshaller.SHORT) .queryParamMarshaller(MarshallingType.DOUBLE, QueryParamMarshaller.DOUBLE) .queryParamMarshaller(MarshallingType.FLOAT, QueryParamMarshaller.FLOAT) .queryParamMarshaller(MarshallingType.BOOLEAN, QueryParamMarshaller.BOOLEAN) .queryParamMarshaller(MarshallingType.INSTANT, QueryParamMarshaller.INSTANT) .queryParamMarshaller(MarshallingType.LIST, QueryParamMarshaller.LIST) .queryParamMarshaller(MarshallingType.MAP, QueryParamMarshaller.MAP) .queryParamMarshaller(MarshallingType.NULL, QueryParamMarshaller.NULL) .pathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.STRING) .pathParamMarshaller(MarshallingType.INTEGER, SimpleTypePathMarshaller.INTEGER) .pathParamMarshaller(MarshallingType.LONG, SimpleTypePathMarshaller.LONG) .pathParamMarshaller(MarshallingType.SHORT, SimpleTypePathMarshaller.SHORT) .pathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .greedyPathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.GREEDY_STRING) .greedyPathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .build(); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link XmlProtocolMarshaller}. */ public static final class Builder { private URI endpoint; private XmlGenerator xmlGenerator; private OperationInfo operationInfo; private Builder() { } /** * @param endpoint Endpoint to set on the marshalled request. * @return This builder for method chaining. */ public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * @param xmlGenerator Object to write XML data. * @return This builder for method chaining. */ public Builder xmlGenerator(XmlGenerator xmlGenerator) { this.xmlGenerator = xmlGenerator; return this; } /** * @param operationInfo Metadata about the operation like URI, HTTP method, etc. * @return This builder for method chaining. */ public Builder operationInfo(OperationInfo operationInfo) { this.operationInfo = operationInfo; return this; } /** * @return New instance of {@link XmlProtocolMarshaller}. */ public XmlProtocolMarshaller build() { return new XmlProtocolMarshaller(this); } } }
2,266
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlWriter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import java.io.IOException; import java.io.Writer; import java.nio.ByteBuffer; import java.util.Date; import java.util.Map; import java.util.Stack; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.DateUtils; import software.amazon.awssdk.utils.StringUtils; /** * Utility for creating easily creating XML documents, one element at a time. */ @SdkInternalApi final class XmlWriter { /** Standard XML prolog to add to the beginning of each XML document. */ private static final String PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private static final String[] UNESCAPE_SEARCHES = { // Ampersands should always be the last to unescape "&quot;", "&apos;", "&lt;", "&gt;", "&#x0D;", "&#x0A;", "&amp;" }; private static final String[] UNESCAPE_REPLACEMENTS = { "\"", "'", "<", ">", "\r", "\n", "&" }; private static final String[] ESCAPE_SEARCHES = { // Ampersands should always be the first to escape "&", "\"", "'", "<", ">", "\r", "\n" }; private static final String[] ESCAPE_REPLACEMENTS = { "&amp;", "&quot;", "&apos;", "&lt;", "&gt;", "&#x0D;", "&#x0A;" }; /** The writer to which the XML document created by this writer will be written. */ private final Writer writer; /** Optional XML namespace attribute value to include in the root element. */ private final String xmlns; private Stack<String> elementStack = new Stack<>(); private boolean rootElement = true; private boolean writtenProlog = false; /** * Creates a new XMLWriter, ready to write an XML document to the specified * writer. The root element in the XML document will specify an xmlns * attribute with the specified namespace parameter. * * @param w * The writer this XMLWriter will write to. * @param xmlns * The XML namespace to include in the xmlns attribute of the * root element. */ XmlWriter(Writer w, String xmlns) { this.writer = w; this.xmlns = xmlns; } /** * Starts a new element with the specified name at the current position in * the in-progress XML document. * * @param element * The name of the new element. * * @return This XMLWriter so that additional method calls can be chained * together. */ XmlWriter startElement(String element) { // Only append the PROLOG if there is XML written. if (!writtenProlog) { writtenProlog = true; append(PROLOG); } append("<" + element); if (rootElement && xmlns != null) { append(" xmlns=\"" + xmlns + "\""); rootElement = false; } append(">"); elementStack.push(element); return this; } /** * Start to write an element with xml attributes. * * @param element the elment to write * @param attributes the xml attribtues * @return the XmlWriter */ XmlWriter startElement(String element, Map<String, String> attributes) { append("<" + element); for (Map.Entry<String, String> attribute: attributes.entrySet()) { append(" " + attribute.getKey() + "=\"" + attribute.getValue() + "\""); } append(">"); elementStack.push(element); return this; } /** * Closes the last opened element at the current position in the in-progress * XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ XmlWriter endElement() { String lastElement = elementStack.pop(); append("</" + lastElement + ">"); return this; } /** * Adds the specified value as text to the current position of the in * progress XML document. * * @param s * The text to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(String s) { append(escapeXmlEntities(s)); return this; } /** * Adds the specified value as Base64 encoded text to the current position of the in * progress XML document. * * @param b * The binary data to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(ByteBuffer b) { append(escapeXmlEntities(BinaryUtils.toBase64(BinaryUtils.copyBytesFrom(b)))); return this; } /** * Adds the specified date as text to the current position of the * in-progress XML document. * * @param date * The date to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(Date date) { append(escapeXmlEntities(DateUtils.formatIso8601Date(date.toInstant()))); return this; } /** * Adds the string representation of the specified object to the current * position of the in progress XML document. * * @param obj * The object to translate to a string and add to the XML * document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(Object obj) { append(escapeXmlEntities(obj.toString())); return this; } private void append(String s) { try { writer.append(s); } catch (IOException e) { throw SdkClientException.builder().message("Unable to write XML document").cause(e).build(); } } private String escapeXmlEntities(String s) { // Unescape any escaped characters. if (s.contains("&")) { s = StringUtils.replaceEach(s, UNESCAPE_SEARCHES, UNESCAPE_REPLACEMENTS); } return StringUtils.replaceEach(s, ESCAPE_SEARCHES, ESCAPE_REPLACEMENTS); } }
2,267
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/QueryParamMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class QueryParamMarshaller { public static final XmlMarshaller<String> STRING = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Double> DOUBLE = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<Float> FLOAT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Boolean> BOOLEAN = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new SimpleQueryParamMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> { if (list == null || list.isEmpty()) { return; } for (Object member : list) { context.marshall(MarshallLocation.QUERY_PARAM, member, paramName, null); } }; public static final XmlMarshaller<Map<String, ?>> MAP = (map, context, paramName, sdkField) -> { if (map == null || map.isEmpty()) { return; } MapTrait mapTrait = sdkField.getRequiredTrait(MapTrait.class); SdkField valueField = mapTrait.valueFieldInfo(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (valueField.containsTrait(ListTrait.class)) { ((List<?>) entry.getValue()).forEach(val -> { context.marshallerRegistry().getMarshaller(MarshallLocation.QUERY_PARAM, val) .marshall(val, context, entry.getKey(), null); }); } else { SimpleQueryParamMarshaller valueMarshaller = (SimpleQueryParamMarshaller) context.marshallerRegistry().getMarshaller(MarshallLocation.QUERY_PARAM, entry.getValue()); context.request().putRawQueryParameter(entry.getKey(), valueMarshaller.convert(entry.getValue(), null)); } } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private QueryParamMarshaller() { } private static class SimpleQueryParamMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleQueryParamMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().appendRawQueryParameter(paramName, converter.convert(val, sdkField)); } public String convert(T val, SdkField<T> sdkField) { return converter.convert(val, sdkField); } } }
2,268
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocols.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.Marshaller; /** * Interface to marshall data for xml protocol * * @param <T> Type to marshall. */ @FunctionalInterface @SdkInternalApi public interface XmlMarshaller<T> extends Marshaller<T> { XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { }; void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField); }
2,269
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/TestUtils.java
package software.amazon.awssdk.http.auth.aws; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.REGION_NAME; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.SERVICE_SIGNING_NAME; import static software.amazon.awssdk.http.auth.spi.signer.HttpSigner.SIGNING_CLOCK; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.function.Consumer; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.async.SimplePublisher; public final class TestUtils { private TestUtils() { } // Helpers for generating test requests public static <T extends AwsCredentialsIdentity> SignRequest<T> generateBasicRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super SignRequest.Builder<T>> signRequestOverrides ) { return SignRequest.builder(credentials) .request(SdkHttpRequest.builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build() .copy(requestOverrides)) .payload(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .putProperty(REGION_NAME, "us-east-1") .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(351153000968L))) .build() .copy(signRequestOverrides); } public static <T extends AwsCredentialsIdentity> AsyncSignRequest<T> generateBasicAsyncRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super AsyncSignRequest.Builder<T>> signRequestOverrides ) { SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); publisher.send(ByteBuffer.wrap("{\"TableName\": \"foo\"}".getBytes())); publisher.complete(); return AsyncSignRequest.builder(credentials) .request(SdkHttpRequest.builder() .protocol("https") .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build() .copy(requestOverrides)) .payload(publisher) .putProperty(REGION_NAME, "us-east-1") .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(351153000968L))) .build() .copy(signRequestOverrides); } public static class AnonymousCredentialsIdentity implements AwsCredentialsIdentity { @Override public String accessKeyId() { return null; } @Override public String secretAccessKey() { return null; } } public static class TickingClock extends Clock { private final Duration tick = Duration.ofSeconds(1); private Instant time; public TickingClock(Instant time) { this.time = time; } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { Instant time = this.time; this.time = time.plus(tick); return time; } } }
2,270
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/AwsV4aHttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws; import static org.junit.jupiter.api.Assertions.assertThrows; import org.assertj.core.api.AssertionsForClassTypes; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.utils.ClassLoaderHelper; public class AwsV4aHttpSignerTest { @Test public void create_WithoutHttpAuthAwsCrtModule_throws() { try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() -> ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.crt.HttpAuthAwsCrt", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, AwsV4aHttpSigner::create); AssertionsForClassTypes.assertThat(e).hasMessageContaining("http-auth-aws-crt"); } } }
2,271
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/RegionSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static software.amazon.awssdk.http.auth.aws.RegionSetTest.Case.tc; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; public class RegionSetTest { private static final List<Case<String>> stringCaseList = Arrays.asList( tc("*", "*", Arrays.asList("*")), tc("us-west-2", "us-west-2", Arrays.asList("us-west-2")), tc("us-east-1,us-west-2", "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(" us-west-2 ", "us-west-2", Arrays.asList("us-west-2")), tc(" us-east-1, us-west-2 ", "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(" a,b ,c ,d ,e ,f , g ", "a,b,c,d,e,f,g", Arrays.asList("a", "b", "c", "d", "e", "f", "g")) ); private static final List<String> stringFailList = Arrays.asList( null, "", " ", ", ,", ",,," ); private static final List<Case<Collection<String>>> collectionCaseList = Arrays.asList( tc(Arrays.asList("*"), "*", Arrays.asList("*")), tc(Arrays.asList("us-west-2"), "us-west-2", Arrays.asList("us-west-2")), tc(Arrays.asList("us-east-1", "us-west-2"), "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(Arrays.asList(" us-west-2 "), "us-west-2", Arrays.asList("us-west-2")), tc(Arrays.asList(" us-east-1", " us-west-2 "), "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(Arrays.asList(" a", "b ", "c ", "d ", "e ", "f ", " g "), "a,b,c,d,e,f,g", Arrays.asList("a", "b", "c", "d", "e", "f", "g") ) ); private static final List<Collection<String>> collectionFailList = Arrays.asList( null, Arrays.asList(), Arrays.asList(""), Arrays.asList(" "), Arrays.asList(" ", ""), Arrays.asList("", "", "") ); private static List<Case<String>> stringCases() { return stringCaseList; } private static List<String> stringFailures() { return stringFailList; } private static List<Case<Collection<String>>> collectionCases() { return collectionCaseList; } private static List<Collection<String>> collectionFailures() { return collectionFailList; } @ParameterizedTest @MethodSource("stringCases") public void create_withStringInput_succeeds(Case<String> stringCase) { RegionSet regionSet = RegionSet.create(stringCase.input); assertEquals(stringCase.asString, regionSet.asString()); assertIterableEquals(stringCase.asSet, regionSet.asSet()); } @ParameterizedTest @MethodSource("stringFailures") public void create_withInvalidStringInput_throws(String input) { Exception ex = assertThrows(Exception.class, () -> RegionSet.create(input)); if (ex instanceof NullPointerException) { assertThat(ex.getMessage()).contains("must not be"); } else if (ex instanceof IllegalArgumentException) { assertThat(ex.getMessage()).contains("must not be"); } else { fail(); } } @ParameterizedTest @MethodSource("collectionCases") public void create_withCollectionInput_succeeds(Case<Collection<String>> collectionCase) { RegionSet regionSet = RegionSet.create(collectionCase.input); assertEquals(collectionCase.asString, regionSet.asString()); assertIterableEquals(collectionCase.asSet, regionSet.asSet()); } @ParameterizedTest @MethodSource("collectionFailures") public void create_withInvalidCollectionInput_throws(Collection<String> input) { Exception ex = assertThrows(Exception.class, () -> RegionSet.create(input)); if (ex instanceof NullPointerException) { assertThat(ex.getMessage()).contains("must not be"); } else if (ex instanceof IllegalArgumentException) { assertThat(ex.getMessage()).contains("must not be"); } else { fail(); } } static final class Case<T> { final T input; final String asString; final Collection<String> asSet; private Case(T input, String asString, Collection<String> asSet) { this.input = input; this.asString = asString; this.asSet = asSet; } static <T> Case<T> tc(T input, String asString, Collection<String> asSet) { return new Case<>(input, asString, asSet); } @Override public String toString() { return String.format("%s => %s :: %s", input, asString, asSet); } } }
2,272
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/SigV4DataFramePublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.eventstream.internal.io; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Function; import io.reactivex.subscribers.TestSubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; public class SigV4DataFramePublisherTest { private static final List<Instant> SIGNING_INSTANTS = Stream.of( // Note: This first Instant is used for signing the request not an event OffsetDateTime.of(1981, 1, 16, 6, 30, 0, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 1, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 2, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 3, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 4, 0, ZoneOffset.UTC).toInstant() ).collect(Collectors.toList()); /** * @return A clock that returns the values from {@link #SIGNING_INSTANTS} in order. * @throws IllegalStateException When there are no more instants to return. */ private static Clock signingClock() { return new Clock() { private final AtomicInteger timeIndex = new AtomicInteger(0); @Override public Instant instant() { int idx = timeIndex.getAndIncrement(); // Note: we use an atomic because Clock must be threadsafe, // though probably not necessary for our tests if (idx >= SIGNING_INSTANTS.size()) { throw new IllegalStateException("Clock ran out of Instants to return! " + idx); } return SIGNING_INSTANTS.get(idx); } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } }; } /** * Test that the sigv4 publisher adapts an existing publisher with sigv4 chunk-signing */ @Test public void sigV4DataFramePublisher_shouldAdaptAndSignPublisher() { TestVector testVector = generateTestVector(); Clock signingClock = signingClock(); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(testVector.payload()) .credentials(credentials) .credentialScope(credentialScope) .signature(testVector.signature()) .signingClock(signingClock) .build(); TestSubscriber testSubscriber = TestSubscriber.create(); Flowable.fromPublisher(sigV4Publisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { final Queue<Message> messages = new LinkedList<>(); final MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(testSubscriber); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueSequence(testVector.expectedPublisher().blockingIterable()); } /** * Test that without demand from subscriber, trailing empty frame is not delivered */ @Test public void testBackPressure() { TestVector testVector = generateTestVector(); Clock signingClock = signingClock(); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(testVector.payload()) .credentials(credentials) .credentialScope(credentialScope) .signature(testVector.signature()) .signingClock(signingClock) .build(); Subscriber<Object> subscriber = Mockito.spy(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) { // Only request the size of request body (which should NOT include the empty frame) s.request(testVector.content().size()); } @Override public void onNext(Object o) { } @Override public void onError(Throwable t) { fail("onError should never been called"); } @Override public void onComplete() { fail("onComplete should never been called"); } }); Flowable.fromPublisher(sigV4Publisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { final Queue<Message> messages = new LinkedList<>(); final MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(subscriber); // The number of events equal to the size of request body (excluding trailing empty frame) verify(subscriber, times(testVector.content().size())).onNext(any()); // subscriber is not terminated (no onError/onComplete) since trailing empty frame is not delivered yet verify(subscriber, never()).onError(any()); verify(subscriber, never()).onComplete(); } private TestVector generateTestVector() { return new TestVector() { final List<String> content = Lists.newArrayList("A", "B", "C"); @Override public List<String> content() { return content; } @Override public String signature() { return "e1d8e8c8815e60969f2a34765c9a15945ffc0badbaa4b7e3b163ea19131e949b"; } @Override public Publisher<ByteBuffer> payload() { List<ByteBuffer> bodyBytes = content.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); return Flowable.fromIterable(bodyBytes); } @Override public Flowable<Message> expectedPublisher() { Flowable<String> sigsHex = Flowable.just( "7aabf85b765e6a4d0d500b6e968657b14726fa3e1eb7e839302728ffd77629a5", "f72aa9642f571d24a6e1ae42f10f073ad9448d8a028b6bcd82da081335adda02", "632af120435b57ec241d8bfbb12e496dfd5e2730a1a02ac0ab6eaa230ae02e9a", "c6f679ddb3af68f5e82f0cf6761244cb2338cf11e7d01a24130aea1b7c17e53e"); // The Last data frame is empty Flowable<String> payloads = Flowable.fromIterable(content).concatWith(Flowable.just("")); return sigsHex.zipWith(payloads, new BiFunction<String, String, Message>() { // The first Instant was used to sign the request private int idx = 1; @Override public Message apply(String sig, String payload) { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":date", HeaderValue.fromTimestamp(SIGNING_INSTANTS.get(idx))); headers.put(":chunk-signature", HeaderValue.fromByteArray(BinaryUtils.fromHex(sig))); idx += 1; return new Message(headers, payload.getBytes(StandardCharsets.UTF_8)); } } ); } }; } private interface TestVector { String signature(); List<String> content(); Publisher<ByteBuffer> payload(); Flowable<Message> expectedPublisher(); } }
2,273
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/SigV4DataFramePublisherTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.eventstream.internal.io; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.async.SimplePublisher; public class SigV4DataFramePublisherTckTest extends PublisherVerification<ByteBuffer> { public SigV4DataFramePublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long elements) { Clock signingClock = new TickingClock(Instant.EPOCH); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); SimplePublisher<ByteBuffer> payload = new SimplePublisher<>(); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(payload) .credentials(credentials) .credentialScope(credentialScope) .signature("signature") .signingClock(signingClock) .build(); // since this publisher specifically appends an empty element to the end, we need to subtract 1 // from the number of elements to expected to be "produced" before end-of-stream long expectedElements = elements - 1; for (int i = 0; i < expectedElements; i++) { payload.send(ByteBuffer.wrap(Integer.toString(i).getBytes(StandardCharsets.UTF_8))); } payload.complete(); return sigV4Publisher; } @Override public Publisher<ByteBuffer> createFailedPublisher() { Clock signingClock = new TickingClock(Instant.EPOCH); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); SimplePublisher<ByteBuffer> payload = new SimplePublisher<>(); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(payload) .credentials(credentials) .credentialScope(credentialScope) .signature("signature") .signingClock(signingClock) .build(); payload.error(new RuntimeException("boom!")); return sigV4Publisher; } @Override public long maxElementsFromPublisher() { return 256L; } }
2,274
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultRequestSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static java.time.ZoneOffset.UTC; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.utils.BinaryUtils.toHex; import java.net.URI; import java.time.Clock; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; public class DefaultRequestSignerTest { V4Properties v4Properties = V4Properties.builder() .credentials(AwsCredentialsIdentity.create("foo", "bar")) .credentialScope(new CredentialScope("baz", "qux", Instant.EPOCH)) .signingClock(Clock.fixed(Instant.EPOCH, UTC)) .doubleUrlEncode(true) .normalizePath(true) .build(); DefaultV4RequestSigner requestSigner = new DefaultV4RequestSigner(v4Properties, "quux"); @Test public void requestSigner_sign_shouldReturnSignedResult_butNotAddAnyAuthInfoToRequest() { SdkHttpRequest.Builder request = SdkHttpRequest .builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .putHeader("Host", "localhost"); String expectedContentHash = "quux"; String expectedSigningKeyHex = "3d558b7a87b67996abc908071e0771a31b2a7977ab247144e60a6cba3356be1f"; String expectedSignature = "6c1f4222e0888e6e68b20ded382bc80c7312465c69fb52cbd6d6ce2d073533bf"; String expectedCanonicalRequestString = "GET\n/\n\n" + "host:localhost\n\n" + "host\nquux"; String expectedHost = "localhost"; V4RequestSigningResult requestSigningResult = requestSigner.sign(request); assertEquals(expectedContentHash, requestSigningResult.getContentHash()); assertEquals(expectedSigningKeyHex, toHex(requestSigningResult.getSigningKey())); assertEquals(expectedSignature, requestSigningResult.getSignature()); assertEquals(expectedCanonicalRequestString, requestSigningResult.getCanonicalRequest().getCanonicalRequestString()); assertEquals(expectedHost, requestSigningResult.getSignedRequest().firstMatchingHeader("Host").orElse("")); assertThat(requestSigningResult.getSignedRequest().build()).usingRecursiveComparison().isEqualTo(request.build()); } }
2,275
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultAwsV4HttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.http.auth.aws.TestUtils.generateBasicAsyncRequest; import static software.amazon.awssdk.http.auth.aws.TestUtils.generateBasicRequest; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.CONTENT_ENCODING; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.AUTH_LOCATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.CHECKSUM_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.CHUNK_ENCODING_ENABLED; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.EXPIRATION_DURATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.MockedStatic; import org.mockito.Mockito; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.auth.aws.TestUtils; import software.amazon.awssdk.http.auth.aws.eventstream.internal.io.SigV4DataFramePublisher; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.AuthLocation; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.ClassLoaderHelper; /** * Test the delegation of signing to the correct implementations. */ public class DefaultAwsV4HttpSignerTest { DefaultAwsV4HttpSigner signer = new DefaultAwsV4HttpSigner(); @Test public void sign_WithNoAdditonalProperties_DelegatesToHeaderSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void signAsync_WithNoAdditonalProperties_DelegatesToHeaderSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_WithQueryAuthLocation_DelegatesToQuerySigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @Test public void signAsync_WithQueryAuthLocation_DelegatesToQuerySigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @ParameterizedTest @ValueSource(longs = {-1, 0, 604801}) public void sign_WithQueryAuthLocationAndInvalidExpiration_Throws(long seconds) { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(seconds)) ); assertThrows(IllegalArgumentException.class, () -> signer.sign(request)); } @ParameterizedTest @ValueSource(longs = {-1, 0, 604801}) public void signAsync_WithQueryAuthLocationAndInvalidExpiration_Throws(long seconds) { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(seconds)) ); assertThrows(IllegalArgumentException.class, () -> signer.signAsync(request)); } @Test public void sign_WithQueryAuthLocationAndExpiration_DelegatesToPresignedSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).isPresent(); } @Test public void signAsync_WithQueryAuthLocationAndExpiration_DelegatesToPresignedSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).isPresent(); } @Test public void sign_WithHeaderAuthLocationAndExpirationDuration_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.HEADER) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithHeaderAuthLocationAndExpirationDuration_Throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.HEADER) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(request).join()); } @Test public void sign_withAnonymousCreds_shouldNotSign() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( new TestUtils.AnonymousCredentialsIdentity(), httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")) .isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isNotPresent(); } @Test public void signAsync_withAnonymousCreds_shouldNotSign() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( new TestUtils.AnonymousCredentialsIdentity(), httpRequest -> { }, signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")) .isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalse_DelegatesToUnsignedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void signAsync_WithPayloadSigningFalse_DelegatesToUnsignedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithEventStreamContentTypeWithoutHttpAuthAwsEventStreamModule_throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() ->ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.eventstream.HttpAuthAwsEventStream", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, () -> signer.sign(request)); assertThat(e).hasMessageContaining("http-auth-aws-eventstream"); } } @Test public void signAsync_WithEventStreamContentTypeWithoutHttpAuthAwsEventStreamModule_throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() ->ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.eventstream.HttpAuthAwsEventStream", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, () -> signer.signAsync(request).join()); assertThat(e).hasMessageContaining("http-auth-aws-eventstream"); } } @Test public void sign_WithEventStreamContentType_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithEventStreamContentType_DelegatesToEventStreamPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.payload().get()).isInstanceOf(SigV4DataFramePublisher.class); } @Test public void sign_WithEventStreamContentTypeAndUnsignedPayload_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithEventStreamContentTypeAndUnsignedPayload_Throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(request)); } @Test public void sign_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksum_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrue_DelegatesToUnsignedPayload() { // Currently, there is no use-case for unsigned chunk-encoding without trailers, so we should assert it falls back to // unsigned-payload (not chunk-encoded) SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueWithoutTrailer_DelegatesToUnsignedPayload() { // Currently, there is no use-case for unsigned chunk-encoding without trailers, so we should assert it falls back to // unsigned-payload (not chunk-encoded) AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueWithChecksumHeader_DelegatesToUnsignedPayload() { // If a checksum is given explicitly, we shouldn't treat it as a flexible-checksum-enabled request SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20") .putHeader("x-amz-checksum-crc32", "bogus"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("bogus"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueWithChecksumHeader_DelegatesToUnsignedPayload() { // If a checksum is given explicitly, we shouldn't treat it as a flexible-checksum-enabled request AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20") .putHeader("x-amz-checksum-crc32", "bogus"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("bogus"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_withChecksumAlgorithm_DelegatesToChecksummerWithThatChecksumAlgorithm() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isPresent(); } @Test public void signAsync_withChecksumAlgorithm_DelegatesToChecksummerWithThatChecksumAlgorithm() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isPresent(); } @Test public void sign_withChecksumAlgorithmAndPayloadSigningFalse_DelegatesToChecksummerWithThatChecksumAlgorithm() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(CHECKSUM_ALGORITHM, CRC32) .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void signAsync_withChecksumAlgorithmAndPayloadSigningFalse_DelegatesToChecksummerWithThatChecksumAlgorithm() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(CHECKSUM_ALGORITHM, CRC32) .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndHttp_FallsBackToPayloadSigning() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2"); } @Test public void signAsync_WithPayloadSigningFalseAndHttp_FallsBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2"); } @Test public void sign_WithPayloadSigningTrueAndChunkEncodingTrueAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, true) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningTrueAndChunkEncodingTrueAndHttp_IgnoresPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, true) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndHttp_DoesNotFallBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksumAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksumAndHttp_DoesNotFallBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); } }
2,276
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/RollingSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; public class RollingSignerTest { @Test public void sign_shouldRollSignature() { RollingSigner signer = new RollingSigner("key".getBytes(StandardCharsets.UTF_8), "seed"); String first = signer.sign(signature -> signature + "a"); String second = signer.sign(signature -> signature + "b"); String third = signer.sign(signature -> signature + "c"); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", first); assertEquals("08f47cc56d186cee34fa7662128d5c9187eb9483938df45282e922d902e85a27", second); assertEquals("10da3ca4a393be5f8368823cb73a777426db24428bd8374fbf54a64a808ff00a", third); } @Test public void reset_shouldResetSeed() { RollingSigner signer = new RollingSigner("key".getBytes(StandardCharsets.UTF_8), "seed"); String first = signer.sign(signature -> signature + "a"); String second = signer.sign(signature -> signature + "b"); signer.reset(); String firstAgain = signer.sign(signature -> signature + "a"); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", first); assertEquals("08f47cc56d186cee34fa7662128d5c9187eb9483938df45282e922d902e85a27", second); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", firstAgain); } }
2,277
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4CanonicalRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.ToString; /** * Tests how canonical resource paths are created including normalization */ public class V4CanonicalRequestTest { public static Iterable<TestCase> data() { return Arrays.asList( // Handling slash tc("Empty path -> (initial) slash added", "", "/"), tc("Slash -> unchanged", "/", "/"), tc("Single segment with initial slash -> unchanged", "/foo", "/foo"), tc("Single segment no slash -> slash prepended", "foo", "/foo"), tc("Multiple segments -> unchanged", "/foo/bar", "/foo/bar"), tc("Multiple segments with trailing slash -> unchanged", "/foo/bar/", "/foo/bar/"), // Double URL encoding tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2Fbar", "/foo%252Fbar", true, true), // No double-url-encoding + normalization tc("Single segment, dot -> should remove dot", "/.", "/"), tc("Single segment, double dot -> unchanged", "/..", "/.."), tc("Multiple segments with dot -> should remove dot", "/foo/./bar", "/foo/bar"), tc("Multiple segments with ending dot -> should remove dot and trailing slash", "/foo/bar/.", "/foo/bar"), tc("Multiple segments with dots -> should remove dots and preceding segment", "/foo/bar/../baz", "/foo/baz"), tc("First segment has colon -> unchanged, url encoded first", "foo:/bar", "/foo%3A/bar", true, true), // Double-url-encoding + normalization tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2F.%2Fbar", "/foo%252F.%252Fbar", true, true), // Double-url-encoding + no normalization tc("No url encode, Multiple segments with dot -> unchanged", "/foo/./bar", "/foo/./bar", false, false), tc("Multiple segments with dots -> unchanged", "/foo/bar/../baz", "/foo/bar/../baz", false, false) ); } private static TestCase tc(String name, String path, String expectedPath) { return new TestCase(name, path, expectedPath, false, true); } private static TestCase tc(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { return new TestCase(name, path, expectedPath, urlEncode, normalizePath); } @ParameterizedTest @MethodSource("data") public void verifyNormalizedPath(TestCase tc) { String canonicalRequest = tc.canonicalRequest.getCanonicalRequestString(); String[] requestParts = canonicalRequest.split("\\n"); String canonicalPath = requestParts[1]; assertEquals(tc.expectedPath, canonicalPath); } @Test public void canonicalRequest_WithForbiddenHeaders_shouldExcludeForbidden() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putHeader("foo", "bar") .putHeader("x-amzn-trace-id", "wontBePresent") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithMultiValueHeaders_shouldCommaSeparateValues() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .appendHeader("foo", "bar") .appendHeader("foo", "baz") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar,baz\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_withSpacedHeaders_shouldStripWhitespace() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putHeader("foo", " bar baz ") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar baz\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithNullParamValue_shouldIncludeEquals() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putRawQueryParameter("foo", (String) null) .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\nfoo=\n\n\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithEmptyParamKey_shouldExcludeParam() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putRawQueryParameter("", "") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\n\n\nsha-256", cr.getCanonicalRequestString()); } private static class TestCase { private final String name; private final String path; private final String expectedPath; private final V4CanonicalRequest canonicalRequest; private TestCase(String name, String path, String expectedPath, boolean doubleUrlEncode, boolean normalizePath) { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .encodedPath(path) .method(SdkHttpMethod.PUT) .build(); this.name = name; this.path = path; this.expectedPath = expectedPath; this.canonicalRequest = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(doubleUrlEncode, normalizePath)); } @Override public String toString() { return ToString.builder("TestCase") .add("name", name) .add("path", path) .add("expectedPath", expectedPath) .build(); } } }
2,278
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/AwsChunkedV4PayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; /** * Test the delegation of signing to the correct implementations. */ public class AwsChunkedV4PayloadSignerTest { int chunkSize = 4; CredentialScope credentialScope = new CredentialScope("us-east-1", "s3", Instant.EPOCH); byte[] data = "{\"TableName\": \"foo\"}".getBytes(); ContentStreamProvider payload = () -> new ByteArrayInputStream(data); SdkHttpRequest.Builder requestBuilder; @BeforeEach public void setUp() { requestBuilder = SdkHttpRequest .builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .putHeader(Header.CONTENT_LENGTH, Integer.toString(data.length)) .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void sign_withSignedPayload_shouldChunkEncodeWithSigV4Ext() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, null); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withSignedPayloadAndChecksum_shouldChunkEncodeWithSigV4ExtAndSigV4Trailer() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n" + "x-amz-trailer-signature:23457d04f4a8e279780cb91e28d4fbd1c6a2dd678d419705461a80514cea206c\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withChecksum_shouldChunkEncodeWithChecksumTrailer() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "x-amz-checksum-sha256:oVyCkrHRKru75BSGBfeHL732RWGP7lqw6AcqezTxVeI=\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(SHA256) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-sha256"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailers_shouldChunkEncodeWithExistingTrailers() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "PreExistingHeader1:someValue1,someValue2\r\n" + "PreExistingHeader2:someValue3\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("PreExistingHeader1", "someValue2") .appendHeader("PreExistingHeader2", "someValue3") .appendHeader("x-amz-trailer", "PreExistingHeader1") .appendHeader("x-amz-trailer", "PreExistingHeader2"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader2")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("PreExistingHeader1", "PreExistingHeader2"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailersAndChecksum_shouldChunkEncodeWithTrailers() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "PreExistingHeader1:someValue1,someValue2\r\n" + "PreExistingHeader2:someValue3\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("PreExistingHeader1", "someValue2") .appendHeader("PreExistingHeader2", "someValue3") .appendHeader("x-amz-trailer", "PreExistingHeader1") .appendHeader("x-amz-trailer", "PreExistingHeader2"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader2")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains( "PreExistingHeader1", "PreExistingHeader2", "x-amz-checksum-crc32" ); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailersAndChecksumAndSignedPayload_shouldAwsChunkEncode() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n" + "zzz:123\r\n" + "PreExistingHeader1:someValue1\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n" + "x-amz-trailer-signature:3f65ab57ede6a5fb7c77b14b35faf2d9dd2c6d89828bdae189a04f3677bc16f2\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("zzz", "123") .appendHeader("x-amz-trailer", "zzz") .appendHeader("x-amz-trailer", "PreExistingHeader1"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("zzz", "PreExistingHeader1", "x-amz-checksum-crc32"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withoutContentLength_calculatesContentLengthFromPayload() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "x-amz-checksum-sha256:oVyCkrHRKru75BSGBfeHL732RWGP7lqw6AcqezTxVeI=\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER"); requestBuilder.removeHeader(Header.CONTENT_LENGTH); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(SHA256) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-sha256"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_shouldReturnResettableContentStreamProvider() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); // successive calls to newStream() should return a stream with the same data every time - this makes sure that state // isn't carried over to the new streams returned by newStream() byte[] tmp = new byte[1024]; for (int i = 0; i < 2; i++) { int actualBytes = readAll(signedPayload.newStream(), tmp); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } } @Test public void signAsync_throws() { AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(null, null)); } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } }
2,279
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4RequestSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.header; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.presigned; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.query; import java.net.URI; import java.time.Clock; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity; public class V4RequestSignerTest { private static final AwsCredentialsIdentity creds = AwsCredentialsIdentity.create("access", "secret"); private static final AwsSessionCredentialsIdentity sessionCreds = AwsSessionCredentialsIdentity.create("access", "secret", "token"); @Test public void sign_computesSigningResult() { String expectedSignature = "4c7049543386ba32bc85e7a7d7b892e7da1c412abf3508ca84775ed099790acf"; String expectedContentHash = "abc123"; String expectedCanonicalRequestString = "GET\n" + "/./foo\n\n" + "x-amz-archive-description:test test\n" + "x-amz-content-sha256:checksum\n\n" + "x-amz-archive-description;x-amz-content-sha256\n" + "abc123"; V4RequestSigningResult result = V4RequestSigner.create(getProperties(creds), "abc123").sign(getRequest()); assertEquals(expectedSignature, result.getSignature()); assertEquals(expectedContentHash, result.getContentHash()); assertEquals(expectedCanonicalRequestString, result.getCanonicalRequest().getCanonicalRequestString()); } @Test public void sign_withHeader_addsAuthHeaders() { String expectedAuthorization = "AWS4-HMAC-SHA256 Credential=access/19700101/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date, " + "Signature=0fafd04465eb6201e868a80f72d15d50731512298f554684ce6627c0619f429a"; V4RequestSigningResult result = header(getProperties(creds)).sign(getRequest()); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Date")).hasValue("19700101T000000Z"); assertThat(result.getSignedRequest().firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void sign_withHeaderAndSessionCredentials_addsAuthHeadersAndTokenHeader() { String expectedAuthorization = "AWS4-HMAC-SHA256 Credential=access/19700101/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;" + "x-amz-security-token, " + "Signature=cda79272f6d258c2cb2f04ac84a5f9515440e0158bf39e212c3dcf88b3a477a9"; V4RequestSigningResult result = header(getProperties(sessionCreds)).sign(getRequest()); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Date")).hasValue("19700101T000000Z"); assertThat(result.getSignedRequest().firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Security-Token")).hasValue("token"); } @Test public void sign_withQuery_addsAuthQueryParams() { V4RequestSigningResult result = query(getProperties(creds)).sign(getRequest()); assertEquals("AWS4-HMAC-SHA256", result.getSignedRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)); assertEquals("19700101T000000Z", result.getSignedRequest().rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals("host;x-amz-archive-description;x-amz-content-sha256", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals("access/19700101/us-east-1/demo/aws4_request", result.getSignedRequest().rawQueryParameters().get( "X-Amz-Credential").get(0)); assertEquals("bb3ddb98bc32b85c8aa484bfaf321171a22ad802baa03ee9d5fcda9842b769c9", result.getSignedRequest().rawQueryParameters().get("X-Amz-Signature").get(0)); } @Test public void sign_withQueryAndSessionCredentials_addsAuthQueryParamsAndTokenParam() { V4RequestSigningResult result = query(getProperties(sessionCreds)).sign(getRequest()); assertEquals("AWS4-HMAC-SHA256", result.getSignedRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)); assertEquals("19700101T000000Z", result.getSignedRequest().rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals("host;x-amz-archive-description;x-amz-content-sha256", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals( "access/19700101/us-east-1/demo/aws4_request", result.getSignedRequest().rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals("2ffe9562fefd57e14f43bf1937b6b85cc0f0180d63789254bddec25498e14a29", result.getSignedRequest().rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals("token", result.getSignedRequest().rawQueryParameters().get("X-Amz-Security-Token").get(0)); } @Test public void sign_withPresigned_addsExpirationParam() { V4RequestSigningResult result = presigned(getProperties(creds), Duration.ZERO).sign(getRequest()); assertEquals("0", result.getSignedRequest().rawQueryParameters().get("X-Amz-Expires").get(0)); assertEquals("host;x-amz-archive-description", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals("691f39caa2064fe4fb897976dfb4b09df54749c825a5fcd1e2f0b3fcd1bcc600", result.getSignature()); } @Test public void sign_withHeader_withNoContentHashHeader_throws() { SdkHttpRequest.Builder request = getRequest().removeHeader("x-amz-content-sha256"); assertThrows(IllegalArgumentException.class, () -> header(getProperties(sessionCreds)).sign(request) ); } @Test public void sign_withQuery_withNoContentHashHeader_throws() { SdkHttpRequest.Builder request = getRequest().removeHeader("x-amz-content-sha256"); assertThrows(IllegalArgumentException.class, () -> query(getProperties(sessionCreds)).sign(request) ); } private V4Properties getProperties(AwsCredentialsIdentity creds) { Clock clock = new TickingClock(Instant.EPOCH); return V4Properties.builder() .credentials(creds) .credentialScope(new CredentialScope("us-east-1", "demo", clock.instant())) .signingClock(clock) .doubleUrlEncode(false) .normalizePath(false) .build(); } private SdkHttpRequest.Builder getRequest() { URI target = URI.create("https://test.com/./foo"); return SdkHttpRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .putHeader("x-amz-content-sha256", "checksum") .putHeader("x-amz-archive-description", "test test"); } }
2,280
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/FlexibleChecksummerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.FlexibleChecksummer.option; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; public class FlexibleChecksummerTest { ContentStreamProvider payload = () -> new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)); Publisher<ByteBuffer> payloadAsync = Flowable.just(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); SdkHttpRequest.Builder request = SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET); @Test public void checksummer_withNoChecksums_shouldNotAddAnyChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer(); SdkHttpRequest expectedRequest = request.build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withNoChecksums_shouldNotAddAnyChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer(); SdkHttpRequest expectedRequest = request.build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummer_withOneChecksum_shouldAddOneChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toHex).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withOneChecksum_shouldAddOneChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toBase64).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummer_withTwoChecksums_shouldAddTwoChecksums() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toHex).build(), option().headerName("crc32").algorithm(CRC32).formatter(BinaryUtils::toBase64).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae") .putHeader("crc32", "jHNlIQ==") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withTwoChecksums_shouldAddTwoChecksums() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toBase64).build(), option().headerName("crc32").algorithm(CRC32).formatter(BinaryUtils::toHex).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=") .putHeader("crc32", "8c736521") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } }
2,281
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/PrecomputedSha256ChecksummerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; public class PrecomputedSha256ChecksummerTest { ContentStreamProvider payload = () -> new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)); Publisher<ByteBuffer> payloadAsync = Flowable.just(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); SdkHttpRequest.Builder request = SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET); @Test public void checksummer_shouldAddComputedValue() { PrecomputedSha256Checksummer checksummer = new PrecomputedSha256Checksummer(() -> "something"); SdkHttpRequest expectedRequest = request .putHeader("x-amz-content-sha256", "something") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.toString(), request.build().toString()); } @Test public void checksummerAsync_shouldAddComputedValue() { PrecomputedSha256Checksummer checksummer = new PrecomputedSha256Checksummer(() -> "something"); SdkHttpRequest expectedRequest = request .putHeader("x-amz-content-sha256", "something") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.toString(), request.build().toString()); } }
2,282
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/SignerKeyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.util; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import org.junit.jupiter.api.Test; public class SignerKeyTest { @Test public void isValidForDate_dayBefore_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z"); assertThat(key.isValidForDate(dayBefore)).isFalse(); } @Test public void isValidForDate_sameDay_true() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant sameDay = Instant.parse("2020-03-03T01:02:03Z"); assertThat(key.isValidForDate(sameDay)).isTrue(); } @Test public void isValidForDate_dayAfter_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z"); assertThat(key.isValidForDate(dayAfter)).isFalse(); } }
2,283
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/FifoCacheTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class FifoCacheTest { @Test public void test() { FifoCache<String> cache = new FifoCache<>(3); assertEquals(0, cache.size()); cache.add("k1", "v1"); assertEquals(1, cache.size()); cache.add("k1", "v11"); assertEquals(1, cache.size()); cache.add("k2", "v2"); assertEquals(2, cache.size()); cache.add("k3", "v3"); assertEquals(3, cache.size()); assertEquals("v11", cache.get("k1")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); cache.add("k4", "v4"); assertEquals(3, cache.size()); assertNull(cache.get("k1")); } @Test public void testZeroSize() { assertThrows(IllegalArgumentException.class, () -> new FifoCache<>(0)); } @Test public void testIllegalArgument() { assertThrows(IllegalArgumentException.class, () -> new FifoCache<>(0)); } @Test public void testSingleEntry() { FifoCache<String> cache = new FifoCache<String>(1); assertEquals(0, cache.size()); cache.add("k1", "v1"); assertEquals(1, cache.size()); cache.add("k1", "v11"); assertEquals(1, cache.size()); assertEquals("v11", cache.get("k1")); cache.add("k2", "v2"); assertEquals(1, cache.size()); assertEquals("v2", cache.get("k2")); assertNull(cache.get("k1")); cache.add("k3", "v3"); assertEquals(1, cache.size()); assertEquals("v3", cache.get("k3")); assertNull(cache.get("k2")); } }
2,284
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/ChecksumUtilTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32C; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.MD5; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA1; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.fromChecksumAlgorithm; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import java.io.ByteArrayInputStream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32CChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Md5Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha1Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; public class ChecksumUtilTest { @Test public void checksumHeaderName_shouldFormatName() { assertEquals("x-amz-checksum-sha256", checksumHeaderName(SHA256)); assertEquals("x-amz-checksum-sha1", checksumHeaderName(SHA1)); assertEquals("x-amz-checksum-crc32", checksumHeaderName(CRC32)); assertEquals("x-amz-checksum-crc32c", checksumHeaderName(CRC32C)); assertEquals("x-amz-checksum-md5", checksumHeaderName(MD5)); } @Test public void fromChecksumAlgorithm_mapsToCorrectSdkChecksum() { assertEquals(Sha256Checksum.class, fromChecksumAlgorithm(SHA256).getClass()); assertEquals(Sha1Checksum.class, fromChecksumAlgorithm(SHA1).getClass()); assertEquals(Crc32Checksum.class, fromChecksumAlgorithm(CRC32).getClass()); assertEquals(Crc32CChecksum.class, fromChecksumAlgorithm(CRC32C).getClass()); assertEquals(Md5Checksum.class, fromChecksumAlgorithm(MD5).getClass()); } @Test public void readAll_consumesEntireStream() { int bytes = 4096 * 4 + 1; byte[] buf = new byte[bytes]; ByteArrayInputStream inputStream = new ByteArrayInputStream(buf); readAll(inputStream); assertEquals(0, inputStream.available()); } }
2,285
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.io; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; import software.amazon.awssdk.utils.BinaryUtils; public class ChecksumInputStreamTest { @Test public void read_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; ByteArrayInputStream backingStream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); SdkChecksum checksum = new Sha256Checksum(); ChecksumInputStream inputStream = new ChecksumInputStream(backingStream, Collections.singleton(checksum)); readAll(inputStream); String computedDigest = BinaryUtils.toHex(checksum.getChecksumBytes()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void read_withMultipleChecksums_shouldComputeCorrectChecksums() { String testString = "AWS SDK for Java"; String expectedSha256Digest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; String expectedCrc32Digest = "4ac37ece"; ByteArrayInputStream backingStream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); SdkChecksum sha256Checksum = new Sha256Checksum(); SdkChecksum crc32Checksum = new Crc32Checksum(); ChecksumInputStream inputStream = new ChecksumInputStream(backingStream, Arrays.asList(sha256Checksum, crc32Checksum)); readAll(inputStream); String computedSha256Digest = BinaryUtils.toHex(sha256Checksum.getChecksumBytes()); String computedCrc32Digest = BinaryUtils.toHex(crc32Checksum.getChecksumBytes()); assertThat(computedSha256Digest).isEqualTo(expectedSha256Digest); assertThat(computedCrc32Digest).isEqualTo(expectedCrc32Digest); } }
2,286
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChunkInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.io; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.ChunkInputStream; public class ChunkInputStreamTest { @Test public void close_shouldDrainChunk() throws IOException { ByteArrayInputStream backingStream = new ByteArrayInputStream(new byte[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}); ChunkInputStream in = new ChunkInputStream(backingStream, 5); in.close(); assertEquals(0, in.remaining()); assertEquals(2, backingStream.available()); } }
2,287
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.io; import java.nio.ByteBuffer; import java.util.Collections; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; /** * TCK verifiation test for {@link ChecksumSubscriber}. */ public class ChecksumSubscriberTckTest extends org.reactivestreams.tck.SubscriberBlackboxVerification<ByteBuffer> { public ChecksumSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber() { return new ChecksumSubscriber(Collections.singleton(new Sha256Checksum())); } @Override public ByteBuffer createElement(int i) { return ByteBuffer.wrap(String.valueOf(i).getBytes()); } }
2,288
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.io; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; import software.amazon.awssdk.utils.BinaryUtils; public class ChecksumSubscriberTest { @Test public void checksum_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; SdkChecksum checksum = new Sha256Checksum(); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.singleton(checksum)); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); joinLikeSync(subscriber.completeFuture()); String computedDigest = BinaryUtils.toHex(checksum.getChecksumBytes()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void checksum_withMultipleChecksums_shouldComputeCorrectChecksums() { String testString = "AWS SDK for Java"; String expectedSha256Digest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; String expectedCrc32Digest = "4ac37ece"; SdkChecksum sha256Checksum = new Sha256Checksum(); SdkChecksum crc32Checksum = new Crc32Checksum(); ChecksumSubscriber subscriber = new ChecksumSubscriber(Arrays.asList(sha256Checksum, crc32Checksum)); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); joinLikeSync(subscriber.completeFuture()); String computedSha256Digest = BinaryUtils.toHex(sha256Checksum.getChecksumBytes()); String computedCrc32Digest = BinaryUtils.toHex(crc32Checksum.getChecksumBytes()); assertThat(computedSha256Digest).isEqualTo(expectedSha256Digest); assertThat(computedCrc32Digest).isEqualTo(expectedCrc32Digest); } @Test public void checksum_futureCancelledBeforeSubscribe_cancelsSubscription() { Subscription mockSubscription = mock(Subscription.class); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.emptyList()); subscriber.completeFuture().cancel(true); subscriber.onSubscribe(mockSubscription); verify(mockSubscription).cancel(); verify(mockSubscription, times(0)).request(anyLong()); } @Test public void checksum_publisherCallsOnError_errorPropagatedToFuture() { Subscription mockSubscription = mock(Subscription.class); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.emptyList()); subscriber.onSubscribe(mockSubscription); RuntimeException error = new RuntimeException("error"); subscriber.onError(error); assertThatThrownBy(subscriber.completeFuture()::join).hasCause(error); } }
2,289
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/chunkedencoding/ChunkedEncodedInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding; import static java.util.Arrays.copyOf; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4CanonicalRequest.getCanonicalHeadersString; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.deriveSigningKey; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.hash; import static software.amazon.awssdk.utils.BinaryUtils.toHex; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.http.auth.aws.internal.signer.RollingSigner; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.Pair; public class ChunkedEncodedInputStreamTest { @Test public void ChunkEncodedInputStream_withBasicParams_returnsEncodedChunks() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .build(); byte[] tmp = new byte[64]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 35; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3\r\nabc\r\n3\r\ndef\r\n3\r\nghi\r\n1\r\nj\r\n0\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, bytesRead); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withExtensions_returnsEncodedExtendedChunks() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkExtensionProvider helloWorldExt = chunk -> Pair.of( "hello".getBytes(StandardCharsets.UTF_8), "world!".getBytes(StandardCharsets.UTF_8) ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .extensions(Collections.singletonList(helloWorldExt)) .build(); byte[] tmp = new byte[128]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 100; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( ("3;hello=world!\r\nabc\r\n3;hello=world!\r\ndef\r\n3;hello=world!\r\nghi\r\n" + "1;hello=world!\r\nj\r\n0;hello=world!\r\n\r\n").getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withTrailers_returnsEncodedChunksAndTrailerChunk() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; TrailerProvider helloWorldTrailer = () -> Pair.of( "hello", Collections.singletonList("world!") ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .trailers(Collections.singletonList(helloWorldTrailer)) .build(); byte[] tmp = new byte[64]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 49; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3\r\nabc\r\n3\r\ndef\r\n3\r\nghi\r\n1\r\nj\r\n0\r\nhello:world!\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withExtensionsAndTrailers_EncodedExtendedChunksAndTrailerChunk() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkExtensionProvider aExt = chunk -> Pair.of("a".getBytes(StandardCharsets.UTF_8), "1".getBytes(StandardCharsets.UTF_8)); ChunkExtensionProvider bExt = chunk -> Pair.of("b".getBytes(StandardCharsets.UTF_8), "2".getBytes(StandardCharsets.UTF_8)); TrailerProvider aTrailer = () -> Pair.of("a", Collections.singletonList("1")); TrailerProvider bTrailer = () -> Pair.of("b", Collections.singletonList("2")); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .addExtension(aExt) .addExtension(bExt) .addTrailer(aTrailer) .addTrailer(bTrailer) .build(); byte[] tmp = new byte[128]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 85; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3;a=1;b=2\r\nabc\r\n3;a=1;b=2\r\ndef\r\n3;a=1;b=2\r\nghi\r\n1;a=1;b=2\r\nj\r\n0;a=1;b=2\r\na:1\r\nb:2\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withAwsParams_returnsAwsSignedAndEncodedChunks() throws IOException { byte[] data = new byte[65 * 1024]; Arrays.fill(data, (byte) 'a'); String seedSignature = "106e2a8a18243abcf37539882f36619c00e2dfc72633413f02d3b74544bfeb8e"; CredentialScope credentialScope = new CredentialScope("us-east-1", "s3", Instant.parse("2013-05-24T00:00:00Z")); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"); byte[] signingKey = deriveSigningKey(credentials, credentialScope); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 64 * 1024; RollingSigner signer = new RollingSigner(signingKey, seedSignature); ChunkExtensionProvider ext = chunk -> Pair.of( "chunk-signature".getBytes(StandardCharsets.UTF_8), signer.sign(previousSignature -> "AWS4-HMAC-SHA256-PAYLOAD" + SignerConstant.LINE_SEPARATOR + credentialScope.getDatetime() + SignerConstant.LINE_SEPARATOR + credentialScope.scope() + SignerConstant.LINE_SEPARATOR + previousSignature + SignerConstant.LINE_SEPARATOR + toHex(hash("")) + SignerConstant.LINE_SEPARATOR + toHex(hash(chunk))) .getBytes(StandardCharsets.UTF_8) ); TrailerProvider checksumTrailer = () -> Pair.of( "x-amz-checksum-crc32c", Collections.singletonList("wdBDMA==") ); List<Pair<String, List<String>>> trailers = Collections.singletonList(checksumTrailer.get()); Function<String, String> template = previousSignature -> "AWS4-HMAC-SHA256-TRAILER" + SignerConstant.LINE_SEPARATOR + credentialScope.getDatetime() + SignerConstant.LINE_SEPARATOR + credentialScope.scope() + SignerConstant.LINE_SEPARATOR + previousSignature + SignerConstant.LINE_SEPARATOR + toHex(hash(getCanonicalHeadersString(trailers))); TrailerProvider signatureTrailer = () -> Pair.of( "x-amz-trailer-signature", Collections.singletonList(signer.sign(template)) ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .extensions(Collections.singletonList(ext)) .trailers(Arrays.asList(checksumTrailer, signatureTrailer)) .build(); byte[] tmp = new byte[chunkSize * 4]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 66946; byte[] actualBytes = copyOf(tmp, expectedBytesRead); ByteArrayOutputStream expected = new ByteArrayOutputStream(); expected.write( "10000;chunk-signature=b474d8862b1487a5145d686f57f013e54db672cee1c953b3010fb58501ef5aa2\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(data, 0, chunkSize); expected.write( "\r\n400;chunk-signature=1c1344b170168f8e65b41376b44b20fe354e373826ccbbe2c1d40a8cae51e5c7\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(data, chunkSize, 1024); expected.write( "\r\n0;chunk-signature=2ca2aba2005185cf7159c6277faf83795951dd77a3a99e6e65d5c9f85863f992\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(( "x-amz-checksum-crc32c:wdBDMA==\r\n" + "x-amz-trailer-signature:ce306fa4cdf73aa89071b78358f0d22ea79c43117314c8ed68017f7d6f91048e\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8) ); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected.toByteArray(), actualBytes); } @ParameterizedTest @ValueSource(ints = {1, 2, 3, 5, 8, 13, 21, 24, 45, 69, 104}) void ChunkEncodedInputStream_withVariableChunkSize_shouldCorrectlyChunkData(int chunkSize) throws IOException { int size = 100; byte[] data = new byte[size]; Arrays.fill(data, (byte) 'a'); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(new ByteArrayInputStream(data)) .header(chunk -> new byte[] {'0'}) .chunkSize(chunkSize) .build(); int expectedBytesRead = 0; int numChunks = size / chunkSize; // 0\r\n<data>\r\n expectedBytesRead += numChunks * (5 + chunkSize); if (size % chunkSize != 0) { // 0\r\n\<left-over>\r\n expectedBytesRead += 5 + (size % chunkSize); } // 0\r\n\r\n expectedBytesRead += 5; byte[] tmp = new byte[expectedBytesRead]; int bytesRead = readAll(inputStream, tmp); assertEquals(expectedBytesRead, bytesRead); } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } }
2,290
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/TestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.crt; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.REGION_SET; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.SERVICE_SIGNING_NAME; import static software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.sanitizeRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.spi.signer.HttpSigner.SIGNING_CLOCK; import java.io.ByteArrayInputStream; import java.net.URI; import java.time.Instant; import java.util.function.Consumer; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningUtils; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; public final class TestUtils { private static final String TEST_VERIFICATION_PUB_X = "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1"; private static final String TEST_VERIFICATION_PUB_Y = "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518"; private TestUtils() { } // Helpers for generating test requests public static <T extends AwsCredentialsIdentity> SignRequest<T> generateBasicRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super SignRequest.Builder<T>> signRequestOverrides ) { return SignRequest.builder(credentials) .request(SdkHttpRequest.builder() .method(SdkHttpMethod.POST) .putHeader("x-amz-archive-description", "test test") .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build() .copy(requestOverrides)) .payload(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .putProperty(REGION_SET, RegionSet.create("aws-global")) .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(1596476903000L))) .build() .copy(signRequestOverrides); } public static AwsSigningConfig generateBasicSigningConfig(AwsCredentialsIdentity credentials) { try (AwsSigningConfig signingConfig = new AwsSigningConfig()) { signingConfig.setCredentials(toCredentials(credentials)); signingConfig.setService("demo"); signingConfig.setRegion("aws-global"); signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); signingConfig.setTime(1596476903000L); signingConfig.setUseDoubleUriEncode(true); signingConfig.setShouldNormalizeUriPath(true); return signingConfig; } } public static boolean verifyEcdsaSignature(SdkHttpRequest request, ContentStreamProvider payload, String expectedCanonicalRequest, AwsSigningConfig signingConfig, String signatureValue) { HttpRequest crtRequest = toRequest(sanitizeRequest(request), payload); return AwsSigningUtils.verifySigv4aEcdsaSignature(crtRequest, expectedCanonicalRequest, signingConfig, signatureValue.getBytes(), TEST_VERIFICATION_PUB_X, TEST_VERIFICATION_PUB_Y); } }
2,291
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/signer/AwsChunkedV4aPayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.crt.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_ECDSA_SIGNED_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * Test the delegation of signing to the correct implementations. */ public class AwsChunkedV4aPayloadSignerTest { private static final int CHUNK_SIZE = 4; private static final CredentialScope CREDENTIAL_SCOPE = new CredentialScope("us-east-1", "s3", Instant.EPOCH); private static final byte[] DATA = "{\"TableName\": \"foo\"}".getBytes(); private static final ContentStreamProvider PAYLOAD = () -> new ByteArrayInputStream(DATA); private SdkHttpRequest.Builder requestBuilder; @BeforeEach public void setUp() { requestBuilder = SdkHttpRequest .builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .putHeader(Header.CONTENT_LENGTH, Integer.toString(DATA.length)) .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void sign_withSignedPayload_shouldChunkEncodeWithSigV4aExt() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withSignedPayloadAndChecksum_shouldChunkEncodeWithSigV4aExtAndSigV4aTrailer() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n + trailer-sig-header + trailer-sig + \r\n) expectedBytes += 21 + 8 + 2 + 24 + 144 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withChecksum_shouldChunkEncodeWithChecksumTrailer() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n) expectedBytes += 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailers_shouldChunkEncodeWithExistingTrailers() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("aTrailer"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n) expectedBytes += 9 + 6 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailersAndChecksum_shouldChunkEncodeWithTrailers() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("aTrailer", "x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n + checksum-header + checksum-value + \r\n) expectedBytes += 9 + 6 + 2 + 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailersAndChecksumAndSignedPayload_shouldAwsChunkEncode() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("aTrailer", "x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n + checksum-header + checksum-value + \r\n + trailer-sig-header + trailer-sig + \r\n) expectedBytes += 9 + 6 + 2 + 21 + 8 + 2 + 24 + 144 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withoutContentLength_calculatesContentLengthFromPayload() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); requestBuilder.removeHeader(Header.CONTENT_LENGTH); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n) expectedBytes += 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_shouldReturnResettableContentStreamProvider() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); byte[] tmp = new byte[2048]; int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // successive calls to newStream() should return a stream with the same data every time - this makes sure that state // isn't carried over to the new streams returned by newStream() for (int i = 0; i < 2; i++) { int actualBytes = readAll(signedPayload.newStream(), tmp); assertEquals(expectedBytes, actualBytes); } } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } private AwsSigningConfig basicSigningConfig() { AwsSigningConfig signingConfig = new AwsSigningConfig(); signingConfig.setCredentials(toCredentials(AwsCredentialsIdentity.create("key", "secret"))); signingConfig.setService("s3"); signingConfig.setRegion("aws-global"); signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); signingConfig.setTime(Instant.now().toEpochMilli()); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_CHUNK); return signingConfig; } private int expectedByteCount(byte[] data, int chunkSize) { int size = data.length; int ecdsaSignatureLength = 144; int chunkHeaderLength = 17 + Integer.toHexString(chunkSize).length(); int numChunks = size / chunkSize; int expectedBytes = 0; // normal chunks // x;chunk-signature=<ecdsa>\r\n<data>\r\n expectedBytes += numChunks * (chunkHeaderLength + ecdsaSignatureLength + chunkSize + 4); // remaining chunk // n;chunk-signature=<ecdsa>\r\n\<remaining-data>\r\n int remainingBytes = size % chunkSize; if (remainingBytes > 0) { int remainingChunkHeaderLength = 17 + Integer.toHexString(remainingBytes).length(); expectedBytes += remainingChunkHeaderLength + ecdsaSignatureLength + remainingBytes + 4; } // final chunk // 0;chunk-signature=<ecsda>\r\n\r\n int finalBytes = 0; int finalChunkHeaderLength = 17 + Integer.toHexString(finalBytes).length(); expectedBytes += finalChunkHeaderLength + ecdsaSignatureLength + 4; return expectedBytes; } private int expectedByteCountUnsigned(byte[] data, int chunkSize) { int size = data.length; int chunkHeaderLength = Integer.toHexString(chunkSize).length(); int numChunks = size / chunkSize; int expectedBytes = 0; // normal chunks // x\r\n<data>\r\n expectedBytes += numChunks * (chunkHeaderLength + chunkSize + 4); // remaining chunk // n\r\n\<remaining-data>\r\n int remainingBytes = size % chunkSize; if (remainingBytes > 0) { int remainingChunkHeaderLength = Integer.toHexString(remainingBytes).length(); expectedBytes += remainingChunkHeaderLength + remainingBytes + 4; } // final chunk // 0\r\n\r\n int finalBytes = 0; int finalChunkHeaderLength = Integer.toHexString(finalBytes).length(); expectedBytes += finalChunkHeaderLength + 4; return expectedBytes; } }
2,292
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/signer/DefaultAwsCrtV4aHttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.crt.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC; import static software.amazon.awssdk.http.auth.aws.TestUtils.AnonymousCredentialsIdentity; import static software.amazon.awssdk.http.auth.aws.crt.TestUtils.generateBasicRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.AUTH_LOCATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.AuthLocation; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.CHUNK_ENCODING_ENABLED; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.EXPIRATION_DURATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.PAYLOAD_SIGNING_ENABLED; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * Functional tests for the Sigv4a signer. These tests call the CRT native signer code. */ public class DefaultAwsCrtV4aHttpSignerTest { DefaultAwsCrtV4aHttpSigner signer = new DefaultAwsCrtV4aHttpSigner(); @Test public void sign_withBasicRequest_shouldSignWithHeaders() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> { } ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_HEADERS); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_withQuery_shouldSignWithQueryParams() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_QUERY_PARAMS); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Algorithm")) .hasValue("AWS4-ECDSA-P256-SHA256"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Credential")) .hasValue("AKIDEXAMPLE/20200803/demo/aws4_request"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-SignedHeaders")) .hasValue("host;x-amz-archive-description"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @Test public void sign_withQueryAndExpiration_shouldSignWithQueryParamsAndExpire() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(1)) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_QUERY_PARAMS); expectedSigningConfig.setExpirationInSeconds(1); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Algorithm")) .hasValue("AWS4-ECDSA-P256-SHA256"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Credential")) .hasValue("AKIDEXAMPLE/20200803/demo/aws4_request"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-SignedHeaders")) .hasValue("host;x-amz-archive-description"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).hasValue("1"); } @Test public void sign_withUnsignedPayload_shouldNotSignPayload() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_HEADERS); expectedSigningConfig.setSignedBodyValue(UNSIGNED_PAYLOAD); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_withAnonymousCredentials_shouldNotSign() { AwsCredentialsIdentity credentials = new AnonymousCredentialsIdentity(); SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertNull(signedRequest.request().headers().get("Authorization")); } @Test public void signAsync_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> signer.signAsync((AsyncSignRequest<? extends AwsCredentialsIdentity>) null) ); } @Test public void sign_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("353"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("554"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueWithoutTrailer_DelegatesToUnsignedPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } }
2,293
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/util/CrtHttpRequestConverterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.crt.internal.util; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toCrtStream; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toRequest; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; public class CrtHttpRequestConverterTest { @Test public void request_withHeaders_isConvertedToCrtFormat() { String data = "data"; SdkHttpRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .putHeader("x-amz-archive-description", "test test") .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); ContentStreamProvider payload = () -> new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); HttpRequest crtHttpRequest = toRequest(request, payload); assertThat(crtHttpRequest.getMethod()).isEqualTo("POST"); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/"); List<HttpHeader> headers = crtHttpRequest.getHeaders(); HttpHeader[] headersAsArray = crtHttpRequest.getHeadersAsArray(); assertThat(headers.size()).isEqualTo(2); assertThat(headersAsArray.length).isEqualTo(2); assertThat(headers.get(0).getName()).isEqualTo("Host"); assertThat(headers.get(0).getValue()).isEqualTo("demo.us-east-1.amazonaws.com"); assertThat(headersAsArray[1].getName()).isEqualTo("x-amz-archive-description"); assertThat(headersAsArray[1].getValue()).isEqualTo("test test"); assertStream(data, crtHttpRequest.getBodyStream()); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_withQueryParams_isConvertedToCrtFormat() { SdkHttpRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .putRawQueryParameter("param1", "value1") .putRawQueryParameter("param2", Arrays.asList("value2-1", "value2-2")) .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("/path") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = toRequest(request, (ContentStreamProvider) null); assertThat(crtHttpRequest.getMethod()).isEqualTo("GET"); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/path?param1=value1&param2=value2-1&param2=value2-2"); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_withEmptyPath_isConvertedToCrtFormat() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = toRequest(request, (ContentStreamProvider) null); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/"); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_byteArray_isConvertedToCrtStream() { byte[] data = new byte[144]; Arrays.fill(data, (byte) 0x2A); HttpRequestBodyStream crtStream = toCrtStream(data); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16 * 1024]); crtStream.sendRequestBody(byteBuffer); byteBuffer.flip(); String result = new String(BinaryUtils.copyBytesFrom(byteBuffer), StandardCharsets.UTF_8); assertThat(result.length()).isEqualTo(144); assertThat(result).containsPattern("^\\*+$"); } private void assertHttpRequestSame(SdkHttpRequest originalRequest, HttpRequest crtRequest) { SdkHttpRequest sdkRequest = toRequest(originalRequest, crtRequest); assertThat(sdkRequest.method()).isEqualTo(originalRequest.method()); assertThat(sdkRequest.protocol()).isEqualTo(originalRequest.protocol()); assertThat(sdkRequest.host()).isEqualTo(originalRequest.host()); assertThat(sdkRequest.encodedPath()).isEqualTo(originalRequest.encodedPath()); assertThat(sdkRequest.headers()).isEqualTo(originalRequest.headers()); assertThat(sdkRequest.rawQueryParameters()).isEqualTo(originalRequest.rawQueryParameters()); } private void assertStream(String expectedData, HttpRequestBodyStream crtStream) { ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16 * 1024]); crtStream.sendRequestBody(byteBuffer); byteBuffer.flip(); String result = new String(BinaryUtils.copyBytesFrom(byteBuffer), StandardCharsets.UTF_8); assertThat(result.length()).isEqualTo(expectedData.length()); assertThat(result).isEqualTo(expectedData); } }
2,294
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/scheme/AwsV4aAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.scheme.DefaultAwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * The <a href="https://smithy.io/2.0/aws/aws-auth.html#aws-auth-sigv4a-trait">aws.auth#sigv4a</a> auth scheme, which uses a * {@link AwsCredentialsIdentity} and AwsV4aHttpSigner. */ @SdkPublicApi public interface AwsV4aAuthScheme extends AuthScheme<AwsCredentialsIdentity> { /** * The scheme ID for this interface. */ String SCHEME_ID = "aws.auth#sigv4a"; /** * Get a default implementation of a {@link AwsV4aAuthScheme} */ static AwsV4aAuthScheme create() { return DefaultAwsV4aAuthScheme.create(); } /** * Retrieve the {@link AwsCredentialsIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link AwsV4aHttpSigner} associated with this authentication scheme. */ @Override AwsV4aHttpSigner signer(); }
2,295
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/scheme/AwsV4AuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.scheme.DefaultAwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * The <a href="https://smithy.io/2.0/aws/aws-auth.html#aws-auth-sigv4-trait">aws.auth#sigv4</a> auth scheme, which uses a * {@link AwsCredentialsIdentity} and {@link AwsV4HttpSigner}. */ @SdkPublicApi public interface AwsV4AuthScheme extends AuthScheme<AwsCredentialsIdentity> { /** * The scheme ID for this interface. */ String SCHEME_ID = "aws.auth#sigv4"; /** * Get a default implementation of a {@link AwsV4AuthScheme} */ static AwsV4AuthScheme create() { return DefaultAwsV4AuthScheme.create(); } /** * Retrieve the {@link AwsCredentialsIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link AwsV4HttpSigner} associated with this authentication scheme. */ @Override AwsV4HttpSigner signer(); }
2,296
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/AwsV4HttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.signer.DefaultAwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * An {@link HttpSigner} that will sign a request using an AWS credentials {@link AwsCredentialsIdentity}). * <p> * The process for signing requests to send to AWS services is documented * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html">here</a>. */ @SdkPublicApi public interface AwsV4HttpSigner extends AwsV4FamilyHttpSigner<AwsCredentialsIdentity> { /** * The AWS region name to be used for computing the signature. This property is required. */ SignerProperty<String> REGION_NAME = SignerProperty.create(AwsV4HttpSigner.class, "RegionName"); /** * Get a default implementation of a {@link AwsV4HttpSigner} */ static AwsV4HttpSigner create() { return new DefaultAwsV4HttpSigner(); } }
2,297
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/RegionSet.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.signer; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * This class represents the concept of a set of regions. * <p> * A region-set can contain one or more comma-separated AWS regions, or a single wildcard to represent all regions ("global"). * Whitespace is trimmed from entries of the set. * <p> * Examples of region-sets: * <ul> * <li>'*' - Represents all regions, global</li> * <li>'eu-west-1' - Represents a single region, eu-west-1</li> * <li>'us-west-2,us-east-1' - Represents 2 regions, us-west-2 and us-east-1</li> * </ul> */ @SdkPublicApi @Immutable public final class RegionSet { /** * The "Global" region, which is represented with a single wildcard character: "*". */ public static final RegionSet GLOBAL; static { GLOBAL = create(Collections.singleton("*")); } private final Set<String> regionSet; private final String regionSetString; private RegionSet(Collection<String> regions) { this.regionSet = Collections.unmodifiableSet(new HashSet<>(regions)); this.regionSetString = String.join(",", regionSet); } /** * Gets the string representation of this RegionSet. */ public String asString() { return regionSetString; } /** * Gets the set of strings that represent this RegionSet. */ public Set<String> asSet() { return regionSet; } /** * Creates a RegionSet with the supplied region-set string. * * @param value See class documentation {@link RegionSet} for the expected format. */ public static RegionSet create(String value) { Validate.notBlank(value, "value must not be blank!"); return create(Arrays.asList(value.trim().split(","))); } /** * Creates a RegionSet from the supplied collection. * * @param regions A collection of regions. */ public static RegionSet create(Collection<String> regions) { Validate.notEmpty(regions, "regions must not be empty!"); return new RegionSet( regions.stream().map(s -> Validate.notBlank(s, "region must not be empty!").trim()).collect(Collectors.toList()) ); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegionSet that = (RegionSet) o; return regionSet.equals(that.regionSet); } @Override public int hashCode() { return Objects.hashCode(regionSet); } }
2,298
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/AwsV4aHttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.auth.aws.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.OptionalDependencyLoaderUtil.getDefaultAwsCrtV4aHttpSigner; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * An {@link HttpSigner} that will sign a request using an AWS credentials {@link AwsCredentialsIdentity}). * <p> * The process for signing requests to send to AWS services is documented * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html">here</a>. */ @SdkPublicApi public interface AwsV4aHttpSigner extends AwsV4FamilyHttpSigner<AwsCredentialsIdentity> { /** * The AWS region-set to be used for computing the signature. This property is required. */ SignerProperty<RegionSet> REGION_SET = SignerProperty.create(AwsV4aHttpSigner.class, "RegionSet"); /** * Get a default implementation of a {@link AwsV4aHttpSigner} */ static AwsV4aHttpSigner create() { return getDefaultAwsCrtV4aHttpSigner(); } }
2,299