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/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpStatusCode.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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Constants for common HTTP status codes. */ @SdkProtectedApi public final class HttpStatusCode { // --- 1xx Informational --- public static final int CONTINUE = 100; // --- 2xx Success --- public static final int OK = 200; public static final int CREATED = 201; public static final int ACCEPTED = 202; public static final int NON_AUTHORITATIVE_INFORMATION = 203; public static final int NO_CONTENT = 204; public static final int RESET_CONTENT = 205; public static final int PARTIAL_CONTENT = 206; // --- 3xx Redirection --- public static final int MOVED_PERMANENTLY = 301; public static final int MOVED_TEMPORARILY = 302; public static final int TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- public static final int BAD_REQUEST = 400; public static final int UNAUTHORIZED = 401; public static final int FORBIDDEN = 403; public static final int NOT_FOUND = 404; public static final int METHOD_NOT_ALLOWED = 405; public static final int NOT_ACCEPTABLE = 406; public static final int REQUEST_TIMEOUT = 408; public static final int REQUEST_TOO_LONG = 413; public static final int THROTTLING = 429; // --- 5xx Server Error --- public static final int INTERNAL_SERVER_ERROR = 500; public static final int BAD_GATEWAY = 502; public static final int SERVICE_UNAVAILABLE = 503; public static final int GATEWAY_TIMEOUT = 504; private HttpStatusCode() { } }
2,800
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpService.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; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Service Provider interface for HTTP implementations. The core uses {@link java.util.ServiceLoader} to find appropriate * HTTP implementations on the classpath. HTTP implementations that wish to be discovered by the default HTTP provider chain * should implement this interface and declare that implementation as a service in the * META-INF/service/software.amazon.awssdk.http.SdkHttpService resource. See * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html">Service Loader</a> for more * information. * * <p> * This interface is simply a factory for {@link SdkHttpClient.Builder}. Implementations must be thread safe. * </p> */ @ThreadSafe @SdkPublicApi public interface SdkHttpService { /** * @return An {@link SdkHttpClient.Builder} capable of creating {@link SdkHttpClient} instances. This factory should be thread * safe. */ SdkHttpClient.Builder createHttpClientBuilder(); }
2,801
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkRequestContext.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; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Container for extra dependencies needed during execution of a request. */ @SdkProtectedApi public class SdkRequestContext { private final boolean isFullDuplex; private SdkRequestContext(Builder builder) { this.isFullDuplex = builder.isFullDuplex; } /** * @return Builder instance to construct a {@link SdkRequestContext}. */ @SdkInternalApi public static Builder builder() { return new Builder(); } /** * Option to indicate if the request is for a full duplex operation ie., request and response are sent/received at the same * time. * This can be used to set http configuration like ReadTimeouts as soon as request has begin sending data instead of * waiting for the entire request to be sent. * * @return True if the operation this request belongs to is full duplex. Otherwise false. */ public boolean fullDuplex() { return isFullDuplex; } /** * Builder for a {@link SdkRequestContext}. */ @SdkInternalApi public static final class Builder { private boolean isFullDuplex; private Builder() { } public boolean fullDuplex() { return isFullDuplex; } public Builder fullDuplex(boolean fullDuplex) { isFullDuplex = fullDuplex; return this; } /** * @return An immutable {@link SdkRequestContext} object. */ public SdkRequestContext build() { return new SdkRequestContext(this); } } }
2,802
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpExecuteRequest.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; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCollector; /** * Request object containing the parameters necessary to make a synchronous HTTP request. * * @see SdkHttpClient */ @SdkPublicApi public final class HttpExecuteRequest { private final SdkHttpRequest request; private final Optional<ContentStreamProvider> contentStreamProvider; private final MetricCollector metricCollector; private HttpExecuteRequest(BuilderImpl builder) { this.request = builder.request; this.contentStreamProvider = builder.contentStreamProvider; this.metricCollector = builder.metricCollector; } /** * @return The HTTP request. */ public SdkHttpRequest httpRequest() { return request; } /** * @return The {@link ContentStreamProvider}. */ public Optional<ContentStreamProvider> contentStreamProvider() { return contentStreamProvider; } /** * @return The {@link MetricCollector}. */ public Optional<MetricCollector> metricCollector() { return Optional.ofNullable(metricCollector); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP request to be executed by the client. * * @param request The request. * @return This builder for method chaining. */ Builder request(SdkHttpRequest request); /** * Set the {@link ContentStreamProvider} to be executed by the client. * @param contentStreamProvider The content stream provider * @return This builder for method chaining */ Builder contentStreamProvider(ContentStreamProvider contentStreamProvider); /** * Set the {@link MetricCollector} to be used by the HTTP client to * report metrics collected for this request. * * @param metricCollector The metric collector. * @return This builder for method chaining. */ Builder metricCollector(MetricCollector metricCollector); HttpExecuteRequest build(); } private static class BuilderImpl implements Builder { private SdkHttpRequest request; private Optional<ContentStreamProvider> contentStreamProvider = Optional.empty(); private MetricCollector metricCollector; @Override public Builder request(SdkHttpRequest request) { this.request = request; return this; } @Override public Builder contentStreamProvider(ContentStreamProvider contentStreamProvider) { this.contentStreamProvider = Optional.ofNullable(contentStreamProvider); return this; } @Override public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } @Override public HttpExecuteRequest build() { return new HttpExecuteRequest(this); } } }
2,803
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkCancellationException.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; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Exception thrown when the response subscription is cancelled. */ @SdkPublicApi public final class SdkCancellationException extends RuntimeException { public SdkCancellationException(String message) { super(message); } }
2,804
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpFullResponse.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; import static java.util.Collections.singletonList; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An immutable HTTP response with a possible HTTP body. * * <p>All implementations of this interface MUST be immutable. Instead of implementing this interface, consider using * {@link #builder()} to create an instance.</p> */ @SdkProtectedApi @Immutable public interface SdkHttpFullResponse extends SdkHttpResponse { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullResponse}. */ static Builder builder() { return new DefaultSdkHttpFullResponse.Builder(); } @Override Builder toBuilder(); /** * Returns the optional stream containing the payload data returned by the service. Note: an {@link AbortableInputStream} * is returned instead of an {@link InputStream}. This allows the stream to be aborted before all content is read, which * usually means destroying the underlying HTTP connection. This may be implemented differently in other HTTP implementations. * * <p>When the response does not include payload data, this will return {@link Optional#empty()}.</p> * * @return The optional stream containing the payload data included in this response, or empty if there is no payload. */ Optional<AbortableInputStream> content(); /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ interface Builder extends SdkHttpResponse.Builder { /** * The status text, exactly as it was configured with {@link #statusText(String)}. */ @Override String statusText(); /** * Configure an {@link SdkHttpResponse#statusText()} to be used in the created HTTP response. This is not validated * until the http response is created. */ @Override Builder statusText(String statusText); /** * The status text, exactly as it was configured with {@link #statusCode(int)}. */ @Override int statusCode(); /** * Configure an {@link SdkHttpResponse#statusCode()} to be used in the created HTTP response. This is not validated * until the http response is created. */ @Override Builder statusCode(int statusCode); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ @Override Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ @Override default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ @Override Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ @Override Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpResponse#headers()} to be used in the created HTTP response. This is not validated * until the http response is created. This overrides any values currently configured in the builder. */ @Override Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ @Override Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ @Override Builder clearHeaders(); /** * The content, exactly as it was configured with {@link #content(AbortableInputStream)}. */ AbortableInputStream content(); /** * Configure an {@link SdkHttpFullResponse#content()} to be used in the HTTP response. This is not validated until * the http response is created. * * <p>Implementers should implement the abort method on the input stream to drop all remaining content with the service. * This is usually done by closing the service connection.</p> */ Builder content(AbortableInputStream content); @Override SdkHttpFullResponse build(); } }
2,805
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/DefaultSdkHttpFullResponse.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; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static software.amazon.awssdk.utils.CollectionUtils.unmodifiableMapOfLists; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.internal.http.LowCopyListMap; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * Internal implementation of {@link SdkHttpFullResponse}, buildable via {@link SdkHttpFullResponse#builder()}. Returned by HTTP * implementation to represent a service response. */ @SdkInternalApi @Immutable class DefaultSdkHttpFullResponse implements SdkHttpFullResponse { private static final long serialVersionUID = 1; private final String statusText; private final int statusCode; private final transient AbortableInputStream content; private transient LowCopyListMap.ForBuildable headers; private DefaultSdkHttpFullResponse(Builder builder) { this.statusCode = Validate.isNotNegative(builder.statusCode, "Status code must not be negative."); this.statusText = builder.statusText; this.content = builder.content; this.headers = builder.headers.forBuildable(); } @Override public Map<String, List<String>> headers() { return headers.forExternalRead(); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { this.headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return this.headers.forInternalRead().size(); } @Override public Optional<AbortableInputStream> content() { return Optional.ofNullable(content); } @Override public Optional<String> statusText() { return Optional.ofNullable(statusText); } @Override public int statusCode() { return statusCode; } @Override public SdkHttpFullResponse.Builder toBuilder() { return new Builder(this); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); headers = LowCopyListMap.emptyHeaders().forBuildable(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultSdkHttpFullResponse that = (DefaultSdkHttpFullResponse) o; return (statusCode == that.statusCode) && Objects.equals(statusText, that.statusText) && Objects.equals(headers, that.headers); } @Override public int hashCode() { int result = statusText != null ? statusText.hashCode() : 0; result = 31 * result + statusCode; result = 31 * result + Objects.hashCode(headers); return result; } /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ static final class Builder implements SdkHttpFullResponse.Builder { private String statusText; private int statusCode; private AbortableInputStream content; private LowCopyListMap.ForBuilder headers; Builder() { headers = LowCopyListMap.emptyHeaders(); } private Builder(DefaultSdkHttpFullResponse defaultSdkHttpFullResponse) { statusText = defaultSdkHttpFullResponse.statusText; statusCode = defaultSdkHttpFullResponse.statusCode; content = defaultSdkHttpFullResponse.content; headers = defaultSdkHttpFullResponse.headers.forBuilder(); } @Override public String statusText() { return statusText; } @Override public Builder statusText(String statusText) { this.statusText = statusText; return this; } @Override public int statusCode() { return statusCode; } @Override public Builder statusCode(int statusCode) { this.statusCode = statusCode; return this; } @Override public AbortableInputStream content() { return content; } @Override public Builder content(AbortableInputStream content) { this.content = content; return this; } @Override public Builder putHeader(String headerName, List<String> headerValues) { Validate.paramNotNull(headerName, "headerName"); Validate.paramNotNull(headerValues, "headerValues"); this.headers.forInternalWrite().put(headerName, new ArrayList<>(headerValues)); return this; } @Override public SdkHttpFullResponse.Builder appendHeader(String headerName, String headerValue) { Validate.paramNotNull(headerName, "headerName"); Validate.paramNotNull(headerValue, "headerValue"); this.headers.forInternalWrite().computeIfAbsent(headerName, k -> new ArrayList<>()).add(headerValue); return this; } @Override public Builder headers(Map<String, List<String>> headers) { Validate.paramNotNull(headers, "headers"); this.headers.setFromExternal(headers); return this; } @Override public Builder removeHeader(String headerName) { this.headers.forInternalWrite().remove(headerName); return this; } @Override public Builder clearHeaders() { this.headers.clear(); return this; } @Override public Map<String, List<String>> headers() { return unmodifiableMapOfLists(this.headers.forInternalRead()); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } /** * @return An immutable {@link DefaultSdkHttpFullResponse} object. */ @Override public SdkHttpFullResponse build() { return new DefaultSdkHttpFullResponse(this); } } }
2,806
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/TlsKeyManagersProvider.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; import javax.net.ssl.KeyManager; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider; /** * Provider for the {@link KeyManager key managers} to be used by the SDK when * creating the SSL context. Key managers are used when the client is required * to authenticate with the remote TLS peer, such as an HTTP proxy. */ @SdkPublicApi @FunctionalInterface public interface TlsKeyManagersProvider { /** * @return The {@link KeyManager}s, or {@code null}. */ KeyManager[] keyManagers(); /** * @return A provider that returns a {@code null} array of {@link KeyManager}s. */ static TlsKeyManagersProvider noneProvider() { return NoneTlsKeyManagersProvider.getInstance(); } }
2,807
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpStatusFamily.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; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The set of HTTP status families defined by the standard. A code can be converted to its family with {@link #of(int)}. */ @SdkProtectedApi public enum HttpStatusFamily { /** * 1xx response family. */ INFORMATIONAL, /** * 2xx response family. */ SUCCESSFUL, /** * 3xx response family. */ REDIRECTION, /** * 4xx response family. */ CLIENT_ERROR, /** * 5xx response family. */ SERVER_ERROR, /** * The family for any status code outside of the range 100-599. */ OTHER; /** * Retrieve the HTTP status family for the given HTTP status code. */ public static HttpStatusFamily of(int httpStatusCode) { switch (httpStatusCode / 100) { case 1: return INFORMATIONAL; case 2: return SUCCESSFUL; case 3: return REDIRECTION; case 4: return CLIENT_ERROR; case 5: return SERVER_ERROR; default: return OTHER; } } /** * Determine whether this HTTP status family is in the list of provided families. * * @param families The list of families to check against this family. * @return True if any of the families in the list match this one. */ public boolean isOneOf(HttpStatusFamily... families) { return families != null && Stream.of(families).anyMatch(family -> family == this); } }
2,808
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/ExecutableHttpRequest.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; import java.io.IOException; import java.util.concurrent.Callable; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An HTTP request that can be invoked by {@link #call()}. Once invoked, the HTTP call can be cancelled via {@link #abort()}, * which should release the thread that has invoked {@link #call()} as soon as possible. */ @SdkPublicApi public interface ExecutableHttpRequest extends Callable<HttpExecuteResponse>, Abortable { @Override HttpExecuteResponse call() throws IOException; }
2,809
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Abortable.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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An Abortable task. */ @SdkProtectedApi public interface Abortable { /** * Aborts the execution of the task. Multiple calls to abort or calling abort an already aborted task * should return without error. */ void abort(); }
2,810
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpExecutionAttribute.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; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.utils.AttributeMap; /** * An attribute attached to a particular HTTP request execution, stored in {@link SdkHttpExecutionAttributes}. It can be * configured on an {@link AsyncExecuteRequest} via * {@link AsyncExecuteRequest.Builder#putHttpExecutionAttribute(SdkHttpExecutionAttribute, * Object)} * * @param <T> The type of data associated with this attribute. */ @SdkPublicApi public abstract class SdkHttpExecutionAttribute<T> extends AttributeMap.Key<T> { protected SdkHttpExecutionAttribute(Class<T> valueType) { super(valueType); } protected SdkHttpExecutionAttribute(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
2,811
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpRequest.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; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable HTTP request without access to the request body. {@link SdkHttpFullRequest} should be used when access to a * request body stream is required. */ @SdkProtectedApi @Immutable public interface SdkHttpRequest extends SdkHttpHeaders, ToCopyableBuilder<SdkHttpRequest.Builder, SdkHttpRequest> { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullRequest}. */ static Builder builder() { return new DefaultSdkHttpFullRequest.Builder(); } /** * Returns the protocol that should be used for HTTP communication. * * <p>This will always be "https" or "http" (lowercase).</p> * * @return Either "http" or "https" depending on which protocol should be used. */ String protocol(); /** * Returns the host that should be communicated with. * * <p>This will never be null.</p> * * @return The host to which the request should be sent. */ String host(); /** * The port that should be used for HTTP communication. If this was not configured when the request was created, it will be * derived from the protocol. For "http" it would be 80, and for "https" it would be 443. * * <p>Important Note: AWS signing DOES NOT include the port when the request is signed if the default port for the protocol is * being used. When sending requests via http over port 80 or via https over port 443, the URI or host header MUST NOT include * the port or a signature error will be raised from the service for signed requests. HTTP plugin implementers are encouraged * to use the {@link #getUri()} method for generating the URI to use for communicating with AWS to ensure the URI used in the * request matches the URI used during signing.</p> * * @return The port that should be used for HTTP communication. */ int port(); /** * Returns the URL-encoded path that should be used in the HTTP request. * * <p>If a path is configured, the path will always start with '/' and may or may not end with '/', depending on what the * service might expect. If a path is not configured, this will always return empty-string (ie. ""). Note that '/' is also a * valid path.</p> * * @return The path to the resource being requested. */ String encodedPath(); /** * Returns a map of all non-URL encoded parameters in this request. HTTP plugins can use * {@link SdkHttpUtils#encodeQueryParameters(Map)} to encode parameters into map-form, or * {@link SdkHttpUtils#encodeAndFlattenQueryParameters(Map)} to encode the parameters into uri-formatted string form. * * <p>This will never be null. If there are no parameters an empty map is returned.</p> * * @return An unmodifiable map of all non-encoded parameters in this request. */ Map<String, List<String>> rawQueryParameters(); default Optional<String> firstMatchingRawQueryParameter(String key) { List<String> values = rawQueryParameters().get(key); return values == null ? Optional.empty() : values.stream().findFirst(); } default Optional<String> firstMatchingRawQueryParameter(Collection<String> keys) { for (String key : keys) { Optional<String> result = firstMatchingRawQueryParameter(key); if (result.isPresent()) { return result; } } return Optional.empty(); } default List<String> firstMatchingRawQueryParameters(String key) { List<String> values = rawQueryParameters().get(key); return values == null ? emptyList() : values; } default void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { rawQueryParameters().forEach(consumer); } default int numRawQueryParameters() { return rawQueryParameters().size(); } default Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(rawQueryParameters()); } default Optional<String> encodedQueryParametersAsFormData() { return SdkHttpUtils.encodeAndFlattenFormData(rawQueryParameters()); } /** * Convert this HTTP request's protocol, host, port, path and query string into a properly-encoded URI string that matches the * URI string used for AWS request signing. * * <p>The URI's port will be missing (-1) when the {@link #port()} is the default port for the {@link #protocol()}. (80 for * http and 443 for https). This is to reflect the fact that request signature does not include the port.</p> * * @return The URI for this request, formatted in the same way the AWS HTTP request signer uses the URI in the signature. */ default URI getUri() { // We can't create a URI by simply passing the query parameters into the URI constructor that takes a query string, // because URI will re-encode them. Because we want to encode them using our encoder, we have to build the URI // ourselves and pass it to the single-argument URI constructor that doesn't perform the encoding. String encodedQueryString = encodedQueryParameters().map(value -> "?" + value).orElse(""); // Do not include the port in the URI when using the default port for the protocol. String portString = SdkHttpUtils.isUsingStandardPort(protocol(), port()) ? "" : ":" + port(); return URI.create(protocol() + "://" + host() + portString + encodedPath() + encodedQueryString); } /** * Returns the HTTP method (GET, POST, etc) to use when sending this request. * * <p>This will never be null.</p> * * @return The HTTP method to use when sending this request. */ SdkHttpMethod method(); /** * A mutable builder for {@link SdkHttpFullRequest}. An instance of this can be created using * {@link SdkHttpFullRequest#builder()}. */ interface Builder extends CopyableBuilder<Builder, SdkHttpRequest>, SdkHttpHeaders { /** * Convenience method to set the {@link #protocol()}, {@link #host()}, {@link #port()}, * {@link #encodedPath()} and extracts query parameters from a {@link URI} object. * * @param uri URI containing protocol, host, port and path. * @return This builder for method chaining. */ default Builder uri(URI uri) { Builder builder = this.protocol(uri.getScheme()) .host(uri.getHost()) .port(uri.getPort()) .encodedPath(SdkHttpUtils.appendUri(uri.getRawPath(), encodedPath())); if (uri.getRawQuery() != null) { builder.clearQueryParameters(); SdkHttpUtils.uriParams(uri) .forEach(this::putRawQueryParameter); } return builder; } /** * The protocol, exactly as it was configured with {@link #protocol(String)}. */ String protocol(); /** * Configure a {@link SdkHttpRequest#protocol()} to be used in the created HTTP request. This is not validated until the * http request is created. */ Builder protocol(String protocol); /** * The host, exactly as it was configured with {@link #host(String)}. */ String host(); /** * Configure a {@link SdkHttpRequest#host()} to be used in the created HTTP request. This is not validated until the * http request is created. */ Builder host(String host); /** * The port, exactly as it was configured with {@link #port(Integer)}. */ Integer port(); /** * Configure a {@link SdkHttpRequest#port()} to be used in the created HTTP request. This is not validated until the * http request is created. In order to simplify mapping from a {@link URI}, "-1" will be treated as "null" when the http * request is created. */ Builder port(Integer port); /** * The path, exactly as it was configured with {@link #encodedPath(String)}. */ String encodedPath(); /** * Configure an {@link SdkHttpRequest#encodedPath()} to be used in the created HTTP request. This is not validated * until the http request is created. This path MUST be URL encoded. * * <p>Justification of requirements: The path must be encoded when it is configured, because there is no way for the HTTP * implementation to distinguish a "/" that is part of a resource name that should be encoded as "%2F" from a "/" that is * part of the actual path.</p> */ Builder encodedPath(String path); /** * The query parameters, exactly as they were configured with {@link #rawQueryParameters(Map)}, * {@link #putRawQueryParameter(String, String)} and {@link #putRawQueryParameter(String, List)}. */ Map<String, List<String>> rawQueryParameters(); /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ default Builder putRawQueryParameter(String paramName, String paramValue) { return putRawQueryParameter(paramName, singletonList(paramValue)); } /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this parameter name in * the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ Builder appendRawQueryParameter(String paramName, String paramValue); /** * Add a single un-encoded query parameter with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValues The un-encoded values for the query parameter. */ Builder putRawQueryParameter(String paramName, List<String> paramValues); /** * Configure an {@link SdkHttpRequest#rawQueryParameters()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. The query parameters * MUST NOT be URL encoded. * * <p>Justification of requirements: The query parameters must not be encoded when they are configured because some HTTP * implementations perform this encoding automatically.</p> */ Builder rawQueryParameters(Map<String, List<String>> queryParameters); /** * Remove all values for the requested query parameter from this builder. */ Builder removeQueryParameter(String paramName); /** * Removes all query parameters from this builder. */ Builder clearQueryParameters(); default void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { rawQueryParameters().forEach(consumer); } default int numRawQueryParameters() { return rawQueryParameters().size(); } default Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(rawQueryParameters()); } /** * The path, exactly as it was configured with {@link #method(SdkHttpMethod)}. */ SdkHttpMethod method(); /** * Configure an {@link SdkHttpRequest#method()} to be used in the created HTTP request. This is not validated * until the http request is created. */ Builder method(SdkHttpMethod httpMethod); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpRequest#headers()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. */ Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ Builder clearHeaders(); } }
2,812
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpResponse.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; import static java.util.Collections.singletonList; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An immutable HTTP response without access to the response body. {@link SdkHttpFullResponse} should be used when access to a * response body stream is required. */ @SdkPublicApi @Immutable public interface SdkHttpResponse extends ToCopyableBuilder<SdkHttpResponse.Builder, SdkHttpResponse>, SdkHttpHeaders, Serializable { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullResponse}. */ static SdkHttpFullResponse.Builder builder() { return new DefaultSdkHttpFullResponse.Builder(); } /** * Returns the HTTP status text returned by the service. * * <p>If this was not provided by the service, empty will be returned.</p> */ Optional<String> statusText(); /** * Returns the HTTP status code (eg. 200, 404, etc.) returned by the service. * * <p>This will always be positive.</p> */ int statusCode(); /** * If we get back any 2xx status code, then we know we should treat the service call as successful. */ default boolean isSuccessful() { return HttpStatusFamily.of(statusCode()) == HttpStatusFamily.SUCCESSFUL; } /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ interface Builder extends CopyableBuilder<Builder, SdkHttpResponse>, SdkHttpHeaders { /** * The status text, exactly as it was configured with {@link #statusText(String)}. */ String statusText(); /** * Configure an {@link SdkHttpResponse#statusText()} to be used in the created HTTP response. This is not validated * until the http response is created. */ Builder statusText(String statusText); /** * The status text, exactly as it was configured with {@link #statusCode(int)}. */ int statusCode(); /** * Configure an {@link SdkHttpResponse#statusCode()} to be used in the created HTTP response. This is not validated * until the http response is created. */ Builder statusCode(int statusCode); /** * The HTTP headers, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpResponse#headers()} to be used in the created HTTP response. This is not validated * until the http response is created. This overrides any values currently configured in the builder. */ Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ Builder clearHeaders(); } }
2,813
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Header.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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Constants for commonly used HTTP headers. */ @SdkProtectedApi public final class Header { public static final String CONTENT_LENGTH = "Content-Length"; public static final String CONTENT_TYPE = "Content-Type"; public static final String CONTENT_MD5 = "Content-MD5"; public static final String TRANSFER_ENCODING = "Transfer-Encoding"; public static final String CHUNKED = "chunked"; public static final String HOST = "Host"; public static final String CONNECTION = "Connection"; public static final String KEEP_ALIVE_VALUE = "keep-alive"; public static final String ACCEPT = "Accept"; private Header() { } }
2,814
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpConfigurationOption.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; import java.time.Duration; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.AttributeMap; /** * Type safe key for an HTTP related configuration option. These options are used for service specific configuration * and are treated as hints for the underlying HTTP implementation for better defaults. If an implementation does not support * a particular option, they are free to ignore it. * * @param <T> Type of option * @see AttributeMap */ @SdkProtectedApi public final class SdkHttpConfigurationOption<T> extends AttributeMap.Key<T> { /** * Timeout for each read to the underlying socket. */ public static final SdkHttpConfigurationOption<Duration> READ_TIMEOUT = new SdkHttpConfigurationOption<>("ReadTimeout", Duration.class); /** * Timeout for each write to the underlying socket. */ public static final SdkHttpConfigurationOption<Duration> WRITE_TIMEOUT = new SdkHttpConfigurationOption<>("WriteTimeout", Duration.class); /** * Timeout for establishing a connection to a remote service. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionTimeout", Duration.class); /** * Timeout for acquiring an already-established connection from a connection pool to a remote service. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_ACQUIRE_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionAcquireTimeout", Duration.class); /** * Timeout after which an idle connection should be closed. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_MAX_IDLE_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionMaxIdleTimeout", Duration.class); /** * Timeout after which a connection should be closed, regardless of whether it is idle. Zero indicates an infinite amount * of time. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_TIME_TO_LIVE = new SdkHttpConfigurationOption<>("ConnectionTimeToLive", Duration.class); /** * Maximum number of connections allowed in a connection pool. */ public static final SdkHttpConfigurationOption<Integer> MAX_CONNECTIONS = new SdkHttpConfigurationOption<>("MaxConnections", Integer.class); /** * HTTP protocol to use. */ public static final SdkHttpConfigurationOption<Protocol> PROTOCOL = new SdkHttpConfigurationOption<>("Protocol", Protocol.class); /** * Maximum number of requests allowed to wait for a connection. */ public static final SdkHttpConfigurationOption<Integer> MAX_PENDING_CONNECTION_ACQUIRES = new SdkHttpConfigurationOption<>("MaxConnectionAcquires", Integer.class); /** * Whether idle connection should be removed after the {@link #CONNECTION_MAX_IDLE_TIMEOUT} has passed. */ public static final SdkHttpConfigurationOption<Boolean> REAP_IDLE_CONNECTIONS = new SdkHttpConfigurationOption<>("ReapIdleConnections", Boolean.class); /** * Whether to enable or disable TCP KeepAlive. * <p> * When enabled, the actual KeepAlive mechanism is dependent on the Operating System and therefore additional TCP KeepAlive * values (like timeout, number of packets, etc) must be configured via the Operating System (sysctl on Linux/Mac, and * Registry values on Windows). */ public static final SdkHttpConfigurationOption<Boolean> TCP_KEEPALIVE = new SdkHttpConfigurationOption<>("TcpKeepalive", Boolean.class); /** * The {@link TlsKeyManagersProvider} that will be used by the HTTP client when authenticating with a * TLS host. */ public static final SdkHttpConfigurationOption<TlsKeyManagersProvider> TLS_KEY_MANAGERS_PROVIDER = new SdkHttpConfigurationOption<>("TlsKeyManagersProvider", TlsKeyManagersProvider.class); /** * Option to disable SSL cert validation and SSL host name verification. By default, this option is off. * Only enable this option for testing purposes. */ public static final SdkHttpConfigurationOption<Boolean> TRUST_ALL_CERTIFICATES = new SdkHttpConfigurationOption<>("TrustAllCertificates", Boolean.class); /** * The {@link TlsTrustManagersProvider} that will be used by the HTTP client when authenticating with a * TLS host. */ public static final SdkHttpConfigurationOption<TlsTrustManagersProvider> TLS_TRUST_MANAGERS_PROVIDER = new SdkHttpConfigurationOption<>("TlsTrustManagersProvider", TlsTrustManagersProvider.class); /** * The maximum amount of time that a TLS handshake is allowed to take from the time the CLIENT HELLO * message is sent to the time the client and server have fully negotiated ciphers and exchanged keys. * * <p> * If not specified, the default value will be the same as the resolved {@link #CONNECTION_TIMEOUT}. */ public static final SdkHttpConfigurationOption<Duration> TLS_NEGOTIATION_TIMEOUT = new SdkHttpConfigurationOption<>("TlsNegotiationTimeout", Duration.class); private static final Duration DEFAULT_SOCKET_READ_TIMEOUT = Duration.ofSeconds(30); private static final Duration DEFAULT_SOCKET_WRITE_TIMEOUT = Duration.ofSeconds(30); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(2); private static final Duration DEFAULT_CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(10); private static final Duration DEFAULT_CONNECTION_MAX_IDLE_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_CONNECTION_TIME_TO_LIVE = Duration.ZERO; /** * 5 seconds = 3 seconds (RTO for 2 packets loss) + 2 seconds (startup latency and RTT buffer) */ private static final Duration DEFAULT_TLS_NEGOTIATION_TIMEOUT = Duration.ofSeconds(5); private static final Boolean DEFAULT_REAP_IDLE_CONNECTIONS = Boolean.TRUE; private static final int DEFAULT_MAX_CONNECTIONS = 50; private static final int DEFAULT_MAX_CONNECTION_ACQUIRES = 10_000; private static final Boolean DEFAULT_TCP_KEEPALIVE = Boolean.FALSE; private static final Boolean DEFAULT_TRUST_ALL_CERTIFICATES = Boolean.FALSE; private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTP1_1; private static final TlsTrustManagersProvider DEFAULT_TLS_TRUST_MANAGERS_PROVIDER = null; private static final TlsKeyManagersProvider DEFAULT_TLS_KEY_MANAGERS_PROVIDER = SystemPropertyTlsKeyManagersProvider.create(); public static final AttributeMap GLOBAL_HTTP_DEFAULTS = AttributeMap .builder() .put(READ_TIMEOUT, DEFAULT_SOCKET_READ_TIMEOUT) .put(WRITE_TIMEOUT, DEFAULT_SOCKET_WRITE_TIMEOUT) .put(CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT) .put(CONNECTION_ACQUIRE_TIMEOUT, DEFAULT_CONNECTION_ACQUIRE_TIMEOUT) .put(CONNECTION_MAX_IDLE_TIMEOUT, DEFAULT_CONNECTION_MAX_IDLE_TIMEOUT) .put(CONNECTION_TIME_TO_LIVE, DEFAULT_CONNECTION_TIME_TO_LIVE) .put(MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS) .put(MAX_PENDING_CONNECTION_ACQUIRES, DEFAULT_MAX_CONNECTION_ACQUIRES) .put(PROTOCOL, DEFAULT_PROTOCOL) .put(TRUST_ALL_CERTIFICATES, DEFAULT_TRUST_ALL_CERTIFICATES) .put(REAP_IDLE_CONNECTIONS, DEFAULT_REAP_IDLE_CONNECTIONS) .put(TCP_KEEPALIVE, DEFAULT_TCP_KEEPALIVE) .put(TLS_KEY_MANAGERS_PROVIDER, DEFAULT_TLS_KEY_MANAGERS_PROVIDER) .put(TLS_TRUST_MANAGERS_PROVIDER, DEFAULT_TLS_TRUST_MANAGERS_PROVIDER) .put(TLS_NEGOTIATION_TIMEOUT, DEFAULT_TLS_NEGOTIATION_TIMEOUT) .build(); private final String name; private SdkHttpConfigurationOption(String name, Class<T> clzz) { super(clzz); this.name = name; } /** * Note that the name is mainly used for debugging purposes. Two option key objects with the same name do not represent * the same option. Option keys are compared by reference when obtaining a value from an {@link AttributeMap}. * * @return Name of this option key. */ public String name() { return name; } @Override public String toString() { return name; } }
2,815
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpMetric.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; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; /** * Metrics collected by HTTP clients for HTTP/1 and HTTP/2 operations. See {@link Http2Metric} for metrics that are only available * on HTTP/2 operations. */ @SdkPublicApi public final class HttpMetric { /** * The name of the HTTP client. */ public static final SdkMetric<String> HTTP_CLIENT_NAME = metric("HttpClientName", String.class, MetricLevel.INFO); /** * The maximum number of concurrent requests that is supported by the HTTP client. * * <p>For HTTP/1 operations, this is equal to the maximum number of TCP connections that can be be pooled by the HTTP client. * For HTTP/2 operations, this is equal to the maximum number of streams that can be pooled by the HTTP client. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> MAX_CONCURRENCY = metric("MaxConcurrency", Integer.class, MetricLevel.INFO); /** * The number of additional concurrent requests that can be supported by the HTTP client without needing to establish * additional connections to the target server. * * <p>For HTTP/1 operations, this is equal to the number of TCP connections that have been established with the service, * but are currently idle/unused. For HTTP/2 operations, this is equal to the number of streams that are currently * idle/unused. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> AVAILABLE_CONCURRENCY = metric("AvailableConcurrency", Integer.class, MetricLevel.INFO); /** * The number of requests that are currently being executed by the HTTP client. * * <p>For HTTP/1 operations, this is equal to the number of TCP connections currently in active communication with the service * (excluding idle connections). For HTTP/2 operations, this is equal to the number of HTTP streams currently in active * communication with the service (excluding idle stream capacity). * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> LEASED_CONCURRENCY = metric("LeasedConcurrency", Integer.class, MetricLevel.INFO); /** * The number of requests that are awaiting concurrency to be made available from the HTTP client. * * <p>For HTTP/1 operations, this is equal to the number of requests currently blocked, waiting for a TCP connection to be * established or returned from the connection pool. For HTTP/2 operations, this is equal to the number of requests currently * blocked, waiting for a new stream (and possibly a new HTTP/2 connection) from the connection pool. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> PENDING_CONCURRENCY_ACQUIRES = metric("PendingConcurrencyAcquires", Integer.class, MetricLevel.INFO); /** * The status code of the HTTP response. * * <p> * This is reported by the SDK core, and should not be reported by an individual HTTP client implementation. */ public static final SdkMetric<Integer> HTTP_STATUS_CODE = metric("HttpStatusCode", Integer.class, MetricLevel.TRACE); /** * The time taken to acquire a channel from the connection pool. * * <p>For HTTP/1 operations, a channel is equivalent to a TCP connection. For HTTP/2 operations, a channel is equivalent to * an HTTP/2 stream channel. For both protocols, the time to acquire a new channel may include the following: * <ol> * <li>Awaiting a concurrency permit, as restricted by the client's max concurrency configuration.</li> * <li>The time to establish a new connection, depending on whether an existing connection is available in the pool or * not.</li> * <li>The time taken to perform a TLS handshake/negotiation, if TLS is enabled.</li> * </ol> */ public static final SdkMetric<Duration> CONCURRENCY_ACQUIRE_DURATION = metric("ConcurrencyAcquireDuration", Duration.class, MetricLevel.INFO); private HttpMetric() { } private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) { return SdkMetric.create(name, clzz, level, MetricCategory.CORE, MetricCategory.HTTP_CLIENT); } }
2,816
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkHttpContentPublisher.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.async; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A {@link Publisher} of HTTP content data that allows streaming operations for asynchronous HTTP clients. */ @SdkPublicApi public interface SdkHttpContentPublisher extends Publisher<ByteBuffer> { /** * @return The content length of the data being produced. */ Optional<Long> contentLength(); }
2,817
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/AsyncExecuteRequest.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.async; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpExecutionAttribute; import software.amazon.awssdk.http.SdkHttpExecutionAttributes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.Validate; /** * Request object containing the parameters necessary to make an asynchronous HTTP request. * * @see SdkAsyncHttpClient */ @SdkPublicApi public final class AsyncExecuteRequest { private final SdkHttpRequest request; private final SdkHttpContentPublisher requestContentPublisher; private final SdkAsyncHttpResponseHandler responseHandler; private final MetricCollector metricCollector; private final boolean isFullDuplex; private final SdkHttpExecutionAttributes sdkHttpExecutionAttributes; private AsyncExecuteRequest(BuilderImpl builder) { this.request = builder.request; this.requestContentPublisher = builder.requestContentPublisher; this.responseHandler = builder.responseHandler; this.metricCollector = builder.metricCollector; this.isFullDuplex = builder.isFullDuplex; this.sdkHttpExecutionAttributes = builder.executionAttributesBuilder.build(); } /** * @return The HTTP request. */ public SdkHttpRequest request() { return request; } /** * @return The publisher of request body. */ public SdkHttpContentPublisher requestContentPublisher() { return requestContentPublisher; } /** * @return The response handler. */ public SdkAsyncHttpResponseHandler responseHandler() { return responseHandler; } /** * @return The {@link MetricCollector}. */ public Optional<MetricCollector> metricCollector() { return Optional.ofNullable(metricCollector); } /** * @return True if the operation this request belongs to is full duplex. Otherwise false. */ public boolean fullDuplex() { return isFullDuplex; } /** * @return the SDK HTTP execution attributes associated with this request */ public SdkHttpExecutionAttributes httpExecutionAttributes() { return sdkHttpExecutionAttributes; } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP request to be executed by the client. * * @param request The request. * @return This builder for method chaining. */ Builder request(SdkHttpRequest request); /** * Set the publisher of the request content. * * @param requestContentPublisher The publisher. * @return This builder for method chaining. */ Builder requestContentPublisher(SdkHttpContentPublisher requestContentPublisher); /** * Set the response handler for the resposne. * * @param responseHandler The response handler. * @return This builder for method chaining. */ Builder responseHandler(SdkAsyncHttpResponseHandler responseHandler); /** * Set the {@link MetricCollector} to be used by the HTTP client to * report metrics collected for this request. * * @param metricCollector The metric collector. * @return This builder for method chaining. */ Builder metricCollector(MetricCollector metricCollector); /** * Option to indicate if the request is for a full duplex operation ie., request and response are sent/received at * the same time. * <p> * This can be used to set http configuration like ReadTimeouts as soon as request has begin sending data instead of * waiting for the entire request to be sent. * * @return True if the operation this request belongs to is full duplex. Otherwise false. */ Builder fullDuplex(boolean fullDuplex); /** * Put an HTTP execution attribute into to the collection of HTTP execution attributes for this request * * @param attribute The execution attribute object * @param value The value of the execution attribute. */ <T> Builder putHttpExecutionAttribute(SdkHttpExecutionAttribute<T> attribute, T value); /** * Sets the additional HTTP execution attributes collection for this request. * <p> * This will override the attributes configured through * {@link #putHttpExecutionAttribute(SdkHttpExecutionAttribute, Object)} * * @param executionAttributes Execution attributes map for this request. * @return This object for method chaining. */ Builder httpExecutionAttributes(SdkHttpExecutionAttributes executionAttributes); AsyncExecuteRequest build(); } private static class BuilderImpl implements Builder { private SdkHttpRequest request; private SdkHttpContentPublisher requestContentPublisher; private SdkAsyncHttpResponseHandler responseHandler; private MetricCollector metricCollector; private boolean isFullDuplex; private SdkHttpExecutionAttributes.Builder executionAttributesBuilder = SdkHttpExecutionAttributes.builder(); @Override public Builder request(SdkHttpRequest request) { this.request = request; return this; } @Override public Builder requestContentPublisher(SdkHttpContentPublisher requestContentPublisher) { this.requestContentPublisher = requestContentPublisher; return this; } @Override public Builder responseHandler(SdkAsyncHttpResponseHandler responseHandler) { this.responseHandler = responseHandler; return this; } @Override public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } @Override public Builder fullDuplex(boolean fullDuplex) { isFullDuplex = fullDuplex; return this; } @Override public <T> Builder putHttpExecutionAttribute(SdkHttpExecutionAttribute<T> attribute, T value) { this.executionAttributesBuilder.put(attribute, value); return this; } @Override public Builder httpExecutionAttributes(SdkHttpExecutionAttributes executionAttributes) { Validate.paramNotNull(executionAttributes, "executionAttributes"); this.executionAttributesBuilder = executionAttributes.toBuilder(); return this; } @Override public AsyncExecuteRequest build() { return new AsyncExecuteRequest(this); } } }
2,818
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkHttpResponseHandler.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.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.http.SdkHttpResponse; /** * Responsible for handling asynchronous http responses * * @param <T> Type of result returned in {@link #complete()}. May be {@link Void}. */ @SdkProtectedApi public interface SdkHttpResponseHandler<T> { /** * Called when the initial response with headers is received. * * @param response the {@link SdkHttpResponse} */ void headersReceived(SdkHttpResponse response); /** * Called when the HTTP client is ready to start sending data to the response handler. Implementations * must subscribe to the {@link Publisher} and request data via a {@link org.reactivestreams.Subscription} as * they can handle it. * * <p> * If at any time the subscriber wishes to stop receiving data, it may call {@link Subscription#cancel()}. This * will be treated as a failure of the response and the {@link #exceptionOccurred(Throwable)} callback will be invoked. * </p> */ void onStream(Publisher<ByteBuffer> publisher); /** * Called when an exception occurs during the request/response. * * This is a terminal method call, no other method invocations should be expected * on the {@link SdkHttpResponseHandler} after this point. * * @param throwable the exception that occurred. */ void exceptionOccurred(Throwable throwable); /** * Called when all parts of the response have been received. * * This is a terminal method call, no other method invocations should be expected * on the {@link SdkHttpResponseHandler} after this point. * * @return Transformed result. */ T complete(); }
2,819
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpClient.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.async; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Interface to take a representation of an HTTP request, asynchronously make an HTTP call, and return a representation of an * HTTP response. * * <p>Implementations MUST be thread safe.</p> */ @Immutable @ThreadSafe @SdkPublicApi public interface SdkAsyncHttpClient extends SdkAutoCloseable { /** * Execute the request. * * @param request The request object. * * @return The future holding the result of the request execution. Upon success execution of the request, the future is * completed with {@code null}, otherwise it is completed exceptionally. */ CompletableFuture<Void> execute(AsyncExecuteRequest request); /** * Each HTTP client implementation should return a well-formed client name * that allows requests to be identifiable back to the client that made the request. * The client name should include the backing implementation as well as the Sync or Async * to identify the transmission type of the request. Client names should only include * alphanumeric characters. Examples of well formed client names include, Apache, for * requests using Apache's http client or NettyNio for Netty's http client. * * @return String containing the name of the client */ default String clientName() { return "UNKNOWN"; } @FunctionalInterface interface Builder<T extends SdkAsyncHttpClient.Builder<T>> extends SdkBuilder<T, SdkAsyncHttpClient> { /** * Create a {@link SdkAsyncHttpClient} with global defaults applied. This is useful for reusing an HTTP client across * multiple services. */ @Override default SdkAsyncHttpClient build() { return buildWithDefaults(AttributeMap.empty()); } /** * Create an {@link SdkAsyncHttpClient} with service specific defaults applied. Applying service defaults is optional * and some options may not be supported by a particular implementation. * * @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in {@link * SdkHttpConfigurationOption}. * @return Created client */ SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults); } }
2,820
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpService.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.async; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Service Provider interface for Async HTTP implementations. The core uses {@link java.util.ServiceLoader} to find appropriate * HTTP implementations on the classpath. HTTP implementations that wish to be discovered by the default HTTP provider chain * should implement this interface and declare that implementation as a service in the * META-INF/service/software.amazon.awssdk.http.async.SdkAsyncHttpService resource. See * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html">Service Loader</a> for more * information. * * <p> * This interface is simply a factory for {@link SdkAsyncHttpClient.Builder}. Implementations must be thread safe. * </p> */ @ThreadSafe @SdkPublicApi public interface SdkAsyncHttpService { /** * @return An {@link SdkAsyncHttpClient.Builder} capable of creating {@link SdkAsyncHttpClient} instances. This factory should * be thread safe. */ SdkAsyncHttpClient.Builder createAsyncHttpClientFactory(); }
2,821
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpResponseHandler.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.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpResponse; /** * Handles asynchronous HTTP responses. */ @SdkPublicApi public interface SdkAsyncHttpResponseHandler { /** * Called when the headers have been received. * * @param headers The headers. */ void onHeaders(SdkHttpResponse headers); /** * Called when the streaming body is ready. * <p> * This method is always called. If the response does not have a body, then the publisher will complete the subscription * without signalling any elements. * * @param stream The streaming body. */ void onStream(Publisher<ByteBuffer> stream); /** * Called when there is an error making the request or receiving the response. If the error is encountered while * streaming the body, then the error is also delivered to the {@link org.reactivestreams.Subscriber}. * * @param error The error. */ void onError(Throwable error); }
2,822
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SimpleSubscriber.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.async; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Simple subscriber that does no backpressure and doesn't care about errors or completion. */ @SdkProtectedApi public class SimpleSubscriber implements Subscriber<ByteBuffer> { private final Consumer<ByteBuffer> consumer; private final AtomicReference<Subscription> subscription = new AtomicReference<>(); public SimpleSubscriber(Consumer<ByteBuffer> consumer) { this.consumer = consumer; } @Override public void onSubscribe(Subscription s) { // As per rule 1.9 we must throw NullPointerException if the subscriber parameter is null if (s == null) { throw new NullPointerException("Subscription MUST NOT be null."); } if (subscription.get() == null) { if (subscription.compareAndSet(null, s)) { s.request(Long.MAX_VALUE); } else { onSubscribe(s); // lost race, retry (will cancel in the else branch below) } } else { try { s.cancel(); // Cancel the additional subscription } catch (final Throwable t) { // Subscription.cancel is not allowed to throw an exception, according to rule 3.15 (new IllegalStateException(s + " violated the Reactive Streams rule 3.15 by throwing an exception from cancel.", t)) .printStackTrace(System.err); } } } @Override public void onNext(ByteBuffer byteBuffer) { // Rule 2.13, null arguments must be failed on eagerly if (byteBuffer == null) { throw new NullPointerException("Element passed to onNext MUST NOT be null."); } consumer.accept(byteBuffer); } @Override public void onError(Throwable t) { if (t == null) { throw new NullPointerException("Throwable passed to onError MUST NOT be null."); } // else, ignore } @Override public void onComplete() { // ignore } }
2,823
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/service-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.servicemetadata.A4bServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AccessAnalyzerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AccountServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AcmPcaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AcmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AirflowServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AmplifyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AmplifybackendServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiDetectiveServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiEcrPublicServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiEcrServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiElasticInferenceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiFleethubIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiMediatailorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiPricingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApigatewayServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppIntegrationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppflowServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApplicationAutoscalingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApplicationinsightsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppmeshServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApprunnerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Appstream2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppsyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AthenaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AuditmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AutoscalingPlansServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AutoscalingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BackupServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BatchServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BraketServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BudgetsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Cloud9ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudcontrolapiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ClouddirectoryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudformationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudfrontServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudhsmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Cloudhsmv2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudsearchServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudtrailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeartifactServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodebuildServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodecommitServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodedeployServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeguruProfilerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeguruReviewerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodepipelineServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarConnectionsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarNotificationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoIdentityServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoIdpServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoSyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComprehendServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComprehendmedicalServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComputeOptimizerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConfigServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConnectparticipantServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ContactLensServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CurServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataJobsIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataMediastoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatabrewServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataexchangeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatapipelineServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatasyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DaxServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DeeplensServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DevicefarmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DevicesIot1clickServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DirectconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DiscoveryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DlmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DocdbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DynamodbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EbsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Ec2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EcsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EdgeSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EksServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticacheServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticbeanstalkServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticfilesystemServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticloadbalancingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticmapreduceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElastictranscoderServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EmailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EmrContainersServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EnhancedS3ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EntitlementMarketplaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EventsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ExecuteApiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FinspaceApiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FinspaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FirehoseServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ForecastServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ForecastqueryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FrauddetectorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FsxServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GameliftServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GlacierServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GlueServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GrafanaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GreengrassServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GroundstationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GuarddutyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HealthServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HealthlakeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HoneycodeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IamServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IdentityChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IdentitystoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ImportexportServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.InspectorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotdeviceadvisorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IoteventsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IoteventsdataServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotsecuredtunnelingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotsitewiseServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotthingsgraphServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotwirelessServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IvsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KafkaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KafkaconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KendraServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisvideoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LakeformationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LambdaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LicenseManagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LightsailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LogsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutequipmentServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutmetricsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutvisionServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MachinelearningServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Macie2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MacieServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ManagedblockchainServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MarketplacecommerceanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediaconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediaconvertServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MedialiveServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediapackageServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediapackageVodServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediastoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MemorydbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MessagingChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MeteringMarketplaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MghServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MgnServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MigrationhubStrategyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MobileanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ModelsLexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ModelsV2LexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MonitoringServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MqServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MturkRequesterServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NeptuneServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NetworkFirewallServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NetworkmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NimbleServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OidcServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OperatorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OpsworksCmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OpsworksServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OrganizationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OutpostsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PersonalizeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PinpointServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PinpointSmsVoiceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PollyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PortalSsoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ProfileServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ProjectsIot1clickServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.QldbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.QuicksightServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RamServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RdsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RdsdataserviceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RedshiftServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RekognitionServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ResourceGroupsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RobomakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53RecoveryControlConfigServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53domainsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53resolverServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeLexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeV2LexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.S3ControlServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.S3OutpostsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SavingsplansServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SchemasServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SdbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SecretsmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SecurityhubServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServerlessrepoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicecatalogAppregistryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicecatalogServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicediscoveryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicequotasServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SessionQldbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ShieldServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SignerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SmsVoicePinpointServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnowDeviceManagementServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnowballServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SqsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SsmIncidentsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SsmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StatesServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StoragegatewayServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StreamsDynamodbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SupportServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SwfServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SyntheticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TaggingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TextractServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TimestreamQueryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TimestreamWriteServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranscribeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranscribestreamingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TransferServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranslateServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ValkyrieServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.VoiceidServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WafRegionalServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WafServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WisdomServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkdocsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkmailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkspacesServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.XrayServiceMetadata; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedServiceMetadataProvider implements ServiceMetadataProvider { private static final Map<String, ServiceMetadata> SERVICE_METADATA = ImmutableMap.<String, ServiceMetadata> builder() .put("a4b", new A4bServiceMetadata()).put("access-analyzer", new AccessAnalyzerServiceMetadata()) .put("account", new AccountServiceMetadata()).put("acm", new AcmServiceMetadata()) .put("acm-pca", new AcmPcaServiceMetadata()).put("airflow", new AirflowServiceMetadata()) .put("amplify", new AmplifyServiceMetadata()).put("amplifybackend", new AmplifybackendServiceMetadata()) .put("api.detective", new ApiDetectiveServiceMetadata()).put("api.ecr", new ApiEcrServiceMetadata()) .put("api.ecr-public", new ApiEcrPublicServiceMetadata()) .put("api.elastic-inference", new ApiElasticInferenceServiceMetadata()) .put("api.fleethub.iot", new ApiFleethubIotServiceMetadata()) .put("api.mediatailor", new ApiMediatailorServiceMetadata()).put("api.pricing", new ApiPricingServiceMetadata()) .put("api.sagemaker", new ApiSagemakerServiceMetadata()).put("apigateway", new ApigatewayServiceMetadata()) .put("app-integrations", new AppIntegrationsServiceMetadata()).put("appflow", new AppflowServiceMetadata()) .put("application-autoscaling", new ApplicationAutoscalingServiceMetadata()) .put("applicationinsights", new ApplicationinsightsServiceMetadata()).put("appmesh", new AppmeshServiceMetadata()) .put("apprunner", new ApprunnerServiceMetadata()).put("appstream2", new Appstream2ServiceMetadata()) .put("appsync", new AppsyncServiceMetadata()).put("aps", new ApsServiceMetadata()) .put("athena", new AthenaServiceMetadata()).put("auditmanager", new AuditmanagerServiceMetadata()) .put("autoscaling", new AutoscalingServiceMetadata()).put("autoscaling-plans", new AutoscalingPlansServiceMetadata()) .put("backup", new BackupServiceMetadata()).put("batch", new BatchServiceMetadata()) .put("braket", new BraketServiceMetadata()).put("budgets", new BudgetsServiceMetadata()) .put("ce", new CeServiceMetadata()).put("chime", new ChimeServiceMetadata()) .put("cloud9", new Cloud9ServiceMetadata()).put("cloudcontrolapi", new CloudcontrolapiServiceMetadata()) .put("clouddirectory", new ClouddirectoryServiceMetadata()) .put("cloudformation", new CloudformationServiceMetadata()).put("cloudfront", new CloudfrontServiceMetadata()) .put("cloudhsm", new CloudhsmServiceMetadata()).put("cloudhsmv2", new Cloudhsmv2ServiceMetadata()) .put("cloudsearch", new CloudsearchServiceMetadata()).put("cloudtrail", new CloudtrailServiceMetadata()) .put("codeartifact", new CodeartifactServiceMetadata()).put("codebuild", new CodebuildServiceMetadata()) .put("codecommit", new CodecommitServiceMetadata()).put("codedeploy", new CodedeployServiceMetadata()) .put("codeguru-profiler", new CodeguruProfilerServiceMetadata()) .put("codeguru-reviewer", new CodeguruReviewerServiceMetadata()) .put("codepipeline", new CodepipelineServiceMetadata()).put("codestar", new CodestarServiceMetadata()) .put("codestar-connections", new CodestarConnectionsServiceMetadata()) .put("codestar-notifications", new CodestarNotificationsServiceMetadata()) .put("cognito-identity", new CognitoIdentityServiceMetadata()).put("cognito-idp", new CognitoIdpServiceMetadata()) .put("cognito-sync", new CognitoSyncServiceMetadata()).put("comprehend", new ComprehendServiceMetadata()) .put("comprehendmedical", new ComprehendmedicalServiceMetadata()) .put("compute-optimizer", new ComputeOptimizerServiceMetadata()).put("config", new ConfigServiceMetadata()) .put("connect", new ConnectServiceMetadata()).put("connectparticipant", new ConnectparticipantServiceMetadata()) .put("contact-lens", new ContactLensServiceMetadata()).put("cur", new CurServiceMetadata()) .put("data.iot", new DataIotServiceMetadata()).put("data.jobs.iot", new DataJobsIotServiceMetadata()) .put("data.mediastore", new DataMediastoreServiceMetadata()).put("databrew", new DatabrewServiceMetadata()) .put("dataexchange", new DataexchangeServiceMetadata()).put("datapipeline", new DatapipelineServiceMetadata()) .put("datasync", new DatasyncServiceMetadata()).put("dax", new DaxServiceMetadata()) .put("deeplens", new DeeplensServiceMetadata()).put("devicefarm", new DevicefarmServiceMetadata()) .put("devices.iot1click", new DevicesIot1clickServiceMetadata()) .put("directconnect", new DirectconnectServiceMetadata()).put("discovery", new DiscoveryServiceMetadata()) .put("dlm", new DlmServiceMetadata()).put("dms", new DmsServiceMetadata()).put("docdb", new DocdbServiceMetadata()) .put("ds", new DsServiceMetadata()).put("dynamodb", new DynamodbServiceMetadata()) .put("ebs", new EbsServiceMetadata()).put("ec2", new Ec2ServiceMetadata()).put("ecs", new EcsServiceMetadata()) .put("edge.sagemaker", new EdgeSagemakerServiceMetadata()).put("eks", new EksServiceMetadata()) .put("elasticache", new ElasticacheServiceMetadata()).put("elasticbeanstalk", new ElasticbeanstalkServiceMetadata()) .put("elasticfilesystem", new ElasticfilesystemServiceMetadata()) .put("elasticloadbalancing", new ElasticloadbalancingServiceMetadata()) .put("elasticmapreduce", new ElasticmapreduceServiceMetadata()) .put("elastictranscoder", new ElastictranscoderServiceMetadata()).put("email", new EmailServiceMetadata()) .put("emr-containers", new EmrContainersServiceMetadata()) .put("entitlement.marketplace", new EntitlementMarketplaceServiceMetadata()).put("es", new EsServiceMetadata()) .put("events", new EventsServiceMetadata()).put("execute-api", new ExecuteApiServiceMetadata()) .put("finspace", new FinspaceServiceMetadata()).put("finspace-api", new FinspaceApiServiceMetadata()) .put("firehose", new FirehoseServiceMetadata()).put("fms", new FmsServiceMetadata()) .put("forecast", new ForecastServiceMetadata()).put("forecastquery", new ForecastqueryServiceMetadata()) .put("frauddetector", new FrauddetectorServiceMetadata()).put("fsx", new FsxServiceMetadata()) .put("gamelift", new GameliftServiceMetadata()).put("glacier", new GlacierServiceMetadata()) .put("glue", new GlueServiceMetadata()).put("grafana", new GrafanaServiceMetadata()) .put("greengrass", new GreengrassServiceMetadata()).put("groundstation", new GroundstationServiceMetadata()) .put("guardduty", new GuarddutyServiceMetadata()).put("health", new HealthServiceMetadata()) .put("healthlake", new HealthlakeServiceMetadata()).put("honeycode", new HoneycodeServiceMetadata()) .put("iam", new IamServiceMetadata()).put("identity-chime", new IdentityChimeServiceMetadata()) .put("identitystore", new IdentitystoreServiceMetadata()).put("importexport", new ImportexportServiceMetadata()) .put("inspector", new InspectorServiceMetadata()).put("iot", new IotServiceMetadata()) .put("iotanalytics", new IotanalyticsServiceMetadata()) .put("iotdeviceadvisor", new IotdeviceadvisorServiceMetadata()).put("iotevents", new IoteventsServiceMetadata()) .put("ioteventsdata", new IoteventsdataServiceMetadata()) .put("iotsecuredtunneling", new IotsecuredtunnelingServiceMetadata()) .put("iotsitewise", new IotsitewiseServiceMetadata()).put("iotthingsgraph", new IotthingsgraphServiceMetadata()) .put("iotwireless", new IotwirelessServiceMetadata()).put("ivs", new IvsServiceMetadata()) .put("kafka", new KafkaServiceMetadata()).put("kafkaconnect", new KafkaconnectServiceMetadata()) .put("kendra", new KendraServiceMetadata()).put("kinesis", new KinesisServiceMetadata()) .put("kinesisanalytics", new KinesisanalyticsServiceMetadata()) .put("kinesisvideo", new KinesisvideoServiceMetadata()).put("kms", new KmsServiceMetadata()) .put("lakeformation", new LakeformationServiceMetadata()).put("lambda", new LambdaServiceMetadata()) .put("license-manager", new LicenseManagerServiceMetadata()).put("lightsail", new LightsailServiceMetadata()) .put("logs", new LogsServiceMetadata()).put("lookoutequipment", new LookoutequipmentServiceMetadata()) .put("lookoutmetrics", new LookoutmetricsServiceMetadata()).put("lookoutvision", new LookoutvisionServiceMetadata()) .put("machinelearning", new MachinelearningServiceMetadata()).put("macie", new MacieServiceMetadata()) .put("macie2", new Macie2ServiceMetadata()).put("managedblockchain", new ManagedblockchainServiceMetadata()) .put("marketplacecommerceanalytics", new MarketplacecommerceanalyticsServiceMetadata()) .put("mediaconnect", new MediaconnectServiceMetadata()).put("mediaconvert", new MediaconvertServiceMetadata()) .put("medialive", new MedialiveServiceMetadata()).put("mediapackage", new MediapackageServiceMetadata()) .put("mediapackage-vod", new MediapackageVodServiceMetadata()).put("mediastore", new MediastoreServiceMetadata()) .put("memorydb", new MemorydbServiceMetadata()).put("messaging-chime", new MessagingChimeServiceMetadata()) .put("metering.marketplace", new MeteringMarketplaceServiceMetadata()).put("mgh", new MghServiceMetadata()) .put("mgn", new MgnServiceMetadata()).put("migrationhub-strategy", new MigrationhubStrategyServiceMetadata()) .put("mobileanalytics", new MobileanalyticsServiceMetadata()).put("models-v2-lex", new ModelsV2LexServiceMetadata()) .put("models.lex", new ModelsLexServiceMetadata()).put("monitoring", new MonitoringServiceMetadata()) .put("mq", new MqServiceMetadata()).put("mturk-requester", new MturkRequesterServiceMetadata()) .put("neptune", new NeptuneServiceMetadata()).put("network-firewall", new NetworkFirewallServiceMetadata()) .put("networkmanager", new NetworkmanagerServiceMetadata()).put("nimble", new NimbleServiceMetadata()) .put("oidc", new OidcServiceMetadata()).put("opsworks", new OpsworksServiceMetadata()) .put("opsworks-cm", new OpsworksCmServiceMetadata()).put("organizations", new OrganizationsServiceMetadata()) .put("outposts", new OutpostsServiceMetadata()).put("personalize", new PersonalizeServiceMetadata()) .put("pi", new PiServiceMetadata()).put("pinpoint", new PinpointServiceMetadata()) .put("pinpoint-sms-voice", new PinpointSmsVoiceServiceMetadata()).put("polly", new PollyServiceMetadata()) .put("portal.sso", new PortalSsoServiceMetadata()).put("profile", new ProfileServiceMetadata()) .put("projects.iot1click", new ProjectsIot1clickServiceMetadata()).put("qldb", new QldbServiceMetadata()) .put("quicksight", new QuicksightServiceMetadata()).put("ram", new RamServiceMetadata()) .put("rds", new RdsServiceMetadata()).put("rdsdataservice", new RdsdataserviceServiceMetadata()) .put("redshift", new RedshiftServiceMetadata()).put("rekognition", new RekognitionServiceMetadata()) .put("resource-groups", new ResourceGroupsServiceMetadata()).put("robomaker", new RobomakerServiceMetadata()) .put("route53", new Route53ServiceMetadata()) .put("route53-recovery-control-config", new Route53RecoveryControlConfigServiceMetadata()) .put("route53domains", new Route53domainsServiceMetadata()) .put("route53resolver", new Route53resolverServiceMetadata()) .put("runtime-v2-lex", new RuntimeV2LexServiceMetadata()).put("runtime.lex", new RuntimeLexServiceMetadata()) .put("runtime.sagemaker", new RuntimeSagemakerServiceMetadata()).put("s3", new EnhancedS3ServiceMetadata()) .put("s3-control", new S3ControlServiceMetadata()).put("s3-outposts", new S3OutpostsServiceMetadata()) .put("savingsplans", new SavingsplansServiceMetadata()).put("schemas", new SchemasServiceMetadata()) .put("sdb", new SdbServiceMetadata()).put("secretsmanager", new SecretsmanagerServiceMetadata()) .put("securityhub", new SecurityhubServiceMetadata()).put("serverlessrepo", new ServerlessrepoServiceMetadata()) .put("servicecatalog", new ServicecatalogServiceMetadata()) .put("servicecatalog-appregistry", new ServicecatalogAppregistryServiceMetadata()) .put("servicediscovery", new ServicediscoveryServiceMetadata()) .put("servicequotas", new ServicequotasServiceMetadata()).put("session.qldb", new SessionQldbServiceMetadata()) .put("shield", new ShieldServiceMetadata()).put("signer", new SignerServiceMetadata()) .put("sms", new SmsServiceMetadata()).put("sms-voice.pinpoint", new SmsVoicePinpointServiceMetadata()) .put("snow-device-management", new SnowDeviceManagementServiceMetadata()) .put("snowball", new SnowballServiceMetadata()).put("sns", new SnsServiceMetadata()) .put("sqs", new SqsServiceMetadata()).put("ssm", new SsmServiceMetadata()) .put("ssm-incidents", new SsmIncidentsServiceMetadata()).put("states", new StatesServiceMetadata()) .put("storagegateway", new StoragegatewayServiceMetadata()) .put("streams.dynamodb", new StreamsDynamodbServiceMetadata()).put("sts", new StsServiceMetadata()) .put("support", new SupportServiceMetadata()).put("swf", new SwfServiceMetadata()) .put("synthetics", new SyntheticsServiceMetadata()).put("tagging", new TaggingServiceMetadata()) .put("textract", new TextractServiceMetadata()).put("timestream.query", new TimestreamQueryServiceMetadata()) .put("timestream.write", new TimestreamWriteServiceMetadata()).put("transcribe", new TranscribeServiceMetadata()) .put("transcribestreaming", new TranscribestreamingServiceMetadata()).put("transfer", new TransferServiceMetadata()) .put("translate", new TranslateServiceMetadata()).put("valkyrie", new ValkyrieServiceMetadata()) .put("voiceid", new VoiceidServiceMetadata()).put("waf", new WafServiceMetadata()) .put("waf-regional", new WafRegionalServiceMetadata()).put("wisdom", new WisdomServiceMetadata()) .put("workdocs", new WorkdocsServiceMetadata()).put("workmail", new WorkmailServiceMetadata()) .put("workspaces", new WorkspacesServiceMetadata()).put("xray", new XrayServiceMetadata()) .put("operator", new OperatorServiceMetadata()).build(); public ServiceMetadata serviceMetadata(String endpointPrefix) { return SERVICE_METADATA.get(endpointPrefix); } }
2,824
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/partition-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.partitionmetadata.AwsCnPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsIsoBPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsIsoPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsUsGovPartitionMetadata; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedPartitionMetadataProvider implements PartitionMetadataProvider { private static final Map<String, PartitionMetadata> PARTITION_METADATA = ImmutableMap.<String, PartitionMetadata> builder() .put("aws", new AwsPartitionMetadata()).put("aws-cn", new AwsCnPartitionMetadata()) .put("aws-us-gov", new AwsUsGovPartitionMetadata()).put("aws-iso", new AwsIsoPartitionMetadata()) .put("aws-iso-b", new AwsIsoBPartitionMetadata()).build(); public PartitionMetadata partitionMetadata(String partition) { return PARTITION_METADATA.get(partition); } public PartitionMetadata partitionMetadata(Region region) { return PARTITION_METADATA.values().stream().filter(p -> region.id().matches(p.regionRegex())).findFirst() .orElse(new AwsPartitionMetadata()); } }
2,825
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/sts-service-metadata.java
package software.amazon.awssdk.regions.servicemetadata; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServicePartitionMetadata; import software.amazon.awssdk.regions.internal.DefaultServicePartitionMetadata; import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class StsServiceMetadata implements ServiceMetadata { private static final String ENDPOINT_PREFIX = "sts"; private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(Region.of("af-south-1"), Region.of("ap-east-1"), Region.of("ap-northeast-1"), Region.of("ap-northeast-2"), Region.of("ap-northeast-3"), Region.of("ap-south-1"), Region.of("ap-southeast-1"), Region.of("ap-southeast-2"), Region.of("aws-global"), Region.of("ca-central-1"), Region.of("eu-central-1"), Region.of("eu-north-1"), Region.of("eu-south-1"), Region.of("eu-west-1"), Region.of("eu-west-2"), Region.of("eu-west-3"), Region.of("me-south-1"), Region.of("sa-east-1"), Region.of("us-east-1"), Region.of("us-east-1-fips"), Region.of("us-east-2"), Region.of("us-east-2-fips"), Region.of("us-west-1"), Region.of("us-west-1-fips"), Region.of("us-west-2"), Region.of("us-west-2-fips"), Region.of("cn-north-1"), Region.of("cn-northwest-1"), Region.of("us-gov-east-1"), Region.of("us-gov-east-1-fips"), Region.of("us-gov-west-1"), Region.of("us-gov-west-1-fips"), Region.of("us-iso-east-1"), Region.of("us-iso-west-1"), Region.of("us-isob-east-1"))); private static final List<ServicePartitionMetadata> PARTITIONS = Collections.unmodifiableList(Arrays.asList( new DefaultServicePartitionMetadata("aws", null), new DefaultServicePartitionMetadata("aws-cn", null), new DefaultServicePartitionMetadata("aws-us-gov", null), new DefaultServicePartitionMetadata("aws-iso", null), new DefaultServicePartitionMetadata("aws-iso-b", null))); private static final Map<ServiceEndpointKey, String> SIGNING_REGIONS_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1-fips")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2-fips")).build(), "us-east-2") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1-fips")).build(), "us-west-1") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2-fips")).build(), "us-west-2") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1-fips")).build(), "us-gov-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1-fips")).build(), "us-gov-west-1").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> SIGNING_REGIONS_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> DNS_SUFFIXES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder().build(); private static final Map<Pair<String, PartitionEndpointKey>, String> DNS_SUFFIXES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> HOSTNAMES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "sts.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1-fips")).build(), "sts-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2-fips")).build(), "sts-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1-fips")).build(), "sts-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2-fips")).build(), "sts-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("fips")).build(), "sts.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1-fips")).build(), "sts.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("fips")).build(), "sts.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1-fips")).build(), "sts.us-gov-west-1.amazonaws.com") .build(); private static final Map<Pair<String, PartitionEndpointKey>, String> HOSTNAMES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build()), "sts.{region}.{dnsSuffix}").build(); @Override public List<Region> regions() { return REGIONS; } @Override public List<ServicePartitionMetadata> servicePartitions() { return PARTITIONS; } @Override public URI endpointFor(ServiceEndpointKey key) { return ServiceMetadataUtils.endpointFor(ServiceMetadataUtils.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ENDPOINT_PREFIX, key.region().id(), ServiceMetadataUtils.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION)); } @Override public Region signingRegion(ServiceEndpointKey key) { return ServiceMetadataUtils.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION); } }
2,826
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/partition-metadata.java
package software.amazon.awssdk.regions.partitionmetadata; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.utils.ImmutableMap; @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class AwsPartitionMetadata implements PartitionMetadata { private static final Map<PartitionEndpointKey, String> DNS_SUFFIXES = ImmutableMap.<PartitionEndpointKey, String> builder() .put(PartitionEndpointKey.builder().build(), "amazonaws.com") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build(), "amazonaws.com") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "api.aws") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build(), "api.aws").build(); private static final Map<PartitionEndpointKey, String> HOSTNAMES = ImmutableMap .<PartitionEndpointKey, String> builder() .put(PartitionEndpointKey.builder().build(), "{service}.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build(), "{service}-fips.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "{service}-fips.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build(), "{service}.{region}.{dnsSuffix}") .build(); private static final String ID = "aws"; private static final String NAME = "AWS Standard"; private static final String REGION_REGEX = "^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$"; @Override public String id() { return ID; } @Override public String name() { return NAME; } @Override public String regionRegex() { return REGION_REGEX; } @Override public String dnsSuffix(PartitionEndpointKey key) { return DNS_SUFFIXES.get(key); } @Override public String hostname(PartitionEndpointKey key) { return HOSTNAMES.get(key); } }
2,827
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/regions.java
package software.amazon.awssdk.regions; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An Amazon Web Services region that hosts a set of Amazon services. * <p> * An instance of this class can be retrieved by referencing one of the static constants defined in this class (eg. * {@link Region#US_EAST_1}) or by using the {@link Region#of(String)} method if the region you want is not included in * this release of the SDK. * </p> * <p> * Each AWS region corresponds to a separate geographical location where a set of Amazon services is deployed. These * regions (except for the special {@link #AWS_GLOBAL} and {@link #AWS_CN_GLOBAL} regions) are separate from each other, * with their own set of resources. This means a resource created in one region (eg. an SQS queue) is not available in * another region. * </p> * <p> * To programmatically determine whether a particular service is deployed to a region, you can use the * {@code serviceMetadata} method on the service's client interface. Additional metadata about a region can be * discovered using {@link RegionMetadata#of(Region)}. * </p> * <p> * The {@link Region#id()} will be used as the signing region for all requests to AWS services unless an explicit region * override is available in {@link RegionMetadata}. This id will also be used to construct the endpoint for accessing a * service unless an explicit endpoint is available for that region in {@link RegionMetadata}. * </p> */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class Region { public static final Region AP_SOUTH_1 = Region.of("ap-south-1"); public static final Region EU_SOUTH_1 = Region.of("eu-south-1"); public static final Region US_GOV_EAST_1 = Region.of("us-gov-east-1"); public static final Region CA_CENTRAL_1 = Region.of("ca-central-1"); public static final Region EU_CENTRAL_1 = Region.of("eu-central-1"); public static final Region US_ISO_WEST_1 = Region.of("us-iso-west-1"); public static final Region US_WEST_1 = Region.of("us-west-1"); public static final Region US_WEST_2 = Region.of("us-west-2"); public static final Region AF_SOUTH_1 = Region.of("af-south-1"); public static final Region EU_NORTH_1 = Region.of("eu-north-1"); public static final Region EU_WEST_3 = Region.of("eu-west-3"); public static final Region EU_WEST_2 = Region.of("eu-west-2"); public static final Region EU_WEST_1 = Region.of("eu-west-1"); public static final Region AP_NORTHEAST_3 = Region.of("ap-northeast-3"); public static final Region AP_NORTHEAST_2 = Region.of("ap-northeast-2"); public static final Region AP_NORTHEAST_1 = Region.of("ap-northeast-1"); public static final Region ME_SOUTH_1 = Region.of("me-south-1"); public static final Region SA_EAST_1 = Region.of("sa-east-1"); public static final Region AP_EAST_1 = Region.of("ap-east-1"); public static final Region CN_NORTH_1 = Region.of("cn-north-1"); public static final Region US_GOV_WEST_1 = Region.of("us-gov-west-1"); public static final Region AP_SOUTHEAST_1 = Region.of("ap-southeast-1"); public static final Region AP_SOUTHEAST_2 = Region.of("ap-southeast-2"); public static final Region US_ISO_EAST_1 = Region.of("us-iso-east-1"); public static final Region US_EAST_1 = Region.of("us-east-1"); public static final Region US_EAST_2 = Region.of("us-east-2"); public static final Region CN_NORTHWEST_1 = Region.of("cn-northwest-1"); public static final Region US_ISOB_EAST_1 = Region.of("us-isob-east-1"); public static final Region AWS_GLOBAL = Region.of("aws-global", true); public static final Region AWS_CN_GLOBAL = Region.of("aws-cn-global", true); public static final Region AWS_US_GOV_GLOBAL = Region.of("aws-us-gov-global", true); public static final Region AWS_ISO_GLOBAL = Region.of("aws-iso-global", true); public static final Region AWS_ISO_B_GLOBAL = Region.of("aws-iso-b-global", true); private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(AP_SOUTH_1, EU_SOUTH_1, US_GOV_EAST_1, CA_CENTRAL_1, EU_CENTRAL_1, US_ISO_WEST_1, US_WEST_1, US_WEST_2, AF_SOUTH_1, EU_NORTH_1, EU_WEST_3, EU_WEST_2, EU_WEST_1, AP_NORTHEAST_3, AP_NORTHEAST_2, AP_NORTHEAST_1, ME_SOUTH_1, SA_EAST_1, AP_EAST_1, CN_NORTH_1, US_GOV_WEST_1, AP_SOUTHEAST_1, AP_SOUTHEAST_2, US_ISO_EAST_1, US_EAST_1, US_EAST_2, CN_NORTHWEST_1, US_ISOB_EAST_1, AWS_GLOBAL, AWS_CN_GLOBAL, AWS_US_GOV_GLOBAL, AWS_ISO_GLOBAL, AWS_ISO_B_GLOBAL)); private final boolean isGlobalRegion; private final String id; private Region(String id, boolean isGlobalRegion) { this.id = id; this.isGlobalRegion = isGlobalRegion; } public static Region of(String value) { return of(value, false); } private static Region of(String value, boolean isGlobalRegion) { Validate.paramNotBlank(value, "region"); String urlEncodedValue = SdkHttpUtils.urlEncode(value); return RegionCache.put(urlEncodedValue, isGlobalRegion); } public static List<Region> regions() { return REGIONS; } public String id() { return this.id; } public RegionMetadata metadata() { return RegionMetadata.of(this); } public boolean isGlobalRegion() { return isGlobalRegion; } @Override public String toString() { return id; } private static class RegionCache { private static final ConcurrentHashMap<String, Region> VALUES = new ConcurrentHashMap<>(); private RegionCache() { } private static Region put(String value, boolean isGlobalRegion) { return VALUES.computeIfAbsent(value, v -> new Region(value, isGlobalRegion)); } } }
2,828
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/region-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.regionmetadata.AfSouth1; import software.amazon.awssdk.regions.regionmetadata.ApEast1; import software.amazon.awssdk.regions.regionmetadata.ApNortheast1; import software.amazon.awssdk.regions.regionmetadata.ApNortheast2; import software.amazon.awssdk.regions.regionmetadata.ApNortheast3; import software.amazon.awssdk.regions.regionmetadata.ApSouth1; import software.amazon.awssdk.regions.regionmetadata.ApSoutheast1; import software.amazon.awssdk.regions.regionmetadata.ApSoutheast2; import software.amazon.awssdk.regions.regionmetadata.CaCentral1; import software.amazon.awssdk.regions.regionmetadata.CnNorth1; import software.amazon.awssdk.regions.regionmetadata.CnNorthwest1; import software.amazon.awssdk.regions.regionmetadata.EuCentral1; import software.amazon.awssdk.regions.regionmetadata.EuNorth1; import software.amazon.awssdk.regions.regionmetadata.EuSouth1; import software.amazon.awssdk.regions.regionmetadata.EuWest1; import software.amazon.awssdk.regions.regionmetadata.EuWest2; import software.amazon.awssdk.regions.regionmetadata.EuWest3; import software.amazon.awssdk.regions.regionmetadata.MeSouth1; import software.amazon.awssdk.regions.regionmetadata.SaEast1; import software.amazon.awssdk.regions.regionmetadata.UsEast1; import software.amazon.awssdk.regions.regionmetadata.UsEast2; import software.amazon.awssdk.regions.regionmetadata.UsGovEast1; import software.amazon.awssdk.regions.regionmetadata.UsGovWest1; import software.amazon.awssdk.regions.regionmetadata.UsIsoEast1; import software.amazon.awssdk.regions.regionmetadata.UsIsoWest1; import software.amazon.awssdk.regions.regionmetadata.UsIsobEast1; import software.amazon.awssdk.regions.regionmetadata.UsWest1; import software.amazon.awssdk.regions.regionmetadata.UsWest2; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedRegionMetadataProvider implements RegionMetadataProvider { private static final Map<Region, RegionMetadata> REGION_METADATA = ImmutableMap.<Region, RegionMetadata> builder() .put(Region.AF_SOUTH_1, new AfSouth1()).put(Region.AP_EAST_1, new ApEast1()) .put(Region.AP_NORTHEAST_1, new ApNortheast1()).put(Region.AP_NORTHEAST_2, new ApNortheast2()) .put(Region.AP_NORTHEAST_3, new ApNortheast3()).put(Region.AP_SOUTH_1, new ApSouth1()) .put(Region.AP_SOUTHEAST_1, new ApSoutheast1()).put(Region.AP_SOUTHEAST_2, new ApSoutheast2()) .put(Region.CA_CENTRAL_1, new CaCentral1()).put(Region.EU_CENTRAL_1, new EuCentral1()) .put(Region.EU_NORTH_1, new EuNorth1()).put(Region.EU_SOUTH_1, new EuSouth1()).put(Region.EU_WEST_1, new EuWest1()) .put(Region.EU_WEST_2, new EuWest2()).put(Region.EU_WEST_3, new EuWest3()).put(Region.ME_SOUTH_1, new MeSouth1()) .put(Region.SA_EAST_1, new SaEast1()).put(Region.US_EAST_1, new UsEast1()).put(Region.US_EAST_2, new UsEast2()) .put(Region.US_WEST_1, new UsWest1()).put(Region.US_WEST_2, new UsWest2()).put(Region.CN_NORTH_1, new CnNorth1()) .put(Region.CN_NORTHWEST_1, new CnNorthwest1()).put(Region.US_GOV_EAST_1, new UsGovEast1()) .put(Region.US_GOV_WEST_1, new UsGovWest1()).put(Region.US_ISO_EAST_1, new UsIsoEast1()) .put(Region.US_ISO_WEST_1, new UsIsoWest1()).put(Region.US_ISOB_EAST_1, new UsIsobEast1()).build(); public RegionMetadata regionMetadata(Region region) { return REGION_METADATA.get(region); } }
2,829
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/endpoint-tags.java
package software.amazon.awssdk.regions; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A tag applied to endpoints to specify that they're to be used in certain contexts. For example, FIPS tags are applied * to endpoints discussed here: https://aws.amazon.com/compliance/fips/ and DUALSTACK tags are applied to endpoints that * can return IPv6 addresses. */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class EndpointTag { public static final EndpointTag DUALSTACK = EndpointTag.of("dualstack"); public static final EndpointTag FIPS = EndpointTag.of("fips"); private static final List<EndpointTag> ENDPOINT_TAGS = Collections.unmodifiableList(Arrays.asList(DUALSTACK, FIPS)); private final String id; private EndpointTag(String id) { this.id = id; } public static EndpointTag of(String id) { return EndpointTagCache.put(id); } public static List<EndpointTag> endpointTags() { return ENDPOINT_TAGS; } public String id() { return this.id; } @Override public String toString() { return id; } private static class EndpointTagCache { private static final ConcurrentHashMap<String, EndpointTag> IDS = new ConcurrentHashMap<>(); private EndpointTagCache() { } private static EndpointTag put(String id) { return IDS.computeIfAbsent(id, EndpointTag::new); } } }
2,830
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/s3-service-metadata.java
package software.amazon.awssdk.regions.servicemetadata; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServicePartitionMetadata; import software.amazon.awssdk.regions.internal.DefaultServicePartitionMetadata; import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class S3ServiceMetadata implements ServiceMetadata { private static final String ENDPOINT_PREFIX = "s3"; private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(Region.of("af-south-1"), Region.of("ap-east-1"), Region.of("ap-northeast-1"), Region.of("ap-northeast-2"), Region.of("ap-northeast-3"), Region.of("ap-south-1"), Region.of("ap-southeast-1"), Region.of("ap-southeast-2"), Region.of("aws-global"), Region.of("ca-central-1"), Region.of("eu-central-1"), Region.of("eu-north-1"), Region.of("eu-south-1"), Region.of("eu-west-1"), Region.of("eu-west-2"), Region.of("eu-west-3"), Region.of("fips-ca-central-1"), Region.of("fips-us-east-1"), Region.of("fips-us-east-2"), Region.of("fips-us-west-1"), Region.of("fips-us-west-2"), Region.of("me-south-1"), Region.of("sa-east-1"), Region.of("us-east-1"), Region.of("us-east-2"), Region.of("us-west-1"), Region.of("us-west-2"), Region.of("cn-north-1"), Region.of("cn-northwest-1"), Region.of("fips-us-gov-east-1"), Region.of("fips-us-gov-west-1"), Region.of("us-gov-east-1"), Region.of("us-gov-west-1"), Region.of("us-iso-east-1"), Region.of("us-iso-west-1"), Region.of("us-isob-east-1"))); private static final List<ServicePartitionMetadata> PARTITIONS = Collections.unmodifiableList(Arrays.asList( new DefaultServicePartitionMetadata("aws", null), new DefaultServicePartitionMetadata("aws-cn", null), new DefaultServicePartitionMetadata("aws-us-gov", null), new DefaultServicePartitionMetadata("aws-iso", null), new DefaultServicePartitionMetadata("aws-iso-b", null))); private static final Map<ServiceEndpointKey, String> SIGNING_REGIONS_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-ca-central-1")).build(), "ca-central-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-1")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-2")).build(), "us-east-2") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-1")).build(), "us-west-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-2")).build(), "us-west-2") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-east-1")).build(), "us-gov-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-west-1")).build(), "us-gov-west-1").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> SIGNING_REGIONS_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> DNS_SUFFIXES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder().build(); private static final Map<Pair<String, PartitionEndpointKey>, String> DNS_SUFFIXES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build()), "amazonaws.com") .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com") .put(Pair.of("aws-cn", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com.cn") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")) .build()), "amazonaws.com") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com") .build(); private static final Map<ServiceEndpointKey, String> HOSTNAMES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("af-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.af-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-1")).build(), "s3.ap-northeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-3")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-1")).build(), "s3.ap-southeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-southeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-2")).build(), "s3.ap-southeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-southeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "s3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-central-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-north-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-north-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-1")).build(), "s3.eu-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-3")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-ca-central-1")).build(), "s3-fips.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-1")).build(), "s3-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-2")).build(), "s3-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-1")).build(), "s3-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-2")).build(), "s3-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("me-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.me-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("sa-east-1")).build(), "s3.sa-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("sa-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.sa-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).build(), "s3.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).build(), "s3.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).build(), "s3.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("cn-north-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.cn-north-1.amazonaws.com.cn") .put(ServiceEndpointKey.builder().region(Region.of("cn-northwest-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.cn-northwest-1.amazonaws.com.cn") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-east-1")).build(), "s3-fips.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-west-1")).build(), "s3-fips.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).build(), "s3.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).build(), "s3.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-gov-west-1.amazonaws.com").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> HOSTNAMES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build()), "{service}-fips.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-cn", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")) .build()), "{service}-fips.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}").build(); @Override public List<Region> regions() { return REGIONS; } @Override public List<ServicePartitionMetadata> servicePartitions() { return PARTITIONS; } @Override public URI endpointFor(ServiceEndpointKey key) { return ServiceMetadataUtils.endpointFor(ServiceMetadataUtils.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ENDPOINT_PREFIX, key.region().id(), ServiceMetadataUtils.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION)); } @Override public Region signingRegion(ServiceEndpointKey key) { return ServiceMetadataUtils.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION); } }
2,831
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/us-east-1.java
package software.amazon.awssdk.regions.regionmetadata; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.RegionMetadata; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class UsEast1 implements RegionMetadata { private static final String ID = "us-east-1"; private static final String DOMAIN = "amazonaws.com"; private static final String DESCRIPTION = "US East (N. Virginia)"; private static final String PARTITION_ID = "aws"; @Override public String id() { return ID; } @Override public String domain() { return DOMAIN; } @Override public String description() { return DESCRIPTION; } @Override public PartitionMetadata partition() { return PartitionMetadata.of(PARTITION_ID); } }
2,832
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/defaultsmode/defaults-mode-configuration.java
package software.amazon.awssdk.defaultsmode; import java.time.Duration; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.utils.AttributeMap; /** * Contains a collection of default configuration options for each DefaultsMode */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultsModeConfiguration { private static final AttributeMap STANDARD_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap STANDARD_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(2000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(2000)).build(); private static final AttributeMap MOBILE_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.ADAPTIVE) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap MOBILE_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(10000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(11000)).build(); private static final AttributeMap CROSS_REGION_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap CROSS_REGION_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(2800)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(2800)).build(); private static final AttributeMap IN_REGION_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap IN_REGION_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(1000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(1000)).build(); private static final AttributeMap LEGACY_DEFAULTS = AttributeMap.empty(); private static final AttributeMap LEGACY_HTTP_DEFAULTS = AttributeMap.empty(); private static final Map<DefaultsMode, AttributeMap> DEFAULT_CONFIG_BY_MODE = new EnumMap<>(DefaultsMode.class); private static final Map<DefaultsMode, AttributeMap> DEFAULT_HTTP_CONFIG_BY_MODE = new EnumMap<>(DefaultsMode.class); static { DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.STANDARD, STANDARD_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.MOBILE, MOBILE_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.CROSS_REGION, CROSS_REGION_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.IN_REGION, IN_REGION_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.LEGACY, LEGACY_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.STANDARD, STANDARD_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.MOBILE, MOBILE_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.CROSS_REGION, CROSS_REGION_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.IN_REGION, IN_REGION_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.LEGACY, LEGACY_HTTP_DEFAULTS); } private DefaultsModeConfiguration() { } /** * Return the default config options for a given defaults mode */ public static AttributeMap defaultConfig(DefaultsMode mode) { return DEFAULT_CONFIG_BY_MODE.getOrDefault(mode, AttributeMap.empty()); } /** * Return the default config options for a given defaults mode */ public static AttributeMap defaultHttpConfig(DefaultsMode mode) { return DEFAULT_HTTP_CONFIG_BY_MODE.getOrDefault(mode, AttributeMap.empty()); } }
2,833
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/defaultsmode/defaults-mode.java
package software.amazon.awssdk.defaultsmode; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.EnumUtils; /** * A defaults mode determines how certain default configuration options are resolved in the SDK. Based on the provided * mode, the SDK will vend sensible default values tailored to the mode for the following settings: * <ul> * <li>retryMode: PLACEHOLDER</li> * <li>s3UsEast1RegionalEndpoints: PLACEHOLDER</li> * <li>connectTimeoutInMillis: PLACEHOLDER</li> * <li>tlsNegotiationTimeoutInMillis: PLACEHOLDER</li> * </ul> * <p> * All options above can be configured by users, and the overridden value will take precedence. * <p> * <b>Note:</b> for any mode other than {@link #LEGACY}, the vended default values might change as best practices may * evolve. As a result, it is encouraged to perform testing when upgrading the SDK if you are using a mode other than * {@link #LEGACY} * <p> * While the {@link #LEGACY} defaults mode is specific to Java, other modes are standardized across all of the AWS SDKs * </p> * <p> * The defaults mode can be configured: * <ol> * <li>Directly on a client via {@code AwsClientBuilder.Builder#defaultsMode(DefaultsMode)}.</li> * <li>On a configuration profile via the "defaults_mode" profile file property.</li> * <li>Globally via the "aws.defaultsMode" system property.</li> * <li>Globally via the "AWS_DEFAULTS_MODE" environment variable.</li> * </ol> */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public enum DefaultsMode { /** * PLACEHOLDER */ LEGACY("legacy"), /** * PLACEHOLDER */ STANDARD("standard"), /** * PLACEHOLDER */ MOBILE("mobile"), /** * PLACEHOLDER */ CROSS_REGION("cross-region"), /** * PLACEHOLDER */ IN_REGION("in-region"), /** * PLACEHOLDER */ AUTO("auto"); private static final Map<String, DefaultsMode> VALUE_MAP = EnumUtils.uniqueIndex(DefaultsMode.class, DefaultsMode::toString); private final String value; private DefaultsMode(String value) { this.value = value; } /** * Use this in place of valueOf to convert the raw string returned by the service into the enum value. * * @param value * real value * @return DefaultsMode corresponding to the value */ public static DefaultsMode fromValue(String value) { Validate.paramNotNull(value, "value"); if (!VALUE_MAP.containsKey(value)) { throw new IllegalArgumentException("The provided value is not a valid defaults mode " + value); } return VALUE_MAP.get(value); } @Override public String toString() { return String.valueOf(value); } }
2,834
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/PoetMatchers.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.codegen.lite; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace; import com.squareup.javapoet.JavaFile; import java.io.IOException; import java.io.InputStream; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.ComparisonFailure; import software.amazon.awssdk.codegen.lite.emitters.CodeTransformer; import software.amazon.awssdk.codegen.lite.emitters.JavaCodeFormatter; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; public final class PoetMatchers { private static final CodeTransformer processor = CodeTransformer.chain(new CopyrightRemover(), new JavaCodeFormatter()); public static Matcher<PoetClass> generatesTo(String expectedTestFile) { return new TypeSafeMatcher<PoetClass>() { @Override protected boolean matchesSafely(PoetClass spec) { String expectedClass = getExpectedClass(spec, expectedTestFile); String actualClass = generateClass(spec); try { assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass)); } catch (AssertionError e) { //Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand //IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass); } return true; } @Override public void describeTo(Description description) { //Since we bubble an exception this will never actually get called } }; } private static String getExpectedClass(PoetClass spec, String testFile) { try { InputStream resource = spec.getClass().getResourceAsStream(testFile); Validate.notNull(resource, "Failed to load test file: " + testFile); return processor.apply(IoUtils.toUtf8String(resource)); } catch (IOException e) { throw new RuntimeException(e); } } private static String generateClass(PoetClass spec) { StringBuilder output = new StringBuilder(); try { buildJavaFile(spec).writeTo(output); } catch (IOException e) { throw new RuntimeException("Failed to generate class", e); } return processor.apply(output.toString()); } private static class CopyrightRemover implements CodeTransformer { @Override public String apply(String input) { return input.substring(input.indexOf("package")); } } private static JavaFile buildJavaFile(PoetClass spec) { return JavaFile.builder(spec.className().packageName(), spec.poetClass()).skipJavaLangImports(true).build(); } }
2,835
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/regions/RegionGenerationTest.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.codegen.lite.regions; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.lite.PoetMatchers.generatesTo; import java.io.File; import java.nio.file.Paths; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; public class RegionGenerationTest { private static final String ENDPOINTS = "/software/amazon/awssdk/codegen/lite/test-endpoints.json"; private static final String SERVICE_METADATA_BASE = "software.amazon.awssdk.regions.servicemetadata"; private static final String REGION_METADATA_BASE = "software.amazon.awssdk.regions.regionmetadata"; private static final String PARTITION_METADATA_BASE = "software.amazon.awssdk.regions.partitionmetadata"; private static final String REGION_BASE = "software.amazon.awssdk.regions"; private File endpoints; private Partitions partitions; @BeforeEach public void before() throws Exception { this.endpoints = Paths.get(getClass().getResource(ENDPOINTS).toURI()).toFile(); this.partitions = RegionMetadataLoader.build(endpoints); } @Test public void regionClass() { RegionGenerator regions = new RegionGenerator(partitions, REGION_BASE); assertThat(regions, generatesTo("regions.java")); } @Test public void regionMetadataClass() { Partition partition = partitions.getPartitions().get(0); RegionMetadataGenerator metadataGenerator = new RegionMetadataGenerator(partition, "us-east-1", "US East (N. Virginia)", REGION_METADATA_BASE, REGION_BASE); assertThat(metadataGenerator, generatesTo("us-east-1.java")); } @Test public void regionMetadataProviderClass() { RegionMetadataProviderGenerator providerGenerator = new RegionMetadataProviderGenerator(partitions, REGION_METADATA_BASE, REGION_BASE); assertThat(providerGenerator, generatesTo("region-metadata-provider.java")); } @Test public void serviceMetadataClass() { ServiceMetadataGenerator serviceMetadataGenerator = new ServiceMetadataGenerator(partitions, "s3", SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataGenerator, generatesTo("s3-service-metadata.java")); } @Test public void serviceWithOverriddenPartitionsMetadataClass() { ServiceMetadataGenerator serviceMetadataGenerator = new ServiceMetadataGenerator(partitions, "sts", SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataGenerator, generatesTo("sts-service-metadata.java")); } @Test public void serviceMetadataProviderClass() { ServiceMetadataProviderGenerator serviceMetadataProviderGenerator = new ServiceMetadataProviderGenerator(partitions, SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataProviderGenerator, generatesTo("service-metadata-provider.java")); } @Test public void partitionMetadataClass() { PartitionMetadataGenerator partitionMetadataGenerator = new PartitionMetadataGenerator(partitions.getPartitions().get(0), PARTITION_METADATA_BASE, REGION_BASE); assertThat(partitionMetadataGenerator, generatesTo("partition-metadata.java")); } @Test public void endpointTagClass() { EndpointTagGenerator partitionMetadataGenerator = new EndpointTagGenerator(partitions, REGION_BASE); assertThat(partitionMetadataGenerator, generatesTo("endpoint-tags.java")); } @Test public void partitionMetadataProviderClass() { PartitionMetadataProviderGenerator partitionMetadataProviderGenerator = new PartitionMetadataProviderGenerator(partitions, PARTITION_METADATA_BASE, REGION_BASE); assertThat(partitionMetadataProviderGenerator, generatesTo("partition-metadata-provider.java")); } }
2,836
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/regions/RegionValidationUtilTest.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.codegen.lite.regions; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class RegionValidationUtilTest { private static final String AWS_PARTITION_REGEX = "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$"; private static final String AWS_CN_PARTITION_REGEX = "^cn\\-\\w+\\-\\d+$"; private static final String AWS_GOV_PARTITION_REGEX = "^us\\-gov\\-\\w+\\-\\d+$"; @Test public void usEast1_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-east-1", AWS_PARTITION_REGEX)); } @Test public void usWest2Fips_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-west-2-fips", AWS_PARTITION_REGEX)); } @Test public void fipsUsWest2_AwsPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-west-2", AWS_PARTITION_REGEX)); } @Test public void fips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_PARTITION_REGEX)); } @Test public void prodFips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("cn-north-1", AWS_CN_PARTITION_REGEX)); } @Test public void usEast1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("us-east-1", AWS_CN_PARTITION_REGEX)); } @Test public void usGovWest1_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void usGovWest1Fips_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1-fips", AWS_GOV_PARTITION_REGEX)); } @Test public void fipsUsGovWest1_AwsGovPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void fips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_GOV_PARTITION_REGEX)); } @Test public void prodFips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_GOV_PARTITION_REGEX)); } @Test public void cnNorth1_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_GOV_PARTITION_REGEX)); } @Test public void awsGlobal_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-global", AWS_PARTITION_REGEX)); } @Test public void awsGovGlobal_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-us-gov-global", AWS_GOV_PARTITION_REGEX)); } @Test public void awsCnGlobal_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-cn-global", AWS_CN_PARTITION_REGEX)); } }
2,837
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeGenerationTest.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.codegen.lite.defaultsmode; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.lite.PoetMatchers.generatesTo; import java.io.File; import java.nio.file.Paths; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class DefaultsModeGenerationTest { private static final String DEFAULT_CONFIGURATION = "/software/amazon/awssdk/codegen/lite/test-sdk-default-configuration.json"; private static final String DEFAULTS_MODE_BASE = "software.amazon.awssdk.defaultsmode"; private File file; private DefaultConfiguration defaultConfiguration; @BeforeEach public void before() throws Exception { this.file = Paths.get(getClass().getResource(DEFAULT_CONFIGURATION).toURI()).toFile(); this.defaultConfiguration = DefaultsLoader.load(file); } @Test public void defaultsModeEnum() { DefaultsModeGenerator generator = new DefaultsModeGenerator(DEFAULTS_MODE_BASE, defaultConfiguration); assertThat(generator, generatesTo("defaults-mode.java")); } @Test public void defaultsModeConfigurationClass() { DefaultsModeConfigurationGenerator generator = new DefaultsModeConfigurationGenerator(DEFAULTS_MODE_BASE, DEFAULTS_MODE_BASE, defaultConfiguration); assertThat(generator, generatesTo("defaults-mode-configuration.java")); } }
2,838
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/Utils.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.codegen.lite; import java.io.Closeable; import java.io.File; import java.io.IOException; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; public final class Utils { private Utils() { } public static String capitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } return name.length() < 2 ? StringUtils.upperCase(name) : StringUtils.upperCase(name.substring(0, 1)) + name.substring(1); } public static File createDirectory(String path) { if (isNullOrEmpty(path)) { throw new IllegalArgumentException( "Invalid path directory. Path directory cannot be null or empty"); } File dir = new File(path); createDirectory(dir); return dir; } public static void createDirectory(File dir) { if (!(dir.exists())) { if (!dir.mkdirs()) { throw new RuntimeException("Not able to create directory. " + dir.getAbsolutePath()); } } } public static File createFile(String dir, String fileName) throws IOException { if (isNullOrEmpty(fileName)) { throw new IllegalArgumentException( "Invalid file name. File name cannot be null or empty"); } createDirectory(dir); File file = new File(dir, fileName); if (!(file.exists())) { if (!(file.createNewFile())) { throw new RuntimeException("Not able to create file . " + file.getAbsolutePath()); } } return file; } public static boolean isNullOrEmpty(String str) { return str == null || str.trim().isEmpty(); } public static void closeQuietly(Closeable closeable) { IoUtils.closeQuietly(closeable, null); } }
2,839
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/PoetClass.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.codegen.lite; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; public interface PoetClass { /** * @return The actual class specification generated from a <code>PoetSpec.builder()...</code> implementation */ TypeSpec poetClass(); ClassName className(); }
2,840
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/CodeGenerator.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.codegen.lite; import static software.amazon.awssdk.codegen.lite.Utils.closeQuietly; import com.squareup.javapoet.JavaFile; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.time.ZonedDateTime; import software.amazon.awssdk.codegen.lite.emitters.CodeWriter; import software.amazon.awssdk.utils.IoUtils; public final class CodeGenerator { private final Writer writer; private final PoetClass poetClass; public CodeGenerator(String outputDirectory, PoetClass poetClass) { this.writer = new CodeWriter(outputDirectory, poetClass.className().simpleName()); this.poetClass = poetClass; } public void generate() { try { writer.write(loadDefaultFileHeader() + "\n"); JavaFile.builder(poetClass.className().packageName(), poetClass.poetClass()) .skipJavaLangImports(true) .build() .writeTo(writer); writer.flush(); } catch (IOException e) { throw new RuntimeException(String.format("Error creating class %s", poetClass.className().simpleName()), e); } finally { closeQuietly(writer); } } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/lite/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } }
2,841
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionValidationUtil.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.codegen.lite.regions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public final class RegionValidationUtil { private static final Set<String> DEPRECATED_REGIONS_ALLOWSLIST = new HashSet<>(); private static final String FIPS_SUFFIX = "-fips"; private static final String FIPS_PREFIX = "fips-"; static { try (InputStream allowListStream = RegionValidationUtil.class.getResourceAsStream("/software/amazon/awssdk/codegen/lite" + "/DeprecatedRegionsAllowlist.txt")) { Validate.notNull(allowListStream, "Failed to load deprecated regions allowlist."); try (BufferedReader br = new BufferedReader(new InputStreamReader(allowListStream, StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { DEPRECATED_REGIONS_ALLOWSLIST.add(StringUtils.trim(line)); } } } catch (IOException e) { throw new UncheckedIOException(e); } } private RegionValidationUtil() { } /** * Determines if a given region string is a "valid" AWS region. * * The region string must either match the partition regex, end with fips * and match the partition regex with that included, or include the word "global". * * @param regex - Regex for regions in a given partition. * @param region - Region string being checked. * @return true if the region string should be included as a region. */ public static boolean validRegion(String region, String regex) { return matchesRegex(region, regex) || matchesRegexFipsSuffix(region, regex) || matchesRegexFipsPrefix(region, regex) || isGlobal(region); } public static boolean validEndpoint(String region, Endpoint endpoint) { boolean invalidEndpoint = Boolean.TRUE.equals(endpoint.getDeprecated()) && !DEPRECATED_REGIONS_ALLOWSLIST.contains(region); return !invalidEndpoint; } private static boolean matchesRegex(String region, String regex) { return region.matches(regex); } private static boolean matchesRegexFipsSuffix(String region, String regex) { return region.replace(FIPS_SUFFIX, "").matches(regex); } private static boolean matchesRegexFipsPrefix(String region, String regex) { return region.replace(FIPS_PREFIX, "").matches(regex); } private static boolean isGlobal(String region) { return region.contains("global"); } }
2,842
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/ServiceMetadataProviderGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class ServiceMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public ServiceMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfServiceMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ClassName.get(regionBasePackage, "ServiceMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "ServiceMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfServiceMetadata, "SERVICE_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regions(partitions)) .build()) .addMethod(getter()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedServiceMetadataProvider"); } private CodeBlock regions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<String, ServiceMetadata>builder()", ImmutableMap.class); Set<String> seenServices = new HashSet<>(); partitions.getPartitions() .forEach(p -> p.getServices() .keySet() .forEach(s -> { if (!seenServices.contains(s)) { builder.add(".put($S, new $T())", s, serviceMetadataClass(s)); seenServices.add(s); } })); return builder.add(".build()").build(); } private ClassName serviceMetadataClass(String service) { if ("s3".equals(service)) { // This class contains extra logic for detecting the regional endpoint flag return ClassName.get(basePackage, "EnhancedS3ServiceMetadata"); } String sanitizedServiceName = service.replace(".", "-"); return ClassName.get(basePackage, Stream.of(sanitizedServiceName.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "ServiceMetadata"); } private MethodSpec getter() { return MethodSpec.methodBuilder("serviceMetadata") .addModifiers(PUBLIC) .addParameter(String.class, "endpointPrefix") .returns(ClassName.get(regionBasePackage, "ServiceMetadata")) .addStatement("return $L.get($L)", "SERVICE_METADATA", "endpointPrefix") .build(); } }
2,843
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/ServiceMetadataGenerator.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.codegen.lite.regions; import static java.util.Collections.emptyList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.codegen.lite.regions.model.Service; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.Validate; public class ServiceMetadataGenerator implements PoetClass { private final Partitions partitions; private final String serviceEndpointPrefix; private final String basePackage; private final String regionBasePackage; public ServiceMetadataGenerator(Partitions partitions, String serviceEndpointPrefix, String basePackage, String regionBasePackage) { this.partitions = partitions; this.serviceEndpointPrefix = serviceEndpointPrefix; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; removeBadRegions(); } private void removeBadRegions() { partitions.getPartitions().forEach(partition -> { partition.getServices().values().forEach(service -> { Iterator<Map.Entry<String, Endpoint>> endpointIterator = service.getEndpoints().entrySet().iterator(); while (endpointIterator.hasNext()) { Map.Entry<String, Endpoint> entry = endpointIterator.next(); String endpointName = entry.getKey(); Endpoint endpoint = entry.getValue(); if (!RegionValidationUtil.validRegion(endpointName, partition.getRegionRegex()) || !RegionValidationUtil.validEndpoint(endpointName, endpoint)) { endpointIterator.remove(); } } }); }); } @Override public TypeSpec poetClass() { TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "Region")); TypeName mapByServiceEndpointKey = ParameterizedTypeName.get(ClassName.get(Map.class), serviceEndpointKeyClass(), ClassName.get(String.class)); TypeName mapByPair = ParameterizedTypeName.get(ClassName.get(Map.class), byPartitionKeyClass(), ClassName.get(String.class)); TypeName listOfServicePartitionMetadata = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "ServicePartitionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addSuperinterface(ClassName.get(regionBasePackage, "ServiceMetadata")) .addField(FieldSpec.builder(String.class, "ENDPOINT_PREFIX") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", serviceEndpointPrefix) .build()) .addField(FieldSpec.builder(listOfRegions, "REGIONS") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regionsField(partitions)) .build()) .addField(FieldSpec.builder(listOfServicePartitionMetadata, "PARTITIONS") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(servicePartitions(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "SIGNING_REGIONS_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(signingRegionsByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "SIGNING_REGIONS_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(signingRegionsByPartition(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "DNS_SUFFIXES_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixesByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "DNS_SUFFIXES_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixesByPartition(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "HOSTNAMES_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnamesByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "HOSTNAMES_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnamesByPartition(partitions)) .build()) .addMethod(regions()) .addMethod(partitions(listOfServicePartitionMetadata)) .addMethod(endpointFor()) .addMethod(signingRegion()) .build(); } @Override public ClassName className() { String sanitizedServiceName = serviceEndpointPrefix.replace(".", "-"); return ClassName.get(basePackage, Stream.of(sanitizedServiceName.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "ServiceMetadata"); } private CodeBlock signingRegionsByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { if (endpoint.getCredentialScope() != null && endpoint.getCredentialScope().getRegion() != null) { builder.add(".put(") .add(serviceEndpointKey(region, emptyList())) .add(", $S)\n", endpoint.getCredentialScope().getRegion()); endpoint.getVariants().forEach(variant -> { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", endpoint.getCredentialScope().getRegion()); }); } }); }); return builder.add(".build()").build(); } private CodeBlock signingRegionsByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { Endpoint partitionDefaults = service.getDefaults(); if (partitionDefaults != null && partitionDefaults.getCredentialScope() != null && partitionDefaults.getCredentialScope().getRegion() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(emptyList())) .add("), $S)\n", partitionDefaults.getCredentialScope().getRegion()); partitionDefaults.getVariants().forEach(variant -> { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", partitionDefaults.getCredentialScope().getRegion()); }); } }); return builder.add(".build()").build(); } private CodeBlock dnsSuffixesByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { endpoint.getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", variant.getDnsSuffix()); } }); }); }); return builder.add(".build()").build(); } private CodeBlock dnsSuffixesByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { if (service.getDefaults() != null) { service.getDefaults().getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", variant.getDnsSuffix()); } }); } }); return builder.add(".build()").build(); } private CodeBlock hostnamesByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { if (endpoint.getHostname() != null) { builder.add(".put(") .add(serviceEndpointKey(region, emptyList())) .add(", $S)\n", endpoint.getHostname()); } endpoint.getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", variant.getHostname()); } }); }); }); return builder.add(".build()").build(); } private CodeBlock hostnamesByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { if (service.getDefaults() != null) { if (service.getDefaults().getHostname() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(emptyList())) .add(", $S)\n", service.getDefaults().getHostname()); } service.getDefaults().getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", variant.getHostname()); } }); } }); return builder.add(".build()").build(); } private CodeBlock serviceEndpointKey(String region, Collection<String> tags) { Validate.paramNotBlank(region, "region"); CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", serviceEndpointKeyClass()) .add(".region($T.of($S))", regionClass(), region); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private CodeBlock partitionEndpointKey(Collection<String> tags) { CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", partitionEndpointKeyClass()); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private CodeBlock regionsField(Partitions partitions) { ClassName regionClass = ClassName.get(regionBasePackage, "Region"); CodeBlock.Builder builder = CodeBlock.builder().add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class); ArrayList<String> regions = new ArrayList<>(); partitions.getPartitions() .stream() .filter(p -> p.getServices().containsKey(serviceEndpointPrefix)) .forEach(p -> regions.addAll(p.getServices().get(serviceEndpointPrefix).getEndpoints().keySet())); for (int i = 0; i < regions.size(); i++) { builder.add("$T.of($S)", regionClass, regions.get(i)); if (i != regions.size() - 1) { builder.add(","); } } return builder.add("))").build(); } private CodeBlock servicePartitions(Partitions partitions) { return CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class) .add(commaSeparatedServicePartitions(partitions)) .add("))") .build(); } private CodeBlock commaSeparatedServicePartitions(Partitions partitions) { ClassName defaultServicePartitionMetadata = ClassName.get(regionBasePackage + ".internal", "DefaultServicePartitionMetadata"); return partitions.getPartitions() .stream() .filter(p -> p.getServices().containsKey(serviceEndpointPrefix)) .map(p -> CodeBlock.of("new $T($S, $L)", defaultServicePartitionMetadata, p.getPartition(), globalRegion(p))) .collect(CodeBlock.joining(",")); } private CodeBlock globalRegion(Partition partition) { ClassName region = ClassName.get(regionBasePackage, "Region"); Service service = partition.getServices().get(this.serviceEndpointPrefix); boolean hasGlobalRegionForPartition = service.isRegionalized() != null && !service.isRegionalized() && service.isPartitionWideEndpointAvailable(); String globalRegionForPartition = hasGlobalRegionForPartition ? service.getPartitionEndpoint() : null; return globalRegionForPartition == null ? CodeBlock.of("null") : CodeBlock.of("$T.of($S)", region, globalRegionForPartition); } private MethodSpec regions() { TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "Region")); return MethodSpec.methodBuilder("regions") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(listOfRegions) .addStatement("return $L", "REGIONS") .build(); } private MethodSpec endpointFor() { return MethodSpec.methodBuilder("endpointFor") .addModifiers(Modifier.PUBLIC) .addParameter(serviceEndpointKeyClass(), "key") .addAnnotation(Override.class) .returns(URI.class) .addCode("return $T.endpointFor(", serviceMetadataUtilsClass()) .addCode("$T.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ", serviceMetadataUtilsClass()) .addCode("ENDPOINT_PREFIX, ") .addCode("key.region().id(), ") .addCode("$T.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION));", serviceMetadataUtilsClass()) .build(); } private MethodSpec signingRegion() { return MethodSpec.methodBuilder("signingRegion") .addModifiers(Modifier.PUBLIC) .addParameter(serviceEndpointKeyClass(), "key") .addAnnotation(Override.class) .returns(ClassName.get(regionBasePackage, "Region")) .addStatement("return $T.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION)", serviceMetadataUtilsClass()) .build(); } private MethodSpec partitions(TypeName listOfServicePartitionMetadata) { return MethodSpec.methodBuilder("servicePartitions") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(listOfServicePartitionMetadata) .addStatement("return $L", "PARTITIONS") .build(); } private Map<Partition, Service> getServiceData(Partitions partitions) { Map<Partition, Service> serviceData = new TreeMap<>(Comparator.comparing(Partition::getPartition)); partitions.getPartitions() .forEach(p -> p.getServices() .entrySet() .stream() .filter(s -> s.getKey().equalsIgnoreCase(serviceEndpointPrefix)) .forEach(s -> serviceData.put(p, s.getValue()))); return serviceData; } private ClassName serviceEndpointKeyClass() { return ClassName.get(regionBasePackage, "ServiceEndpointKey"); } private ClassName partitionEndpointKeyClass() { return ClassName.get(regionBasePackage, "PartitionEndpointKey"); } private ClassName regionClass() { return ClassName.get(regionBasePackage, "Region"); } private ClassName endpointTagClass() { return ClassName.get(regionBasePackage, "EndpointTag"); } private TypeName byPartitionKeyClass() { return ParameterizedTypeName.get(ClassName.get(Pair.class), ClassName.get(String.class), partitionEndpointKeyClass()); } private ClassName serviceMetadataUtilsClass() { return ClassName.get(regionBasePackage + ".internal.util", "ServiceMetadataUtils"); } }
2,844
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; public class RegionGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; public RegionGenerator(Partitions partitions, String basePackage) { this.partitions = partitions; this.basePackage = basePackage; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(String.class, "id") .addParameter(boolean.class, "isGlobalRegion") .addStatement("this.id = id") .addStatement("this.isGlobalRegion = isGlobalRegion") .build()); regions(builder); builder.addField(FieldSpec.builder(boolean.class, "isGlobalRegion") .addModifiers(FINAL, PRIVATE) .build()) .addField(FieldSpec.builder(String.class, "id") .addModifiers(FINAL, PRIVATE) .build()) .addMethod(regionOf()) .addMethod(regionOfGlobal()) .addMethod(regionsGetter()) .addMethod(id()) .addMethod(metadata()) .addMethod(isGlobalRegion()) .addMethod(regionToString()); return builder.addType(cache()).build(); } private void regions(TypeSpec.Builder builder) { Set<String> regions = partitions.getPartitions() .stream() .flatMap(p -> p.getRegions().keySet().stream()) .collect(Collectors.toSet()); CodeBlock.Builder regionsArray = CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class); String regionsCodeBlock = regions.stream().map(r -> { builder.addField(FieldSpec.builder(className(), regionName(r)) .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S)", className(), r) .build()); return regionName(r); }).collect(Collectors.joining(", ")); addGlobalRegions(builder); regionsArray.add(regionsCodeBlock + ", ") .add("AWS_GLOBAL, ") .add("AWS_CN_GLOBAL, ") .add("AWS_US_GOV_GLOBAL, ") .add("AWS_ISO_GLOBAL, ") .add("AWS_ISO_B_GLOBAL"); regionsArray.add("))"); TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), className()); builder.addField(FieldSpec.builder(listOfRegions, "REGIONS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer(regionsArray.build()).build()); } private void addGlobalRegions(TypeSpec.Builder builder) { builder.addField(FieldSpec.builder(className(), "AWS_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-global") .build()) .addField(FieldSpec.builder(className(), "AWS_CN_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-cn-global") .build()) .addField(FieldSpec.builder(className(), "AWS_US_GOV_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-us-gov-global") .build()) .addField(FieldSpec.builder(className(), "AWS_ISO_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-iso-global") .build()) .addField(FieldSpec.builder(className(), "AWS_ISO_B_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-iso-b-global") .build()); } private String regionName(String region) { return region.replace("-", "_").toUpperCase(Locale.US); } private MethodSpec regionOf() { return MethodSpec.methodBuilder("of") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "value") .returns(className()) .addStatement("return of($L, false)", "value") .build(); } private MethodSpec regionOfGlobal() { return MethodSpec.methodBuilder("of") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "value") .addParameter(boolean.class, "isGlobalRegion") .returns(className()) .addStatement("$T.paramNotBlank($L, $S)", Validate.class, "value", "region") .addStatement("$T $L = $T.urlEncode($L)", String.class, "urlEncodedValue", SdkHttpUtils.class, "value") .addStatement("return $L.put($L, $L)", "RegionCache", "urlEncodedValue", "isGlobalRegion") .build(); } private MethodSpec id() { return MethodSpec.methodBuilder("id") .addModifiers(PUBLIC) .returns(String.class) .addStatement("return this.id") .build(); } private MethodSpec metadata() { ClassName regionMetadataClass = ClassName.get("software.amazon.awssdk.regions", "RegionMetadata"); return MethodSpec.methodBuilder("metadata") .addModifiers(PUBLIC) .returns(regionMetadataClass) .addStatement("return $T.of(this)", regionMetadataClass) .build(); } private MethodSpec regionsGetter() { return MethodSpec.methodBuilder("regions") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(List.class), className())) .addStatement("return $L", "REGIONS") .build(); } private MethodSpec isGlobalRegion() { return MethodSpec.methodBuilder("isGlobalRegion") .addModifiers(PUBLIC) .returns(boolean.class) .addStatement("return $L", "isGlobalRegion") .build(); } private MethodSpec regionToString() { return MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addStatement("return $L", "id") .build(); } private TypeSpec cache() { ParameterizedTypeName mapOfStringRegion = ParameterizedTypeName.get(ClassName.get(ConcurrentHashMap.class), ClassName.get(String.class), className()); return TypeSpec.classBuilder("RegionCache") .addModifiers(PRIVATE, STATIC) .addField(FieldSpec.builder(mapOfStringRegion, "VALUES") .addModifiers(PRIVATE, STATIC, FINAL) .initializer("new $T<>()", ConcurrentHashMap.class) .build()) .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()) .addMethod(MethodSpec.methodBuilder("put") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "value") .addParameter(boolean.class, "isGlobalRegion") .returns(className()) .addStatement("return $L.computeIfAbsent(value, v -> new $T(value, isGlobalRegion))", "VALUES", className()) .build()) .build(); } private CodeBlock documentation() { return CodeBlock.builder() .add("An Amazon Web Services region that hosts a set of Amazon services.") .add(System.lineSeparator()) .add("<p>An instance of this class can be retrieved by referencing one of the static constants defined in" + " this class (eg. {@link Region#US_EAST_1}) or by using the {@link Region#of(String)} method if " + "the region you want is not included in this release of the SDK.</p>") .add(System.lineSeparator()) .add("<p>Each AWS region corresponds to a separate geographical location where a set of Amazon services " + "is deployed. These regions (except for the special {@link #AWS_GLOBAL} and {@link #AWS_CN_GLOBAL}" + " regions) are separate from each other, with their own set of resources. This means a resource " + "created in one region (eg. an SQS queue) is not available in another region.</p>") .add(System.lineSeparator()) .add("<p>To programmatically determine whether a particular service is deployed to a region, you can use " + "the {@code serviceMetadata} method on the service's client interface. Additional metadata about " + "a region can be discovered using {@link RegionMetadata#of(Region)}.</p>") .add(System.lineSeparator()) .add("<p>The {@link Region#id()} will be used as the signing region for all requests to AWS services " + "unless an explicit region override is available in {@link RegionMetadata}. This id will also be " + "used to construct the endpoint for accessing a service unless an explicit endpoint is available " + "for that region in {@link RegionMetadata}.</p>") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, "Region"); } }
2,845
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataProviderGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class RegionMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public RegionMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfRegionMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(regionBasePackage, "Region"), ClassName.get(regionBasePackage, "RegionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "RegionMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfRegionMetadata, "REGION_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regions(partitions)) .build()) .addMethod(getter()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedRegionMetadataProvider"); } private CodeBlock regions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<Region, RegionMetadata>builder()", ImmutableMap.class); partitions.getPartitions() .forEach(p -> p.getRegions() .keySet() .forEach(r -> builder.add(".put(Region.$L, new $T())", regionClass(r), regionMetadataClass(r)))); return builder.add(".build()").build(); } private String regionClass(String region) { return region.replace("-", "_").toUpperCase(Locale.US); } private ClassName regionMetadataClass(String region) { return ClassName.get(basePackage, Stream.of(region.split("-")).map(Utils::capitalize).collect(Collectors.joining())); } private MethodSpec getter() { return MethodSpec.methodBuilder("regionMetadata") .addModifiers(PUBLIC) .addParameter(ClassName.get(regionBasePackage, "Region"), "region") .returns(ClassName.get(regionBasePackage, "RegionMetadata")) .addStatement("return $L.get($L)", "REGION_METADATA", "region") .build(); } }
2,846
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partition; public class RegionMetadataGenerator implements PoetClass { private final Partition partition; private final String region; private final String regionDescription; private final String basePackage; private final String regionBasePackage; public RegionMetadataGenerator(Partition partition, String region, String regionDescription, String basePackage, String regionBasePackage) { this.partition = partition; this.region = region; this.regionDescription = regionDescription; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { return TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addSuperinterface(ClassName.get(regionBasePackage, "RegionMetadata")) .addField(staticFinalField("ID", region)) .addField(staticFinalField("DOMAIN", partition.getDnsSuffix())) .addField(staticFinalField("DESCRIPTION", regionDescription)) .addField(staticFinalField("PARTITION_ID", partition.getPartition())) .addMethod(getter("id", "ID")) .addMethod(getter("domain", "DOMAIN")) .addMethod(getter("description", "DESCRIPTION")) .addMethod(partition()) .build(); } private MethodSpec partition() { ClassName regionMetadataClass = ClassName.get("software.amazon.awssdk.regions", "PartitionMetadata"); return MethodSpec.methodBuilder("partition") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(regionMetadataClass) .addStatement("return $T.of(PARTITION_ID)", regionMetadataClass) .build(); } @Override public ClassName className() { return ClassName.get(basePackage, Stream.of(region.split("-")).map(Utils::capitalize).collect(Collectors.joining())); } private FieldSpec staticFinalField(String fieldName, String fieldValue) { return FieldSpec.builder(String.class, fieldName) .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", fieldValue) .build(); } private MethodSpec getter(String getterName, String fieldName) { return MethodSpec.methodBuilder(getterName) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addStatement("return $L", fieldName.toUpperCase(Locale.US)) .build(); } }
2,847
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/PartitionMetadataGenerator.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.codegen.lite.regions; import static java.util.Collections.emptyList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.utils.ImmutableMap; public class PartitionMetadataGenerator implements PoetClass { private final Partition partition; private final String basePackage; private final String regionBasePackage; public PartitionMetadataGenerator(Partition partition, String basePackage, String regionBasePackage) { this.partition = partition; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapByPartitionEndpointKey = ParameterizedTypeName.get(ClassName.get(Map.class), partitionEndpointKeyClass(), ClassName.get(String.class)); return TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "PartitionMetadata")) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addField(FieldSpec.builder(mapByPartitionEndpointKey, "DNS_SUFFIXES") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixes()) .build()) .addField(FieldSpec.builder(mapByPartitionEndpointKey, "HOSTNAMES") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnames()) .build()) .addField(FieldSpec.builder(String.class, "ID") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getPartition()) .build()) .addField(FieldSpec.builder(String.class, "NAME") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getPartitionName()) .build()) .addField(FieldSpec.builder(String.class, "REGION_REGEX") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getRegionRegex()) .build()) .addMethod(getter("id", "ID")) .addMethod(getter("name", "NAME")) .addMethod(getter("regionRegex", "REGION_REGEX")) .addMethod(dnsSuffixGetter()) .addMethod(hostnameGetter()) .build(); } private CodeBlock dnsSuffixes() { CodeBlock.Builder builder = CodeBlock.builder() .add("$T.<$T, $T>builder()", ImmutableMap.class, partitionEndpointKeyClass(), String.class); builder.add(".put(") .add(partitionEndpointKey(emptyList())) .add(", $S)", partition.getDnsSuffix()); if (partition.getDefaults() != null) { partition.getDefaults().getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put(") .add(partitionEndpointKey(variant.getTags())) .add(", $S)", variant.getDnsSuffix()); } }); } return builder.add(".build()").build(); } private CodeBlock hostnames() { CodeBlock.Builder builder = CodeBlock.builder() .add("$T.<$T, $T>builder()", ImmutableMap.class, partitionEndpointKeyClass(), String.class); if (partition.getDefaults() != null) { builder.add(".put(") .add(partitionEndpointKey(emptyList())) .add(", $S)", partition.getDefaults().getHostname()); partition.getDefaults().getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put(") .add(partitionEndpointKey(variant.getTags())) .add(", $S)", variant.getHostname()); } }); } return builder.add(".build()").build(); } private MethodSpec dnsSuffixGetter() { return MethodSpec.methodBuilder("dnsSuffix") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addParameter(partitionEndpointKeyClass(), "key") .addStatement("return DNS_SUFFIXES.get(key)") .build(); } private MethodSpec hostnameGetter() { return MethodSpec.methodBuilder("hostname") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addParameter(partitionEndpointKeyClass(), "key") .addStatement("return HOSTNAMES.get(key)") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, Stream.of(partition.getPartition().split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "PartitionMetadata"); } private MethodSpec getter(String methodName, String field) { return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addStatement("return $L", field) .build(); } private CodeBlock partitionEndpointKey(Collection<String> tags) { CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", partitionEndpointKeyClass()); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private ClassName endpointTagClass() { return ClassName.get(regionBasePackage, "EndpointTag"); } private ClassName partitionEndpointKeyClass() { return ClassName.get(regionBasePackage, "PartitionEndpointKey"); } }
2,848
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/PartitionMetadataProviderGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class PartitionMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public PartitionMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfPartitionMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ClassName.get(regionBasePackage, "PartitionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "PartitionMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfPartitionMetadata, "PARTITION_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(partitions(partitions)) .build()) .addMethod(getter()) .addMethod(partitionMetadata()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedPartitionMetadataProvider"); } private CodeBlock partitions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<String, PartitionMetadata>builder()", ImmutableMap.class); partitions.getPartitions() .forEach(p -> builder.add(".put($S, new $T())", p.getPartition(), partitionMetadataClass(p.getPartition()))); return builder.add(".build()").build(); } private ClassName partitionMetadataClass(String partition) { return ClassName.get(basePackage, Stream.of(partition.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "PartitionMetadata"); } private MethodSpec partitionMetadata() { return MethodSpec.methodBuilder("partitionMetadata") .addModifiers(PUBLIC) .addParameter(ClassName.get(regionBasePackage, "Region"), "region") .returns(ClassName.get(regionBasePackage, "PartitionMetadata")) .addStatement("return $L.values().stream().filter(p -> $L.id().matches(p.regionRegex()))" + ".findFirst().orElse(new $L())", "PARTITION_METADATA", "region", "AwsPartitionMetadata") .build(); } private MethodSpec getter() { return MethodSpec.methodBuilder("partitionMetadata") .addModifiers(PUBLIC) .addParameter(String.class, "partition") .returns(ClassName.get(regionBasePackage, "PartitionMetadata")) .addStatement("return $L.get($L)", "PARTITION_METADATA", "partition") .build(); } }
2,849
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/EndpointTagGenerator.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.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.codegen.lite.regions.model.Service; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public class EndpointTagGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; public EndpointTagGenerator(Partitions partitions, String basePackage) { this.partitions = partitions; this.basePackage = basePackage; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(String.class, "id") .addStatement("this.id = id") .build()); endpointTags(builder); builder.addField(FieldSpec.builder(String.class, "id") .addModifiers(FINAL, PRIVATE) .build()) .addMethod(tagOf()) .addMethod(tagGetter()) .addMethod(id()) .addMethod(tagToString()); return builder.addType(cache()).build(); } private void endpointTags(TypeSpec.Builder builder) { Stream<Endpoint> endpointsFromPartitions = partitions.getPartitions().stream().map(Partition::getDefaults); Stream<Endpoint> endpointsFromServices = partitions.getPartitions().stream() .flatMap(p -> p.getServices().values().stream()) .flatMap(s -> s.getEndpoints().values().stream()); Stream<Endpoint> endpointsFromServiceDefaults = partitions.getPartitions().stream() .flatMap(p -> p.getServices().values().stream()) .map(Service::getDefaults) .filter(Objects::nonNull); Set<String> allTags = Stream.concat(endpointsFromPartitions, Stream.concat(endpointsFromServices, endpointsFromServiceDefaults)) .flatMap(e -> e.getVariants().stream()) .flatMap(v -> v.getTags().stream()) .collect(Collectors.toCollection(TreeSet::new)); // Add each tag as a separate entry in the endpoint tags allTags.forEach(tag -> builder.addField(FieldSpec.builder(className(), enumValueForTagId(tag)) .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S)", className(), tag) .build())); String tagsCodeBlock = allTags.stream() .map(this::enumValueForTagId) .collect(Collectors.joining(", ")); CodeBlock initializer = CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class) .add(tagsCodeBlock) .add("))") .build(); TypeName listOfTags = ParameterizedTypeName.get(ClassName.get(List.class), className()); builder.addField(FieldSpec.builder(listOfTags, "ENDPOINT_TAGS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer(initializer) .build()); } private String enumValueForTagId(String tag) { return Stream.of(CodegenNamingUtils.splitOnWordBoundaries(tag)) .map(StringUtils::upperCase) .collect(Collectors.joining("_")); } private MethodSpec tagOf() { return MethodSpec.methodBuilder("of") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "id") .returns(className()) .addStatement("return EndpointTagCache.put($L)", "id") .build(); } private MethodSpec id() { return MethodSpec.methodBuilder("id") .addModifiers(PUBLIC) .returns(String.class) .addStatement("return this.id") .build(); } private MethodSpec tagGetter() { return MethodSpec.methodBuilder("endpointTags") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(List.class), className())) .addStatement("return $L", "ENDPOINT_TAGS") .build(); } private MethodSpec tagToString() { return MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addStatement("return $L", "id") .build(); } private TypeSpec cache() { ParameterizedTypeName mapOfStringTags = ParameterizedTypeName.get(ClassName.get(ConcurrentHashMap.class), ClassName.get(String.class), className()); return TypeSpec.classBuilder("EndpointTagCache") .addModifiers(PRIVATE, STATIC) .addField(FieldSpec.builder(mapOfStringTags, "IDS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer("new $T<>()", ConcurrentHashMap.class) .build()) .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()) .addMethod(MethodSpec.methodBuilder("put") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "id") .returns(className()) .addStatement("return $L.computeIfAbsent(id, $T::new)", "IDS", className()) .build()) .build(); } private CodeBlock documentation() { return CodeBlock.builder() .add("A tag applied to endpoints to specify that they're to be used in certain contexts. For example, " + "FIPS tags are applied to endpoints discussed here: https://aws.amazon.com/compliance/fips/ and " + "DUALSTACK tags are applied to endpoints that can return IPv6 addresses.") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, "EndpointTag"); } }
2,850
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataLoader.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.codegen.lite.regions; import com.fasterxml.jackson.jr.ob.JSON; import java.io.File; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; /** * Loads all the partition files into memory. */ @SdkInternalApi public final class RegionMetadataLoader { private RegionMetadataLoader() { } public static Partitions build(File path) { return loadPartitionFromStream(path, path.toString()); } private static Partitions loadPartitionFromStream(File stream, String location) { try { return JSON.std.with(JSON.Feature.USE_IS_GETTERS) .beanFrom(Partitions.class, stream); } catch (IOException | RuntimeException e) { throw new RuntimeException("Error while loading partitions file from " + location, e); } } }
2,851
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/EndpointVariant.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class EndpointVariant { private String dnsSuffix; private String hostname; private List<String> tags; public String getDnsSuffix() { return dnsSuffix; } @JsonProperty(value = "dnsSuffix") public void setDnsSuffix(String dnsSuffix) { this.dnsSuffix = dnsSuffix; } public String getHostname() { return hostname; } @JsonProperty(value = "hostname") public void setHostname(String hostname) { this.hostname = hostname; } public List<String> getTags() { return tags; } @JsonProperty(value = "tags") public void setTags(List<String> tags) { this.tags = tags; } }
2,852
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Partitions.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Metadata of all partitions. */ @SdkInternalApi public final class Partitions { /** * the version of json schema for the partition metadata. */ private String version; /** * list of partitions. */ private List<Partition> partitions; public Partitions() { } public Partitions(@JsonProperty(value = "version") String version, @JsonProperty(value = "partitions") List<Partition> partitions) { this.version = Validate.paramNotNull(version, "version"); this.partitions = Validate.paramNotNull(partitions, "version"); } /** * returns the version of the json schema for the partition metadata document. */ public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } /** * returns the list of all partitions loaded from the partition metadata document. */ public List<Partition> getPartitions() { return partitions; } public void setPartitions(List<Partition> partitions) { this.partitions = partitions; } }
2,853
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/PartitionRegion.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Metadata about a region in partition. */ @SdkInternalApi public final class PartitionRegion { /** * description of the region. */ private String description; public PartitionRegion() { } public PartitionRegion(@JsonProperty(value = "description") String description) { this.description = Validate.notNull(description, "Region description"); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
2,854
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/CredentialScope.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.codegen.lite.regions.model; import software.amazon.awssdk.annotations.SdkInternalApi; /** * credential scope associated with an endpoint. */ @SdkInternalApi public final class CredentialScope { /** * region string to be used when signing a request for an endpoint. */ private String region; /** * service name string to be used when signing a request for an endpoint */ private String service; /** * Returns the region string to be used when signing a request for an * endpoint. */ public String getRegion() { return region; } /** * Sets the region string to be used when signing a request for an * endpoint. */ public void setRegion(String region) { this.region = region; } /** * Returns the service name string to be used when signing a request for an * endpoint. */ public String getService() { return service; } /** * Sets the service name string to be used when signing a request for an * endpoint. */ public void setService(String service) { this.service = service; } }
2,855
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Service.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Endpoint configuration for a service in a partition. */ @SdkInternalApi public final class Service { /** * endpoint configuration for every region in a partition. */ private Map<String, Endpoint> endpoints; /** * default endpoint configuration for a service across all regions in the * partition */ private Endpoint defaults; /** * the region name if the service is enabled partition wide. */ private String partitionEndpoint; /** * Returns true if the service is regionalized. */ private Boolean isRegionalized; public Service() { } public Service(@JsonProperty(value = "endpoints") Map<String, Endpoint> endpoints) { this.endpoints = Validate.paramNotNull(endpoints, "endpoints"); } /** * Returns the endpoints configuration for all regions in a partition * that service supports. */ public Map<String, Endpoint> getEndpoints() { return endpoints; } public void setEndpoints(Map<String, Endpoint> endpoints) { this.endpoints = endpoints; } /** * returns the default endpoints configuration for all regions in a * partition. */ public Endpoint getDefaults() { return defaults; } /** * Sets the default endpoints configuration for all regions in a * partition. */ public void setDefaults(Endpoint defaults) { this.defaults = defaults; } /** * returns the region name if the service is enabled partition wide. */ public String getPartitionEndpoint() { return partitionEndpoint; } /** * sets the region name if the service is enabled partition wide. */ @JsonProperty(value = "partitionEndpoint") public void setPartitionEndpoint(String partitionEndpoint) { this.partitionEndpoint = partitionEndpoint; } /** * returns true if the service is regionalized. */ public Boolean isRegionalized() { return isRegionalized; } /** * sets the regionalized property for a service.. */ @JsonProperty(value = "isRegionalized") public void setIsRegionalized(Boolean regionalized) { isRegionalized = regionalized; } /** * A convenient method that returns true if a service has a partition * wide endpoint available. */ public boolean isPartitionWideEndpointAvailable() { return this.partitionEndpoint != null; } }
2,856
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Endpoint.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Endpoint configuration. */ @SdkInternalApi public final class Endpoint implements Cloneable { private static final String HTTP = "http"; private static final String HTTPS = "https"; /** * endpoint string. */ private String hostname; /** * credential scope for the endpoint. */ private CredentialScope credentialScope; /** * supported schemes for the endpoint. */ private List<String> protocols; /** * supported signature versions of the endpoint. */ private List<String> signatureVersions; /** * ssl common name for the endpoint. */ private String sslCommonName; private List<EndpointVariant> variants = new ArrayList<>(); private Boolean deprecated; public Endpoint() { } /** * Merges the given endpoints and returns the merged one. */ public Endpoint merge(Endpoint higher) { if (higher == null) { higher = new Endpoint(); } Endpoint merged = this.clone(); merged.setCredentialScope(higher.getCredentialScope() != null ? higher.getCredentialScope() : merged.getCredentialScope()); merged.setHostname(higher.getHostname() != null ? higher.getHostname() : merged.getHostname()); merged.setSslCommonName(higher.getSslCommonName() != null ? higher.getSslCommonName() : merged.getSslCommonName()); merged.setProtocols(higher.getProtocols() != null ? higher.getProtocols() : merged.getProtocols()); merged.setSignatureVersions(higher.getSignatureVersions() != null ? higher.getSignatureVersions() : merged.getSignatureVersions()); return merged; } /** * returns the endpoint string. */ public String getHostname() { return hostname; } /** * sets the endpoint string. */ @JsonProperty(value = "hostname") public void setHostname(String hostname) { this.hostname = hostname; } /** * returns credential scope for the endpoint. */ public CredentialScope getCredentialScope() { return credentialScope; } /** * sets the credential scope for the endpoint. */ @JsonProperty(value = "credentialScope") public void setCredentialScope(CredentialScope credentialScope) { this.credentialScope = credentialScope; } /** * returns the supported schemes for the endpoint. */ public List<String> getProtocols() { return protocols; } /** * sets the supported schemes for the endpoint. */ public void setProtocols(List<String> protocols) { this.protocols = protocols; } /** * returns the supported signature versions of the endpoint. */ public List<String> getSignatureVersions() { return signatureVersions; } /** * returns the supported signature versions of the endpoint. */ @JsonProperty(value = "signatureVersions") public void setSignatureVersions(List<String> signatureVersions) { this.signatureVersions = signatureVersions; } /** * returns the ssl common name for the endpoint. */ public String getSslCommonName() { return sslCommonName; } /** * sets the ssl common name for the endpoint. */ @JsonProperty(value = "sslCommonName") public void setSslCommonName(String sslCommonName) { this.sslCommonName = sslCommonName; } /** * A convenient method that returns true if the endpoint support HTTPS * scheme. Returns false otherwise. */ public boolean hasHttpsSupport() { return isProtocolSupported(HTTPS); } /** * A convenient method that returns true if the endpoint support HTTP * scheme. Returns false otherwise. */ public boolean hasHttpSupport() { return isProtocolSupported(HTTP); } private boolean isProtocolSupported(String protocol) { return protocols != null && protocols.contains(protocol); } @Override protected Endpoint clone() { try { return (Endpoint) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() even though we're Cloneable!", e); } } public List<EndpointVariant> getVariants() { return variants; } public void setVariants(List<EndpointVariant> variants) { this.variants = variants; } public Boolean getDeprecated() { return deprecated; } public void setDeprecated(Boolean deprecated) { this.deprecated = deprecated; } }
2,857
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Partition.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.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * This class models a AWS partition and contains all metadata about it. */ @SdkInternalApi public final class Partition { /** * The name of the partition. */ private String partition; /** * Supported regions. */ private Map<String, PartitionRegion> regions; /** * Supported services; */ private Map<String, Service> services; /** * description of the partition. */ private String partitionName; /** * dns suffix for the endpoints in the partition. */ private String dnsSuffix; /** * region name regex for regions in the partition. */ private String regionRegex; /** * default endpoint configuration. */ private Endpoint defaults; public Partition() { } public Partition(@JsonProperty(value = "partition") String partition, @JsonProperty(value = "regions") Map<String, PartitionRegion> regions, @JsonProperty(value = "services") Map<String, Service> services) { this.partition = Validate.paramNotNull(partition, "Partition"); this.regions = regions; this.services = services; } /** * Returns the name of the partition. */ public String getPartition() { return partition; } public void setPartition(String partition) { this.partition = partition; } /** * Returns the description of the partition. */ public String getPartitionName() { return partitionName; } /** * Sets the description of the partition. */ public void setPartitionName(String partitionName) { this.partitionName = partitionName; } /** * Returns the dns suffix of the partition. */ public String getDnsSuffix() { return dnsSuffix; } /** * Sets the dns suffix of the partition. */ public void setDnsSuffix(String dnsSuffix) { this.dnsSuffix = dnsSuffix; } /** * Returns the regex for the regions in the partition. */ public String getRegionRegex() { return regionRegex; } /** * Sets the regex for the regions in the partition. */ public void setRegionRegex(String regionRegex) { this.regionRegex = regionRegex; } /** * Returns the default endpoint configuration of the partition. */ public Endpoint getDefaults() { return defaults; } /** * Sets the default endpoint configuration of the partition. */ public void setDefaults(Endpoint defaults) { this.defaults = defaults; } /** * Returns the set of regions associated with the partition. */ public Map<String, PartitionRegion> getRegions() { return regions; } public void setRegions(Map<String, PartitionRegion> regions) { this.regions = regions; } /** * Returns the set of services supported by the partition. */ public Map<String, Service> getServices() { return services; } public void setServices(Map<String, Service> services) { this.services = services; } /** * Returns true if the region is explicitly configured in the partition * or if the region matches the {@link #regionRegex} of the partition. */ public boolean hasRegion(String region) { return regions.containsKey(region) || matchesRegionRegex(region) || hasServiceEndpoint(region); } private boolean matchesRegionRegex(String region) { Pattern p = Pattern.compile(regionRegex); return p.matcher(region).matches(); } @Deprecated private boolean hasServiceEndpoint(String endpoint) { for (Service s : services.values()) { if (s.getEndpoints().containsKey(endpoint)) { return true; } } return false; } }
2,858
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeGenerator.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.codegen.lite.defaultsmode; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.EnumUtils; /** * Generates DefaultsMode enum */ public class DefaultsModeGenerator implements PoetClass { private static final String VALUE = "value"; private static final String VALUE_MAP = "VALUE_MAP"; private final String basePackage; private final DefaultConfiguration configuration; public DefaultsModeGenerator(String basePackage, DefaultConfiguration configuration) { this.basePackage = basePackage; this.configuration = configuration; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.enumBuilder(className()) .addField(valueMapField()) .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL) .addModifiers(PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember(VALUE, "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(fromValueSpec()) .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build()) .addMethod(createConstructor()); builder.addEnumConstant("LEGACY", enumValueTypeSpec("legacy", javaDocForMode("legacy"))); configuration.modeDefaults().keySet().forEach(k -> { String enumKey = sanitizeEnum(k); builder.addEnumConstant(enumKey, enumValueTypeSpec(k, javaDocForMode(k))); }); builder.addEnumConstant("AUTO", enumValueTypeSpec("auto", javaDocForMode("auto"))); return builder.build(); } @Override public ClassName className() { return ClassName.get(basePackage, "DefaultsMode"); } private TypeSpec enumValueTypeSpec(String value, String documentation) { return TypeSpec.anonymousClassBuilder("$S", value) .addJavadoc(documentation) .build(); } private FieldSpec valueMapField() { ParameterizedTypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), className()); return FieldSpec.builder(mapType, VALUE_MAP) .addModifiers(PRIVATE, STATIC, FINAL) .initializer("$1T.uniqueIndex($2T.class, $2T::toString)", EnumUtils.class, className()) .build(); } private String sanitizeEnum(String str) { return str.replace('-', '_').toUpperCase(Locale.US); } private String javaDocForMode(String mode) { return configuration.modesDocumentation().getOrDefault(mode, ""); } private CodeBlock documentation() { CodeBlock.Builder builder = CodeBlock.builder() .add("A defaults mode determines how certain default configuration options are " + "resolved in " + "the SDK. " + "Based on the provided " + "mode, the SDK will vend sensible default values tailored to the mode for " + "the following settings:") .add(System.lineSeparator()); builder.add("<ul>"); configuration.configurationDocumentation().forEach((k, v) -> { builder.add("<li>" + k + ": " + v + "</li>"); }); builder.add("</ul>").add(System.lineSeparator()); builder.add("<p>All options above can be configured by users, and the overridden value will take precedence.") .add("<p><b>Note:</b> for any mode other than {@link #LEGACY}, the vended default values might change " + "as best practices may evolve. As a result, it is encouraged to perform testing when upgrading the SDK if" + " you are using a mode other than {@link #LEGACY}") .add(System.lineSeparator()); return builder.add("<p>While the {@link #LEGACY} defaults mode is specific to Java, other modes are " + "standardized across " + "all of the AWS SDKs</p>") .add(System.lineSeparator()) .add("<p>The defaults mode can be configured:") .add(System.lineSeparator()) .add("<ol>") .add("<li>Directly on a client via {@code AwsClientBuilder.Builder#defaultsMode" + "(DefaultsMode)}.</li>") .add(System.lineSeparator()) .add("<li>On a configuration profile via the \"defaults_mode\" profile file property.</li>") .add(System.lineSeparator()) .add("<li>Globally via the \"aws.defaultsMode\" system property.</li>") .add("<li>Globally via the \"AWS_DEFAULTS_MODE\" environment variable.</li>") .add("</ol>") .build(); } private MethodSpec fromValueSpec() { return MethodSpec.methodBuilder("fromValue") .returns(className()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Use this in place of valueOf to convert the raw string returned by the service into the " + "enum value.\n\n" + "@param $N real value\n" + "@return $T corresponding to the value\n", VALUE, className()) .addParameter(String.class, VALUE) .addStatement("$T.paramNotNull(value, $S)", Validate.class, VALUE) .beginControlFlow("if (!VALUE_MAP.containsKey(value))") .addStatement("throw new IllegalArgumentException($S + value)", "The provided value is not a" + " valid " + "defaults mode ") .endControlFlow() .addStatement("return $N.get($N)", VALUE_MAP, VALUE) .build(); } private MethodSpec createConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(String.class, VALUE) .addStatement("this.$1N = $1N", VALUE) .build(); } private static MethodSpec.Builder toStringBuilder() { return MethodSpec.methodBuilder("toString") .returns(String.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class); } }
2,859
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsLoader.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.codegen.lite.defaultsmode; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; import software.amazon.awssdk.utils.Logger; /** * Loads sdk-default-configuration.json into memory. It filters out unsupported configuration options from the file */ @SdkInternalApi public final class DefaultsLoader { private static final Logger log = Logger.loggerFor(DefaultsLoader.class); private static final Set<String> UNSUPPORTED_OPTIONS = new HashSet<>(); static { UNSUPPORTED_OPTIONS.add("stsRegionalEndpoints"); } private DefaultsLoader() { } public static DefaultConfiguration load(File path) { return loadDefaultsFromFile(path); } private static DefaultConfiguration loadDefaultsFromFile(File path) { DefaultConfiguration defaultsResolution = new DefaultConfiguration(); Map<String, Map<String, String>> resolvedDefaults = new HashMap<>(); try (FileInputStream fileInputStream = new FileInputStream(path)) { JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build(); Map<String, JsonNode> sdkDefaultConfiguration = jsonNodeParser.parse(fileInputStream) .asObject(); Map<String, JsonNode> base = sdkDefaultConfiguration.get("base").asObject(); Map<String, JsonNode> modes = sdkDefaultConfiguration.get("modes").asObject(); modes.forEach((mode, modifiers) -> applyModificationToOneMode(resolvedDefaults, base, mode, modifiers)); Map<String, JsonNode> documentation = sdkDefaultConfiguration.get("documentation").asObject(); Map<String, JsonNode> modesDocumentation = documentation.get("modes").asObject(); Map<String, JsonNode> configDocumentation = documentation.get("configuration").asObject(); defaultsResolution.modesDocumentation( modesDocumentation.entrySet() .stream() .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().asString()), Map::putAll)); defaultsResolution.configurationDocumentation( configDocumentation.entrySet() .stream() .filter(e -> !UNSUPPORTED_OPTIONS.contains(e.getKey())) .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().asString()), Map::putAll)); } catch (IOException e) { throw new RuntimeException(e); } defaultsResolution.modeDefaults(resolvedDefaults); return defaultsResolution; } private static void applyModificationToOneConfigurationOption(Map<String, String> resolvedDefaultsForCurrentMode, String option, JsonNode modifier) { String resolvedValue; String baseValue = resolvedDefaultsForCurrentMode.get(option); if (UNSUPPORTED_OPTIONS.contains(option)) { return; } Map<String, JsonNode> modifierMap = modifier.asObject(); if (modifierMap.size() != 1) { throw new IllegalStateException("More than one modifier exists for option " + option); } String modifierString = modifierMap.keySet().iterator().next(); switch (modifierString) { case "override": resolvedValue = modifierMap.get("override").visit(new StringJsonNodeVisitor()); break; case "multiply": resolvedValue = processMultiply(baseValue, modifierMap); break; case "add": resolvedValue = processAdd(baseValue, modifierMap); break; default: throw new UnsupportedOperationException("Unsupported modifier: " + modifierString); } resolvedDefaultsForCurrentMode.put(option, resolvedValue); } private static void applyModificationToOneMode(Map<String, Map<String, String>> resolvedDefaults, Map<String, JsonNode> base, String mode, JsonNode modifiers) { log.info(() -> "Apply modification for mode: " + mode); Map<String, String> resolvedDefaultsForCurrentMode = base.entrySet().stream().filter(e -> !UNSUPPORTED_OPTIONS.contains(e.getKey())) .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().visit(new StringJsonNodeVisitor())), Map::putAll); // Iterate the configuration options and apply modification. modifiers.asObject().forEach((option, modifier) -> applyModificationToOneConfigurationOption( resolvedDefaultsForCurrentMode, option, modifier)); resolvedDefaults.put(mode, resolvedDefaultsForCurrentMode); } private static String processAdd(String baseValue, Map<String, JsonNode> modifierMap) { String resolvedValue; String add = modifierMap.get("add").asNumber(); int parsedAdd = Integer.parseInt(add); int number = Math.addExact(Integer.parseInt(baseValue), parsedAdd); resolvedValue = String.valueOf(number); return resolvedValue; } private static String processMultiply(String baseValue, Map<String, JsonNode> modifierMap) { String resolvedValue; String multiply = modifierMap.get("multiply").asNumber(); double parsedValue = Double.parseDouble(multiply); double resolvedNumber = Integer.parseInt(baseValue) * parsedValue; int castValue = (int) resolvedNumber; if (castValue != resolvedNumber) { throw new IllegalStateException("The transformed value must be be a float number: " + castValue); } resolvedValue = String.valueOf(castValue); return resolvedValue; } private static final class StringJsonNodeVisitor implements JsonNodeVisitor<String> { @Override public String visitNull() { throw new IllegalStateException("Invalid type encountered"); } @Override public String visitBoolean(boolean b) { throw new IllegalStateException("Invalid type (boolean) encountered " + b); } @Override public String visitNumber(String s) { return s; } @Override public String visitString(String s) { return s; } @Override public String visitArray(List<JsonNode> list) { throw new IllegalStateException("Invalid type (list) encountered: " + list); } @Override public String visitObject(Map<String, JsonNode> map) { throw new IllegalStateException("Invalid type (map) encountered: " + map); } @Override public String visitEmbeddedObject(Object o) { throw new IllegalStateException("Invalid type (embedded) encountered: " + o); } } }
2,860
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeConfigurationGenerator.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.codegen.lite.defaultsmode; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.EnumMap; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.utils.AttributeMap; /** * Generates DefaultsModeConfiguration class that contains default options for each mode */ public class DefaultsModeConfigurationGenerator implements PoetClass { private static final String DEFAULT_CONFIG_BY_MODE_ENUM_MAP = "DEFAULT_CONFIG_BY_MODE"; private static final String DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP = "DEFAULT_HTTP_CONFIG_BY_MODE"; private static final String DEFAULTS_VAR_SUFFIX = "_DEFAULTS"; private static final String HTTP_DEFAULTS_VAR_SUFFIX = "_HTTP_DEFAULTS"; private static final Map<String, OptionMetadata> CONFIGURATION_MAPPING = new HashMap<>(); private static final Map<String, OptionMetadata> HTTP_CONFIGURATION_MAPPING = new HashMap<>(); private static final String CONNECT_TIMEOUT_IN_MILLIS = "connectTimeoutInMillis"; private static final String TLS_NEGOTIATION_TIMEOUT_IN_MILLIS = "tlsNegotiationTimeoutInMillis"; private static final String S3_US_EAST_1_REGIONAL_ENDPOINTS = "s3UsEast1RegionalEndpoints"; private final String basePackage; private final String defaultsModeBase; private final DefaultConfiguration configuration; static { HTTP_CONFIGURATION_MAPPING.put(CONNECT_TIMEOUT_IN_MILLIS, new OptionMetadata(ClassName.get("java.time", "Duration"), ClassName.get("software.amazon.awssdk.http", "SdkHttpConfigurationOption", "CONNECTION_TIMEOUT"))); HTTP_CONFIGURATION_MAPPING.put(TLS_NEGOTIATION_TIMEOUT_IN_MILLIS, new OptionMetadata(ClassName.get("java.time", "Duration"), ClassName.get("software.amazon.awssdk.http", "SdkHttpConfigurationOption", "TLS_NEGOTIATION_TIMEOUT"))); CONFIGURATION_MAPPING.put("retryMode", new OptionMetadata(ClassName.get("software.amazon.awssdk.core.retry", "RetryMode" ), ClassName.get("software.amazon.awssdk.core.client.config", "SdkClientOption", "DEFAULT_RETRY_MODE"))); CONFIGURATION_MAPPING.put(S3_US_EAST_1_REGIONAL_ENDPOINTS, new OptionMetadata(ClassName.get(String.class), ClassName.get("software.amazon.awssdk.regions", "ServiceMetadataAdvancedOption", "DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT"))); } public DefaultsModeConfigurationGenerator(String basePackage, String defaultsModeBase, DefaultConfiguration configuration) { this.basePackage = basePackage; this.configuration = configuration; this.defaultsModeBase = defaultsModeBase; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(PUBLIC, FINAL) .addJavadoc(documentation()) .addAnnotation(SdkInternalApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(defaultConfigMethod(DEFAULT_CONFIG_BY_MODE_ENUM_MAP, "defaultConfig")) .addMethod(defaultConfigMethod(DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP, "defaultHttpConfig")) .addMethod(createConstructor()); configuration.modeDefaults().entrySet().forEach(entry -> { builder.addField(addDefaultsFieldForMode(entry)); builder.addField(addHttpDefaultsFieldForMode(entry)); }); addDefaultsFieldForLegacy(builder, "LEGACY_DEFAULTS"); addDefaultsFieldForLegacy(builder, "LEGACY_HTTP_DEFAULTS"); addEnumMapField(builder, DEFAULT_CONFIG_BY_MODE_ENUM_MAP); addEnumMapField(builder, DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP); addStaticEnumMapBlock(builder); return builder.build(); } private void addStaticEnumMapBlock(TypeSpec.Builder builder) { CodeBlock.Builder staticCodeBlock = CodeBlock.builder(); putItemsToEnumMap(staticCodeBlock, configuration.modeDefaults().keySet(), DEFAULTS_VAR_SUFFIX, DEFAULT_CONFIG_BY_MODE_ENUM_MAP); putItemsToEnumMap(staticCodeBlock, configuration.modeDefaults().keySet(), HTTP_DEFAULTS_VAR_SUFFIX, DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP); builder.addStaticBlock(staticCodeBlock.build()); } private void addEnumMapField(TypeSpec.Builder builder, String name) { ParameterizedTypeName map = ParameterizedTypeName.get(ClassName.get(Map.class), defaultsModeClassName(), ClassName.get(AttributeMap.class)); FieldSpec field = FieldSpec.builder(map, name, PRIVATE, STATIC, FINAL) .initializer("new $T<>(DefaultsMode.class)", EnumMap.class).build(); builder.addField(field); } private void putItemsToEnumMap(CodeBlock.Builder codeBlock, Set<String> modes, String suffix, String mapName) { modes.forEach(m -> { String mode = sanitizeMode(m); codeBlock.addStatement("$N.put(DefaultsMode.$N, $N)", mapName, mode, mode + suffix); }); // Add LEGACY since LEGACY is not in the modes set codeBlock.addStatement("$N.put(DefaultsMode.LEGACY, LEGACY$N)", mapName, suffix); } @Override public ClassName className() { return ClassName.get(basePackage, "DefaultsModeConfiguration"); } private FieldSpec addDefaultsFieldForMode(Map.Entry<String, Map<String, String>> modeEntry) { String mode = modeEntry.getKey(); String fieldName = sanitizeMode(mode) + DEFAULTS_VAR_SUFFIX; CodeBlock.Builder attributeBuilder = CodeBlock.builder() .add("$T.builder()", AttributeMap.class); modeEntry.getValue() .entrySet() .stream() .filter(e -> CONFIGURATION_MAPPING.containsKey(e.getKey())) .forEach(e -> attributeMapBuilder(e.getKey(), e.getValue(), attributeBuilder)); FieldSpec.Builder fieldSpec = FieldSpec.builder(AttributeMap.class, fieldName, PRIVATE, STATIC, FINAL) .initializer(attributeBuilder .add(".build()") .build()); return fieldSpec.build(); } private void addDefaultsFieldForLegacy(TypeSpec.Builder builder, String name) { FieldSpec field = FieldSpec.builder(AttributeMap.class, name, PRIVATE, STATIC, FINAL) .initializer("$T.empty()", AttributeMap.class).build(); builder.addField(field); } private void attributeMapBuilder(String option, String value, CodeBlock.Builder attributeBuilder) { OptionMetadata optionMetadata = CONFIGURATION_MAPPING.get(option); switch (option) { case "retryMode": attributeBuilder.add(".put($T, $T.$N)", optionMetadata.attribute, optionMetadata.type, value.toUpperCase(Locale.US)); break; case S3_US_EAST_1_REGIONAL_ENDPOINTS: attributeBuilder.add(".put($T, $S)", optionMetadata.attribute, value); break; default: throw new IllegalStateException("Unsupported option " + option); } } private void httpAttributeMapBuilder(String option, String value, CodeBlock.Builder attributeBuilder) { OptionMetadata optionMetadata = HTTP_CONFIGURATION_MAPPING.get(option); switch (option) { case CONNECT_TIMEOUT_IN_MILLIS: case TLS_NEGOTIATION_TIMEOUT_IN_MILLIS: attributeBuilder.add(".put($T, $T.ofMillis($N))", optionMetadata.attribute, optionMetadata.type, value); break; default: throw new IllegalStateException("Unsupported option " + option); } } private FieldSpec addHttpDefaultsFieldForMode(Map.Entry<String, Map<String, String>> modeEntry) { String mode = modeEntry.getKey(); String fieldName = sanitizeMode(mode) + HTTP_DEFAULTS_VAR_SUFFIX; CodeBlock.Builder attributeBuilder = CodeBlock.builder() .add("$T.builder()", AttributeMap.class); modeEntry.getValue() .entrySet() .stream() .filter(e -> HTTP_CONFIGURATION_MAPPING.containsKey(e.getKey())) .forEach(e -> httpAttributeMapBuilder(e.getKey(), e.getValue(), attributeBuilder)); FieldSpec.Builder fieldSpec = FieldSpec.builder(AttributeMap.class, fieldName, PRIVATE, STATIC, FINAL) .initializer(attributeBuilder .add(".build()") .build()); return fieldSpec.build(); } private String sanitizeMode(String str) { return str.replace('-', '_').toUpperCase(Locale.US); } private CodeBlock documentation() { CodeBlock.Builder builder = CodeBlock.builder() .add("Contains a collection of default configuration options for each " + "DefaultsMode"); return builder.build(); } private MethodSpec defaultConfigMethod(String enumMap, String methodName) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName) .returns(AttributeMap.class) .addModifiers(PUBLIC, STATIC) .addJavadoc("Return the default config options for a given defaults " + "mode") .addParameter(defaultsModeClassName(), "mode") .addStatement("return $N.getOrDefault(mode, $T.empty())", enumMap, AttributeMap.class); return methodBuilder.build(); } private ClassName defaultsModeClassName() { return ClassName.get(defaultsModeBase, "DefaultsMode"); } private MethodSpec createConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); } private static final class OptionMetadata { private final ClassName type; private final ClassName attribute; OptionMetadata(ClassName type, ClassName attribute) { this.type = type; this.attribute = attribute; } } }
2,861
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultConfiguration.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.codegen.lite.defaultsmode; import java.util.Map; /** * Container for default configuration */ public class DefaultConfiguration { /** * The transformed configuration values for each mode */ private Map<String, Map<String, String>> modeDefaults; /** * The documentation for each mode */ private Map<String, String> modesDocumentation; /* * The documentation for each configuration option */ private Map<String, String> configurationDocumentation; public Map<String, Map<String, String>> modeDefaults() { return modeDefaults; } public DefaultConfiguration modeDefaults(Map<String, Map<String, String>> modeDefaults) { this.modeDefaults = modeDefaults; return this; } public Map<String, String> modesDocumentation() { return modesDocumentation; } public DefaultConfiguration modesDocumentation(Map<String, String> documentation) { this.modesDocumentation = documentation; return this; } public Map<String, String> configurationDocumentation() { return configurationDocumentation; } public DefaultConfiguration configurationDocumentation(Map<String, String> configurationDocumentation) { this.configurationDocumentation = configurationDocumentation; return this; } }
2,862
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/CodeWriter.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.codegen.lite.emitters; import static software.amazon.awssdk.codegen.lite.Utils.closeQuietly; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.utils.StringUtils; /** * Formats the generated code and write it to the underlying file. The caller should call the flush * method to write the contents to the file. This class is intended to be used only by the code * generation system and is not to be used for public use. */ public class CodeWriter extends StringWriter { /** * The code transformation that should be applied before code is written. */ private final CodeTransformer codeWriteTransformer = CodeTransformer.chain(new UnusedImportRemover(), new JavaCodeFormatter()); /** * The code transformation that should be applied before source code is "compared" for equality. This is only used when * attempting to clobber a file that has already been generated. */ private final CodeTransformer codeComparisonTransformer = new LinkRemover(); private final String dir; private final String file; /** * Constructor to use for .java files. * @param dir * output directory where the file is to be created. * @param file * name of the file without .java suffix. */ public CodeWriter(String dir, String file) { this(dir, file, ".java"); } /** * Constructor to use for custom file suffixes. * * @param dir * output directory where the file is to be created. * @param file * name of the file excluding suffix. * @param fileNameSuffix * suffix to be appended at the end of file name. */ public CodeWriter(String dir, String file, String fileNameSuffix) { if (dir == null) { throw new IllegalArgumentException( "Output Directory cannot be null."); } if (file == null) { throw new IllegalArgumentException("File name cannot be null."); } if (fileNameSuffix == null) { throw new IllegalArgumentException("File name suffix cannot be null."); } if (!file.endsWith(fileNameSuffix)) { file = file + fileNameSuffix; } this.dir = dir; this.file = file; Utils.createDirectory(dir); } /** * This method is expected to be called only once during the code generation process after the * template processing is done. */ @Override public void flush() { PrintWriter out = null; try { File outputFile = Utils.createFile(dir, this.file); String contents = getBuffer().toString(); String formattedContents = codeWriteTransformer.apply(contents); if (outputFile.length() == 0) { out = new PrintWriter(outputFile, "UTF-8"); out.write(formattedContents); } else { validateFileContentMatches(outputFile, formattedContents); } } catch (IOException e) { throw new IllegalStateException(e); } finally { closeQuietly(out); } } private void validateFileContentMatches(File outputFile, String newFileContents) throws IOException { byte[] currentFileBytes = Files.readAllBytes(outputFile.toPath()); String currentFileContents = new String(currentFileBytes, StandardCharsets.UTF_8); String currentContentForComparison = codeComparisonTransformer.apply(currentFileContents); String newContentForComparison = codeComparisonTransformer.apply(newFileContents); if (!StringUtils.equals(currentContentForComparison, newContentForComparison)) { throw new IllegalStateException("Attempted to clobber existing file (" + outputFile + ") with a new file that has " + "different content. This may indicate forgetting to clean up old generated files " + "before running the generator?\n" + "Existing file: \n" + currentContentForComparison + "\n\n" + "New file: \n" + newContentForComparison); } } }
2,863
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/LinkRemover.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.codegen.lite.emitters; import java.util.regex.Pattern; /** * Removes HTML "anchor" tags from a string. This is used to compare files during clobbering while ignoring their documentation * links, which will pretty much always differ. */ public class LinkRemover implements CodeTransformer { private static final Pattern LINK_PATTERN = Pattern.compile("(<a[ \n]*/>|<a[> \n].*?</a>)", Pattern.DOTALL); @Override public String apply(String input) { return LINK_PATTERN.matcher(input).replaceAll(""); } }
2,864
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/JavaCodeFormatter.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.codegen.lite.emitters; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.TextEdit; /** * Formats the generated java source code. Uses Eclipse JDT core plugin from the Eclipse SDK. */ @SuppressWarnings("unchecked") public class JavaCodeFormatter implements CodeTransformer { private static final Map<String, Object> DEFAULT_FORMATTER_OPTIONS; static { DEFAULT_FORMATTER_OPTIONS = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, DefaultCodeFormatterConstants.FALSE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_COMPACT, DefaultCodeFormatterConstants.INDENT_DEFAULT)); // Formats custom file headers if provided DEFAULT_FORMATTER_OPTIONS .put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, DefaultCodeFormatterConstants.TRUE); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "130"); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "120"); } private final CodeFormatter codeFormatter; /** * Creates a JavaCodeFormatter using the default formatter options. */ public JavaCodeFormatter() { this(new HashMap<>()); } /** * Creates a JavaCodeFormatter using the default formatter options and * optionally applying user provided options on top. * * @param overrideOptions user provided options to apply on top of defaults */ public JavaCodeFormatter(final Map<String, Object> overrideOptions) { Map formatterOptions = new HashMap<>(DEFAULT_FORMATTER_OPTIONS); if (overrideOptions != null) { formatterOptions.putAll(overrideOptions); } this.codeFormatter = ToolFactory.createCodeFormatter(formatterOptions, ToolFactory.M_FORMAT_EXISTING); } @Override public String apply(String contents) { TextEdit edit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, System.lineSeparator()); if (edit == null) { // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost return contents; } IDocument document = new Document(contents); try { edit.apply(document); } catch (Exception e) { throw new RuntimeException( "Failed to format the generated source code.", e); } return document.get(); } }
2,865
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/CodeTransformer.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.codegen.lite.emitters; import java.util.function.Function; import java.util.stream.Stream; public interface CodeTransformer extends Function<String, String> { static CodeTransformer chain(CodeTransformer... processors) { return input -> Stream.of(processors).map(p -> (Function<String, String>) p) .reduce(Function.identity(), Function::andThen).apply(input); } @Override String apply(String input); }
2,866
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/UnusedImportRemover.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.codegen.lite.emitters; import static java.util.stream.Collectors.toSet; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UnusedImportRemover implements CodeTransformer { private static Pattern IMPORT_PATTERN = Pattern.compile("import(?:\\s+)(?:static\\s+)?(.*)(?:\\s*);"); @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } private Function<String, String> removeImportFunction(String importToRemove) { return c -> c.replaceFirst(findSpecificImportRegex(importToRemove), ""); } private Set<String> findUnusedImports(String content) { return findImports(content).stream().filter(isUnused(content)).collect(toSet()); } private List<String> findImports(String content) { Matcher m = IMPORT_PATTERN.matcher(content); List<String> imports = new ArrayList<>(); while (m.find()) { imports.add(m.group(1)); } return imports; } private String removeAllImports(String content) { return content.replaceAll(IMPORT_PATTERN.pattern(), ""); } private Predicate<String> isUnused(String content) { String contentWithoutImports = removeAllImports(content); return importToCheck -> !importToCheck.contains("*") && (isNotReferenced(contentWithoutImports, importToCheck) || isDuplicate(content, importToCheck)); } private boolean isNotReferenced(String contentWithoutImports, String importToCheck) { String symbol = importToCheck.substring(importToCheck.lastIndexOf('.') + 1); return !Pattern.compile(String.format("\\b%s\\b", symbol)).matcher(contentWithoutImports).find(); } private boolean isDuplicate(String content, String importToCheck) { Matcher m = Pattern.compile(findSpecificImportRegex(importToCheck)).matcher(content); return m.find() && m.find(); } private String findSpecificImportRegex(String specificImport) { return String.format("import(?:\\s+)(?:static )?(?:%s)(?:\\s*);", specificImport); } }
2,867
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws/test/AppTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class AppTest { @Test public void handleRequest_shouldReturnConstantValue() { App function = new App(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,868
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link App}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_WEST_2) .httpClientBuilder(UrlConnectionHttpClient.builder()) .build(); } }
2,869
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.s3.S3Client; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class App implements RequestHandler<Object, Object> { private final S3Client s3Client; public App() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. s3Client = DependencyFactory.s3Client(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using s3Client. return input; } }
2,870
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/test/java/software/amazonaws/test/MyWafRegionalFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyWafRegionalFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyWafRegionalFunction function = new MyWafRegionalFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,871
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.regional.WafRegionalClient; /** * The module containing all dependencies required by the {@link MyWafRegionalFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of WafRegionalClient */ public static WafRegionalClient wafRegionalClient() { return WafRegionalClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.AP_SOUTHEAST_1) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
2,872
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws/test/MyWafRegionalFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.waf.regional.WafRegionalClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyWafRegionalFunction implements RequestHandler<Object, Object> { private final WafRegionalClient wafRegionalClient; public MyWafRegionalFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. wafRegionalClient = DependencyFactory.wafRegionalClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using wafRegionalClient. return input; } }
2,873
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws/test/MyNettyFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyNettyFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyNettyFunction function = new MyNettyFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,874
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; /** * The module containing all dependencies required by the {@link MyNettyFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of KinesisAsyncClient */ public static KinesisAsyncClient kinesisClient() { return KinesisAsyncClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_EAST_1) .httpClientBuilder(NettyNioAsyncHttpClient.builder()) .build(); } }
2,875
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/MyNettyFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyNettyFunction implements RequestHandler<Object, Object> { private final KinesisAsyncClient kinesisClient; public MyNettyFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. kinesisClient = DependencyFactory.kinesisClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using kinesisClient. return input; } }
2,876
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws/test/MyApacheFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyApacheFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyApacheFunction function = new MyApacheFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,877
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * The module containing all dependencies required by the {@link MyApacheFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbClient */ public static DynamoDbClient dynamoDbClient() { return DynamoDbClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
2,878
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/MyApacheFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyApacheFunction implements RequestHandler<Object, Object> { private final DynamoDbClient dynamoDbClient; public MyApacheFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. dynamoDbClient = DependencyFactory.dynamoDbClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using dynamoDbClient. return input; } }
2,879
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/test/java/software/amazonaws/test/MyDynamoDbStreamsFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyDynamoDbStreamsFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyDynamoDbStreamsFunction function = new MyDynamoDbStreamsFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,880
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws/test/MyDynamoDbStreamsFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyDynamoDbStreamsFunction implements RequestHandler<Object, Object> { private final DynamoDbStreamsClient dynamoDbStreamsClient; public MyDynamoDbStreamsFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. dynamoDbStreamsClient = DependencyFactory.dynamoDbStreamsClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using dynamoDbStreamsClient. return input; } }
2,881
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; /** * The module containing all dependencies required by the {@link MyDynamoDbStreamsFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbStreamsClient */ public static DynamoDbStreamsClient dynamoDbStreamsClient() { return DynamoDbStreamsClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.AP_SOUTHEAST_1) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
2,882
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/test
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/test/java/__handlerClassName__Test.java
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ${handlerClassName}Test { @Test public void handleRequest_shouldReturnConstantValue() { ${handlerClassName} function = new ${handlerClassName}(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
2,883
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main/java/DependencyFactory.java
#parse ( "global.vm") package ${package}; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; #if ($region == 'null') import software.amazon.awssdk.core.SdkSystemSetting; #end import software.amazon.awssdk.http.${httpClientPackageName}; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; /** * The module containing all dependencies required by the {@link ${handlerClassName}}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of ${serviceClientClassName} */ public static ${serviceClientClassName} ${serviceClientVariable}Client() { return ${serviceClientClassName}.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) #if ($region == 'null') .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) #else .region(Region.${regionEnum}) #end .httpClientBuilder(${httpClientClassName}.builder()) .build(); } }
2,884
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main/java/__handlerClassName__.java
#parse ( "global.vm") package ${package}; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class ${handlerClassName} implements RequestHandler<Object, Object> { private final ${serviceClientClassName} ${serviceClientVariable}Client; public ${handlerClassName}() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. ${serviceClientVariable}Client = DependencyFactory.${serviceClientVariable}Client(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using ${serviceClientVariable}Client. return input; } }
2,885
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
2,886
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3Client; public class Handler { private final S3Client s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
2,887
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
2,888
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
2,889
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
2,890
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; public class Handler { private final DynamoDbClient dynamoDbClient; public Handler() { dynamoDbClient = DependencyFactory.dynamoDbClient(); } public void sendRequest() { // TODO: invoking the api calls using dynamoDbClient. } }
2,891
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbClient */ public static DynamoDbClient dynamoDbClient() { return DynamoDbClient.builder() .httpClientBuilder(UrlConnectionHttpClient.builder()) .build(); } }
2,892
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
2,893
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
2,894
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3AsyncClient; public class Handler { private final S3AsyncClient s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
2,895
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3AsyncClient */ public static S3AsyncClient s3Client() { return S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder()) .build(); } }
2,896
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
2,897
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
2,898
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3Client; public class Handler { private final S3Client s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
2,899