index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/AuthSchemeGeneratorTasks.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.emitters.tasks; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeInterceptorSpec; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeParamsSpec; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeProviderSpec; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.auth.scheme.DefaultAuthSchemeParamsSpec; import software.amazon.awssdk.codegen.poet.auth.scheme.EndpointBasedAuthSchemeProviderSpec; import software.amazon.awssdk.codegen.poet.auth.scheme.ModelBasedAuthSchemeProviderSpec; public final class AuthSchemeGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams generatorTaskParams; public AuthSchemeGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.generatorTaskParams = dependencies; } @Override protected List<GeneratorTask> createTasks() { AuthSchemeSpecUtils authSchemeSpecUtils = new AuthSchemeSpecUtils(model); List<GeneratorTask> tasks = new ArrayList<>(); tasks.add(generateParamsInterface()); tasks.add(generateProviderInterface()); tasks.add(generateDefaultParamsImpl()); tasks.add(generateModelBasedProvider()); tasks.add(generateAuthSchemeInterceptor()); if (authSchemeSpecUtils.useEndpointBasedAuthProvider()) { tasks.add(generateEndpointBasedProvider()); } return tasks; } private GeneratorTask generateParamsInterface() { return new PoetGeneratorTask(authSchemeDir(), model.getFileHeader(), new AuthSchemeParamsSpec(model)); } private GeneratorTask generateDefaultParamsImpl() { return new PoetGeneratorTask(authSchemeInternalDir(), model.getFileHeader(), new DefaultAuthSchemeParamsSpec(model)); } private GeneratorTask generateProviderInterface() { return new PoetGeneratorTask(authSchemeDir(), model.getFileHeader(), new AuthSchemeProviderSpec(model)); } private GeneratorTask generateModelBasedProvider() { return new PoetGeneratorTask(authSchemeInternalDir(), model.getFileHeader(), new ModelBasedAuthSchemeProviderSpec(model)); } private GeneratorTask generateEndpointBasedProvider() { return new PoetGeneratorTask(authSchemeInternalDir(), model.getFileHeader(), new EndpointBasedAuthSchemeProviderSpec(model)); } private GeneratorTask generateAuthSchemeInterceptor() { return new PoetGeneratorTask(authSchemeInternalDir(), model.getFileHeader(), new AuthSchemeInterceptorSpec(model)); } private String authSchemeDir() { return generatorTaskParams.getPathProvider().getAuthSchemeDirectory(); } private String authSchemeInternalDir() { return generatorTaskParams.getPathProvider().getAuthSchemeInternalDirectory(); } }
3,900
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/CommonGeneratorTasks.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.emitters.tasks; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; /** * Common generator tasks. */ class CommonGeneratorTasks extends CompositeGeneratorTask { CommonGeneratorTasks(GeneratorTaskParams params) { super(new CommonClientGeneratorTasks(params), new SyncClientGeneratorTasks(params), new MarshallerGeneratorTasks(params), new ModelClassGeneratorTasks(params), new PackageInfoGeneratorTasks(params), new BaseExceptionClassGeneratorTasks(params), new CommonInternalGeneratorTasks(params)); } }
3,901
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/CompositeGeneratorTask.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.emitters.tasks; import java.util.concurrent.ForkJoinTask; import software.amazon.awssdk.codegen.emitters.GeneratorTask; public abstract class CompositeGeneratorTask extends GeneratorTask { private final GeneratorTask[] tasks; protected CompositeGeneratorTask(GeneratorTask... tasks) { this.tasks = tasks; } @Override protected void compute() { ForkJoinTask.invokeAll(tasks); } }
3,902
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/MarshallerGeneratorTasks.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.emitters.tasks; import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.transform.MarshallerSpec; public class MarshallerGeneratorTasks extends BaseGeneratorTasks { private final Metadata metadata; public MarshallerGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.metadata = model.getMetadata(); } @Override protected List<GeneratorTask> createTasks() { return model.getShapes().entrySet().stream() .filter(e -> shouldGenerate(e.getValue())) .flatMap(safeFunction(e -> createTask(e.getKey(), e.getValue()))) .collect(Collectors.toList()); } private boolean shouldGenerate(ShapeModel shapeModel) { if (shapeModel.getCustomization().isSkipGeneratingMarshaller()) { info("Skipping generating marshaller class for " + shapeModel.getShapeName()); return false; } ShapeType shapeType = shapeModel.getShapeType(); return (ShapeType.Request == shapeType || (ShapeType.Model == shapeType && metadata.isJsonProtocol())) // The event stream shape is a container for event subtypes and isn't something that needs to ever be marshalled && !shapeModel.isEventStream(); } private Stream<GeneratorTask> createTask(String javaShapeName, ShapeModel shapeModel) throws Exception { return ShapeType.Request == shapeModel.getShapeType() || (ShapeType.Model == shapeModel.getShapeType() && shapeModel.isEvent() && EventStreamUtils.isRequestEvent(model, shapeModel)) ? Stream.of(createPoetGeneratorTask(new MarshallerSpec(model, shapeModel))) : Stream.empty(); } }
3,903
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/PackageInfoGeneratorTasks.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.emitters.tasks; import java.util.Collections; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.SimpleGeneratorTask; import software.amazon.awssdk.codegen.model.intermediate.Metadata; /** * Emits the package-info.java for the base service package. Includes the service * level documentation. */ public final class PackageInfoGeneratorTasks extends BaseGeneratorTasks { private final String baseDirectory; PackageInfoGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.baseDirectory = dependencies.getPathProvider().getClientDirectory(); } @Override protected List<GeneratorTask> createTasks() throws Exception { Metadata metadata = model.getMetadata(); String packageInfoContents = String.format("/**%n" + " * %s%n" + "*/%n" + "package %s;", metadata.getDocumentation(), metadata.getFullClientPackageName()); return Collections.singletonList(new SimpleGeneratorTask(baseDirectory, "package-info.java", model.getFileHeader(), () -> packageInfoContents)); } }
3,904
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/AsyncClientGeneratorTasks.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.emitters.tasks; import java.io.IOException; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.poet.builder.AsyncClientBuilderClass; import software.amazon.awssdk.codegen.poet.builder.AsyncClientBuilderInterface; import software.amazon.awssdk.codegen.poet.client.AsyncClientClass; import software.amazon.awssdk.codegen.poet.client.AsyncClientInterface; import software.amazon.awssdk.codegen.poet.client.DelegatingAsyncClientClass; import software.amazon.awssdk.codegen.poet.endpointdiscovery.EndpointDiscoveryAsyncCacheLoaderGenerator; public class AsyncClientGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams generatorTaskParams; public AsyncClientGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.generatorTaskParams = dependencies; } @Override protected List<GeneratorTask> createTasks() throws Exception { List<GeneratorTask> generatorTasks = new ArrayList<>(); generatorTasks.add(createClientClassTask()); generatorTasks.add(createClientBuilderTask()); generatorTasks.add(createClientBuilderInterfaceTask()); generatorTasks.add(createClientInterfaceTask()); if (model.getEndpointOperation().isPresent()) { generatorTasks.add(createEndpointDiscoveryCacheLoaderTask()); } if (model.getCustomizationConfig().isDelegateAsyncClientClass()) { generatorTasks.add(createDecoratorClientClassTask()); } return generatorTasks; } private GeneratorTask createClientClassTask() throws IOException { return createPoetGeneratorTask(new AsyncClientClass(generatorTaskParams)); } private GeneratorTask createDecoratorClientClassTask() throws IOException { return createPoetGeneratorTask(new DelegatingAsyncClientClass(model)); } private GeneratorTask createClientBuilderTask() throws IOException { return createPoetGeneratorTask(new AsyncClientBuilderClass(model)); } private GeneratorTask createClientBuilderInterfaceTask() throws IOException { return createPoetGeneratorTask(new AsyncClientBuilderInterface(model)); } private GeneratorTask createClientInterfaceTask() throws IOException { return createPoetGeneratorTask(new AsyncClientInterface(model)); } private GeneratorTask createEndpointDiscoveryCacheLoaderTask() throws IOException { return createPoetGeneratorTask(new EndpointDiscoveryAsyncCacheLoaderGenerator(generatorTaskParams)); } }
3,905
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/EventStreamGeneratorTasks.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.emitters.tasks; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamResponseHandlerBuilderImplSpec; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamResponseHandlerSpec; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamVisitorBuilderImplSpec; /** * Generator tasks for event streaming operations. */ class EventStreamGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams params; EventStreamGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.params = dependencies; } @Override protected List<GeneratorTask> createTasks() throws Exception { String fileHeader = model.getFileHeader(); String modelDirectory = params.getPathProvider().getModelDirectory(); return model.getOperations().values().stream() .filter(OperationModel::hasEventStreamOutput) .flatMap(this::eventStreamClassSpecs) .map(spec -> new PoetGeneratorTask(modelDirectory, fileHeader, spec)) .collect(Collectors.toList()); } private Stream<ClassSpec> eventStreamClassSpecs(OperationModel opModel) { return Stream.of( new EventStreamResponseHandlerSpec(params, opModel), new EventStreamResponseHandlerBuilderImplSpec(params, opModel), new EventStreamVisitorBuilderImplSpec(params, opModel)); } }
3,906
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/BaseGeneratorTasks.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.emitters.tasks; import java.io.IOException; import java.util.List; import java.util.concurrent.ForkJoinTask; import org.slf4j.Logger; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; public abstract class BaseGeneratorTasks extends GeneratorTask { protected final String baseDirectory; protected final String testDirectory; protected final IntermediateModel model; protected final Logger log; public BaseGeneratorTasks(GeneratorTaskParams dependencies) { this.baseDirectory = dependencies.getPathProvider().getSourceDirectory(); this.testDirectory = dependencies.getPathProvider().getTestDirectory(); this.model = dependencies.getModel(); this.log = dependencies.getLog(); } protected void info(String message) { log.info(message); } /** * Hook to allow subclasses to indicate they have no tasks so they can assume when createTasks is called there's something to * emit. */ protected boolean hasTasks() { return true; } protected final GeneratorTask createPoetGeneratorTask(ClassSpec classSpec) throws IOException { String targetDirectory = baseDirectory + '/' + Utils.packageToDirectory(classSpec.className().packageName()); return new PoetGeneratorTask(targetDirectory, model.getFileHeader(), classSpec); } protected final GeneratorTask createPoetGeneratorTestTask(ClassSpec classSpec) throws IOException { String targetDirectory = testDirectory + '/' + Utils.packageToDirectory(classSpec.className().packageName()); return new PoetGeneratorTask(targetDirectory, model.getFileHeader(), classSpec); } protected abstract List<GeneratorTask> createTasks() throws Exception; @Override protected void compute() { try { if (hasTasks()) { String taskName = getClass().getSimpleName(); log.info("Starting " + taskName + "..."); ForkJoinTask.invokeAll(createTasks()); log.info(" Completed " + taskName + "."); } } catch (Exception e) { throw new RuntimeException(e); } } }
3,907
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/ModelClassGeneratorTasks.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.emitters.tasks; import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.common.EnumClass; import software.amazon.awssdk.codegen.poet.model.AwsServiceBaseRequestSpec; import software.amazon.awssdk.codegen.poet.model.AwsServiceBaseResponseSpec; import software.amazon.awssdk.codegen.poet.model.AwsServiceModel; import software.amazon.awssdk.codegen.poet.model.EventModelSpec; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; import software.amazon.awssdk.codegen.poet.model.ResponseMetadataSpec; import software.amazon.awssdk.codegen.poet.model.ServiceModelCopiers; class ModelClassGeneratorTasks extends BaseGeneratorTasks { private final String modelClassDir; private final IntermediateModel intermediateModel; ModelClassGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.modelClassDir = dependencies.getPathProvider().getModelDirectory(); this.intermediateModel = dependencies.getModel(); } @Override protected List<GeneratorTask> createTasks() { List<GeneratorTask> tasks = new ArrayList<>(); tasks.add(new PoetGeneratorTask(modelClassDir, model.getFileHeader(), new AwsServiceBaseRequestSpec(model))); tasks.add(new PoetGeneratorTask(modelClassDir, model.getFileHeader(), new AwsServiceBaseResponseSpec(model))); model.getShapes().values().stream() .filter(this::shouldGenerateShape) .map(safeFunction(this::createTask)) .forEach(tasks::add); tasks.addAll(eventModelGenerationTasks()); new ServiceModelCopiers(model).copierSpecs().stream() .map(safeFunction(spec -> new PoetGeneratorTask(modelClassDir, model.getFileHeader(), spec))) .forEach(tasks::add); tasks.add(new PoetGeneratorTask(modelClassDir, model.getFileHeader(), new ResponseMetadataSpec(model))); return tasks; } private boolean shouldGenerateShape(ShapeModel shapeModel) { if (shapeModel.getCustomization().isSkipGeneratingModelClass()) { info("Skip generating class " + shapeModel.getShapeName()); return false; } return true; } private GeneratorTask createTask(ShapeModel shapeModel) { Metadata metadata = model.getMetadata(); ClassSpec classSpec; if (shapeModel.getShapeType() == ShapeType.Enum) { classSpec = new EnumClass(metadata.getFullModelPackageName(), shapeModel); } else { classSpec = new AwsServiceModel(model, shapeModel); } return new PoetGeneratorTask(modelClassDir, model.getFileHeader(), classSpec); } private List<GeneratorTask> eventModelGenerationTasks() { return model.getShapes().values().stream() .filter(ShapeModel::isEventStream) .flatMap(eventStream -> { EventStreamSpecHelper eventStreamSpecHelper = new EventStreamSpecHelper(eventStream, intermediateModel); return eventStream.getMembers().stream() .filter(e -> e.getShape().isEvent()) .filter(e -> !eventStreamSpecHelper.useLegacyGenerationScheme(e)) .map(e -> createEventGenerationTask(e, eventStream)); }) .collect(Collectors.toList()); } private GeneratorTask createEventGenerationTask(MemberModel memberModel, ShapeModel eventStream) { EventModelSpec spec = new EventModelSpec(memberModel, eventStream, model); String outputDir = modelClassDir + "/" + eventStream.getShapeName().toLowerCase(Locale.ENGLISH); return new PoetGeneratorTask(outputDir, model.getFileHeader(), spec); } }
3,908
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/SyncClientGeneratorTasks.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.emitters.tasks; import java.io.IOException; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.poet.builder.SyncClientBuilderClass; import software.amazon.awssdk.codegen.poet.builder.SyncClientBuilderInterface; import software.amazon.awssdk.codegen.poet.client.DelegatingSyncClientClass; import software.amazon.awssdk.codegen.poet.client.SyncClientClass; import software.amazon.awssdk.codegen.poet.client.SyncClientInterface; import software.amazon.awssdk.codegen.poet.endpointdiscovery.EndpointDiscoveryCacheLoaderGenerator; public class SyncClientGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams generatorTaskParams; public SyncClientGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.generatorTaskParams = dependencies; } @Override protected boolean hasTasks() { return !model.getCustomizationConfig().isSkipSyncClientGeneration(); } @Override protected List<GeneratorTask> createTasks() throws Exception { List<GeneratorTask> tasks = new ArrayList<>(); tasks.add(createClientClassTask()); tasks.add(createClientBuilderTask()); tasks.add(createClientInterfaceTask()); tasks.add(createClientBuilderInterfaceTask()); if (model.getEndpointOperation().isPresent()) { tasks.add(createEndpointDiscoveryCacheLoaderTask()); } if (model.getCustomizationConfig().isDelegateSyncClientClass()) { tasks.add(createDecoratorClientClassTask()); } return tasks; } private GeneratorTask createClientClassTask() throws IOException { return createPoetGeneratorTask(new SyncClientClass(generatorTaskParams)); } private GeneratorTask createDecoratorClientClassTask() throws IOException { return createPoetGeneratorTask(new DelegatingSyncClientClass(model)); } private GeneratorTask createClientBuilderTask() throws IOException { return createPoetGeneratorTask(new SyncClientBuilderClass(model)); } private GeneratorTask createClientInterfaceTask() throws IOException { return createPoetGeneratorTask(new SyncClientInterface(model)); } private GeneratorTask createClientBuilderInterfaceTask() throws IOException { return createPoetGeneratorTask(new SyncClientBuilderInterface(model)); } private GeneratorTask createEndpointDiscoveryCacheLoaderTask() throws IOException { return createPoetGeneratorTask(new EndpointDiscoveryCacheLoaderGenerator(generatorTaskParams)); } }
3,909
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/PaginatorsGeneratorTasks.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.emitters.tasks; import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.paginators.AsyncResponseClassSpec; import software.amazon.awssdk.codegen.poet.paginators.SyncResponseClassSpec; import software.amazon.awssdk.codegen.poet.paginators.customizations.SameTokenAsyncResponseClassSpec; import software.amazon.awssdk.codegen.poet.paginators.customizations.SameTokenSyncResponseClassSpec; public class PaginatorsGeneratorTasks extends BaseGeneratorTasks { private static final String SAME_TOKEN_CUSTOMIZATION = "LastPageHasPreviousToken"; private final String paginatorsClassDir; private final Map<String, String> customization; public PaginatorsGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.paginatorsClassDir = dependencies.getPathProvider().getPaginatorsDirectory(); this.customization = dependencies.getModel().getCustomizationConfig().getPaginationCustomization(); } @Override protected boolean hasTasks() { return model.hasPaginators(); } @Override protected List<GeneratorTask> createTasks() throws Exception { return model.getPaginators().entrySet().stream() .filter(entry -> entry.getValue().isValid()) .flatMap(safeFunction(this::createSyncAndAsyncTasks)) .collect(Collectors.toList()); } private Stream<GeneratorTask> createSyncAndAsyncTasks(Map.Entry<String, PaginatorDefinition> entry) throws IOException { if (!shouldGenerateSyncPaginators()) { return Stream.of(createAsyncTask(entry)); } return Stream.of(createSyncTask(entry), createAsyncTask(entry)); } private GeneratorTask createSyncTask(Map.Entry<String, PaginatorDefinition> entry) throws IOException { ClassSpec classSpec = new SyncResponseClassSpec(model, entry.getKey(), entry.getValue()); if (customization != null && customization.containsKey(entry.getKey())) { if (SAME_TOKEN_CUSTOMIZATION.equals(customization.get(entry.getKey()))) { classSpec = new SameTokenSyncResponseClassSpec(model, entry.getKey(), entry.getValue()); } } return new PoetGeneratorTask(paginatorsClassDir, model.getFileHeader(), classSpec); } private GeneratorTask createAsyncTask(Map.Entry<String, PaginatorDefinition> entry) throws IOException { ClassSpec classSpec = new AsyncResponseClassSpec(model, entry.getKey(), entry.getValue()); if (customization != null && customization.containsKey(entry.getKey())) { if (SAME_TOKEN_CUSTOMIZATION.equals(customization.get(entry.getKey()))) { classSpec = new SameTokenAsyncResponseClassSpec(model, entry.getKey(), entry.getValue()); } } return new PoetGeneratorTask(paginatorsClassDir, model.getFileHeader(), classSpec); } private boolean shouldGenerateSyncPaginators() { return !super.model.getCustomizationConfig().isSkipSyncClientGeneration(); } }
3,910
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/BaseExceptionClassGeneratorTasks.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.emitters.tasks; import java.util.Collections; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.poet.model.BaseExceptionClass; public class BaseExceptionClassGeneratorTasks extends BaseGeneratorTasks { private final String modelClassDir; public BaseExceptionClassGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.modelClassDir = dependencies.getPathProvider().getModelDirectory(); } /** * If a custom base class is provided we assume it already exists and does not need to be generated */ @Override protected boolean hasTasks() { return model.getCustomizationConfig().getSdkModeledExceptionBaseClassName() == null; } @Override protected List<GeneratorTask> createTasks() throws Exception { return Collections.singletonList( new PoetGeneratorTask(modelClassDir, model.getFileHeader(), new BaseExceptionClass(model))); } }
3,911
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/RulesEngineRuntimeGeneratorTask.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.emitters.tasks; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.SimpleGeneratorTask; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; public final class RulesEngineRuntimeGeneratorTask extends BaseGeneratorTasks { public static final String RUNTIME_CLASS_NAME = "WaitersRuntime"; private final String engineInternalClassDir; private final String engineInternalResourcesDir; private final String engineInternalPackageName; private final String fileHeader; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public RulesEngineRuntimeGeneratorTask(GeneratorTaskParams generatorTaskParams) { super(generatorTaskParams); this.engineInternalClassDir = generatorTaskParams.getPathProvider().getEndpointRulesInternalDirectory(); this.engineInternalResourcesDir = generatorTaskParams.getPathProvider().getEndpointRulesInternalResourcesDirectory(); this.engineInternalPackageName = generatorTaskParams.getModel().getMetadata().getFullInternalEndpointRulesPackageName(); this.fileHeader = generatorTaskParams.getModel().getFileHeader(); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(generatorTaskParams.getModel()); } @Override protected List<GeneratorTask> createTasks() throws Exception { List<GeneratorTask> copyTasks = new ArrayList<>(); List<String> rulesEngineFiles = endpointRulesSpecUtils.rulesEngineResourceFiles(); for (String path : rulesEngineJavaFilePaths(rulesEngineFiles)) { String newFileName = computeNewName(path); copyTasks.add(new SimpleGeneratorTask(engineInternalClassDir, newFileName, fileHeader, () -> rulesEngineFileContent("/" + path))); } return copyTasks; } private List<String> rulesEngineJavaFilePaths(Collection<String> runtimeEngineFiles) { return runtimeEngineFiles.stream() .filter(e -> e.endsWith(".java.resource")) .collect(Collectors.toList()); } private String rulesEngineFileContent(String path) { return "package " + engineInternalPackageName + ";\n" + "\n" + loadResourceAsString(path); } private String loadResourceAsString(String path) { try { return IoUtils.toUtf8String(loadResource(path)); } catch (IOException e) { throw new UncheckedIOException(e); } } private InputStream loadResource(String name) { InputStream resourceAsStream = RulesEngineRuntimeGeneratorTask.class.getResourceAsStream(name); Validate.notNull(resourceAsStream, "Failed to load resource from %s", name); return resourceAsStream; } private String computeNewName(String path) { String[] pathComponents = path.split("/"); return StringUtils.replace(pathComponents[pathComponents.length - 1], ".resource", ""); } }
3,912
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/WaitersRuntimeGeneratorTask.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.emitters.tasks; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Collections; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.SimpleGeneratorTask; import software.amazon.awssdk.utils.IoUtils; public final class WaitersRuntimeGeneratorTask extends BaseGeneratorTasks { public static final String RUNTIME_CLASS_NAME = "WaitersRuntime"; private final String waitersInternalClassDir; private final String waitersInternalPackageName; private final String fileHeader; private final String runtimeClassCode; public WaitersRuntimeGeneratorTask(GeneratorTaskParams generatorTaskParams) { super(generatorTaskParams); this.waitersInternalClassDir = generatorTaskParams.getPathProvider().getWaitersInternalDirectory(); this.waitersInternalPackageName = generatorTaskParams.getModel().getMetadata().getFullWaitersInternalPackageName(); this.fileHeader = generatorTaskParams.getModel().getFileHeader(); this.runtimeClassCode = loadWaitersRuntimeCode(); } @Override protected List<GeneratorTask> createTasks() throws Exception { String codeContents = "package " + waitersInternalPackageName + ";\n" + "\n" + runtimeClassCode; String fileName = RUNTIME_CLASS_NAME + ".java"; return Collections.singletonList(new SimpleGeneratorTask(waitersInternalClassDir, fileName, fileHeader, () -> codeContents)); } private static String loadWaitersRuntimeCode() { try { InputStream is = WaitersRuntimeGeneratorTask.class.getResourceAsStream( "/software/amazon/awssdk/codegen/waiters/WaitersRuntime.java.resource"); return IoUtils.toUtf8String(is); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } }
3,913
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/WaitersGeneratorTasks.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.emitters.tasks; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.poet.waiters.AsyncWaiterClassSpec; import software.amazon.awssdk.codegen.poet.waiters.AsyncWaiterInterfaceSpec; import software.amazon.awssdk.codegen.poet.waiters.WaiterClassSpec; import software.amazon.awssdk.codegen.poet.waiters.WaiterInterfaceSpec; @SdkInternalApi public class WaitersGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams generatorTaskParams; public WaitersGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); this.generatorTaskParams = dependencies; } @Override protected boolean hasTasks() { return model.hasWaiters(); } @Override protected List<GeneratorTask> createTasks() { List<GeneratorTask> generatorTasks = new ArrayList<>(); generatorTasks.addAll(createSyncTasks()); generatorTasks.addAll(createAsyncTasks()); generatorTasks.add(new WaitersRuntimeGeneratorTask(generatorTaskParams)); return generatorTasks; } private List<GeneratorTask> createSyncTasks() { List<GeneratorTask> syncTasks = new ArrayList<>(); syncTasks.add(new PoetGeneratorTask(waitersClassDir(), model.getFileHeader(), new WaiterInterfaceSpec(model))); syncTasks.add(new PoetGeneratorTask(waitersClassDir(), model.getFileHeader(), new WaiterClassSpec(model))); return syncTasks; } private List<GeneratorTask> createAsyncTasks() { List<GeneratorTask> asyncTasks = new ArrayList<>(); asyncTasks.add(new PoetGeneratorTask(waitersClassDir(), model.getFileHeader(), new AsyncWaiterInterfaceSpec(model))); asyncTasks.add(new PoetGeneratorTask(waitersClassDir(), model.getFileHeader(), new AsyncWaiterClassSpec(model))); return asyncTasks; } private String waitersClassDir() { return generatorTaskParams.getPathProvider().getWaitersDirectory(); } }
3,914
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/CommonInternalGeneratorTasks.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.emitters.tasks; import java.util.Arrays; import java.util.List; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.poet.client.SdkClientOptions; import software.amazon.awssdk.codegen.poet.common.UserAgentUtilsSpec; public class CommonInternalGeneratorTasks extends BaseGeneratorTasks { private final GeneratorTaskParams params; public CommonInternalGeneratorTasks(GeneratorTaskParams params) { super(params); this.params = params; } @Override protected List<GeneratorTask> createTasks() throws Exception { return Arrays.asList(createClientOptionTask(), createUserAgentTask()); } private PoetGeneratorTask createClientOptionTask() { return new PoetGeneratorTask(clientOptionsDir(), params.getModel().getFileHeader(), new SdkClientOptions(params.getModel())); } private PoetGeneratorTask createUserAgentTask() { return new PoetGeneratorTask(clientOptionsDir(), params.getModel().getFileHeader(), new UserAgentUtilsSpec(params.getModel())); } private String clientOptionsDir() { return params.getPathProvider().getClientInternalDirectory(); } }
3,915
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/EndpointProviderTasks.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.emitters.tasks; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.PoetGeneratorTask; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.poet.rules.ClientContextParamsClassSpec; import software.amazon.awssdk.codegen.poet.rules.DefaultPartitionDataProviderSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointParametersClassSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointProviderInterfaceSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointProviderSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointProviderTestSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointResolverInterceptorSpec; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesClientTestSpec; import software.amazon.awssdk.codegen.poet.rules.RequestEndpointInterceptorSpec; public final class EndpointProviderTasks extends BaseGeneratorTasks { private final GeneratorTaskParams generatorTaskParams; public EndpointProviderTasks(GeneratorTaskParams dependencies) { super(dependencies); this.generatorTaskParams = dependencies; } @Override protected List<GeneratorTask> createTasks() throws Exception { List<GeneratorTask> tasks = new ArrayList<>(); tasks.add(generateInterface()); tasks.add(generateParams()); tasks.add(generateDefaultProvider()); tasks.addAll(generateInterceptors()); if (shouldGenerateEndpointTests()) { tasks.add(generateProviderTests()); } if (shouldGenerateEndpointTests() && shouldGenerateClientEndpointTests()) { tasks.add(generateClientTests()); } if (hasClientContextParams()) { tasks.add(generateClientContextParams()); } tasks.add(new RulesEngineRuntimeGeneratorTask(generatorTaskParams)); tasks.add(generateDefaultPartitionsProvider()); return tasks; } private GeneratorTask generateInterface() { return new PoetGeneratorTask(endpointRulesDir(), model.getFileHeader(), new EndpointProviderInterfaceSpec(model)); } private GeneratorTask generateParams() { return new PoetGeneratorTask(endpointRulesDir(), model.getFileHeader(), new EndpointParametersClassSpec(model)); } private GeneratorTask generateDefaultProvider() { return new PoetGeneratorTask(endpointRulesInternalDir(), model.getFileHeader(), new EndpointProviderSpec(model)); } private GeneratorTask generateDefaultPartitionsProvider() { return new PoetGeneratorTask(endpointRulesInternalDir(), model.getFileHeader(), new DefaultPartitionDataProviderSpec(model)); } private Collection<GeneratorTask> generateInterceptors() { return Arrays.asList( new PoetGeneratorTask(endpointRulesInternalDir(), model.getFileHeader(), new EndpointResolverInterceptorSpec(model)), new PoetGeneratorTask(endpointRulesInternalDir(), model.getFileHeader(), new RequestEndpointInterceptorSpec(model))); } private GeneratorTask generateClientTests() { return new PoetGeneratorTask(endpointTestsDir(), model.getFileHeader(), new EndpointRulesClientTestSpec(model)); } private GeneratorTask generateProviderTests() { return new PoetGeneratorTask(endpointTestsDir(), model.getFileHeader(), new EndpointProviderTestSpec(model)); } private GeneratorTask generateClientContextParams() { return new PoetGeneratorTask(endpointRulesInternalDir(), model.getFileHeader(), new ClientContextParamsClassSpec(model)); } private String endpointRulesDir() { return generatorTaskParams.getPathProvider().getEndpointRulesDirectory(); } private String endpointRulesInternalDir() { return generatorTaskParams.getPathProvider().getEndpointRulesInternalDirectory(); } private String endpointTestsDir() { return generatorTaskParams.getPathProvider().getEndpointRulesTestDirectory(); } private boolean shouldGenerateEndpointTests() { CustomizationConfig customizationConfig = generatorTaskParams.getModel().getCustomizationConfig(); return !Boolean.TRUE.equals(customizationConfig.isSkipEndpointTestGeneration()) && !generatorTaskParams.getModel().getEndpointTestSuiteModel().getTestCases().isEmpty(); } private boolean shouldGenerateClientEndpointTests() { boolean generateEndpointClientTests = generatorTaskParams.getModel() .getCustomizationConfig() .isGenerateEndpointClientTests(); boolean someTestCasesHaveOperationInputs = model.getEndpointTestSuiteModel().getTestCases().stream() .anyMatch(t -> t.getOperationInputs() != null); return generateEndpointClientTests || someTestCasesHaveOperationInputs; } private boolean hasClientContextParams() { Map<String, ClientContextParam> clientContextParams = model.getClientContextParams(); return clientContextParams != null && !clientContextParams.isEmpty(); } }
3,916
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/emitters/tasks/AwsGeneratorTasks.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.emitters.tasks; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; /** * Generator tasks for AWS style clients. */ public class AwsGeneratorTasks extends CompositeGeneratorTask { public AwsGeneratorTasks(GeneratorTaskParams params) { super(new CommonGeneratorTasks(params), new AsyncClientGeneratorTasks(params), new PaginatorsGeneratorTasks(params), new EventStreamGeneratorTasks(params), new WaitersGeneratorTasks(params), new EndpointProviderTasks(params), new AuthSchemeGeneratorTasks(params)); } }
3,917
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/checksum/HttpChecksum.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.checksum; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Class to map the HttpChecksum trait of an operation. */ @SdkInternalApi public class HttpChecksum { private boolean requestChecksumRequired; private String requestAlgorithmMember; private String requestValidationModeMember; private List<String> responseAlgorithms; public boolean isRequestChecksumRequired() { return requestChecksumRequired; } public void setRequestChecksumRequired(boolean requestChecksumRequired) { this.requestChecksumRequired = requestChecksumRequired; } public String getRequestAlgorithmMember() { return requestAlgorithmMember; } public void setRequestAlgorithmMember(String requestAlgorithmMember) { this.requestAlgorithmMember = requestAlgorithmMember; } public String getRequestValidationModeMember() { return requestValidationModeMember; } public void setRequestValidationModeMember(String requestValidationModeMember) { this.requestValidationModeMember = requestValidationModeMember; } public List<String> getResponseAlgorithms() { return responseAlgorithms; } public void setResponseAlgorithms(List<String> responseAlgorithms) { this.responseAlgorithms = responseAlgorithms; } }
3,918
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/FinalizeNewServiceModuleMain.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.release; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.cli.CommandLine; import org.w3c.dom.Document; import org.w3c.dom.Node; import software.amazon.awssdk.utils.Validate; /** * A command line application to add new services to the shared pom.xml files. * * Example usage: * <pre> * mvn exec:java -pl :release-scripts \ * -Dexec.mainClass="software.amazon.awssdk.release.FinalizeNewServiceModuleMain" \ * -Dexec.args="--maven-project-root /path/to/root * --service-module-names service-module-name-1,service-module-name-2" * </pre> */ public class FinalizeNewServiceModuleMain extends Cli { private FinalizeNewServiceModuleMain() { super(requiredOption("service-module-names", "A comma-separated list containing the name of the service modules to be created."), requiredOption("maven-project-root", "The root directory for the maven project.")); } public static void main(String[] args) { new FinalizeNewServiceModuleMain().run(args); } @Override protected void run(CommandLine commandLine) throws Exception { new NewServiceCreator(commandLine).run(); } private static class NewServiceCreator { private final Path mavenProjectRoot; private final List<String> serviceModuleNames; private NewServiceCreator(CommandLine commandLine) { this.mavenProjectRoot = Paths.get(commandLine.getOptionValue("maven-project-root").trim()); this.serviceModuleNames = Stream.of(commandLine.getOptionValue("service-module-names").split(",")) .map(String::trim) .collect(Collectors.toList()); Validate.isTrue(Files.exists(mavenProjectRoot), "Project root does not exist: " + mavenProjectRoot); } public void run() throws Exception { for (String serviceModuleName : serviceModuleNames) { Path servicesPomPath = mavenProjectRoot.resolve("services").resolve("pom.xml"); Path aggregatePomPath = mavenProjectRoot.resolve("aws-sdk-java").resolve("pom.xml"); Path bomPomPath = mavenProjectRoot.resolve("bom").resolve("pom.xml"); new AddSubmoduleTransformer(serviceModuleName).transform(servicesPomPath); new AddDependencyTransformer(serviceModuleName).transform(aggregatePomPath); new AddDependencyManagementDependencyTransformer(serviceModuleName).transform(bomPomPath); } } private static class AddSubmoduleTransformer extends PomTransformer { private final String serviceModuleName; private AddSubmoduleTransformer(String serviceModuleName) { this.serviceModuleName = serviceModuleName; } @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node modules = findChild(project, "modules"); addChild(modules, textElement(doc, "module", serviceModuleName)); } } private static class AddDependencyTransformer extends PomTransformer { private final String serviceModuleName; private AddDependencyTransformer(String serviceModuleName) { this.serviceModuleName = serviceModuleName; } @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node dependencies = findChild(project, "dependencies"); addChild(dependencies, sdkDependencyElement(doc, serviceModuleName)); } } private static class AddDependencyManagementDependencyTransformer extends PomTransformer { private final String serviceModuleName; private AddDependencyManagementDependencyTransformer(String serviceModuleName) { this.serviceModuleName = serviceModuleName; } @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node dependencyManagement = findChild(project, "dependencyManagement"); Node dependencies = findChild(dependencyManagement, "dependencies"); addChild(dependencies, sdkDependencyElement(doc, serviceModuleName)); } } } }
3,919
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/NewServiceMain.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.release; import static java.nio.charset.StandardCharsets.UTF_8; import static software.amazon.awssdk.release.CreateNewServiceModuleMain.computeInternalDependencies; import static software.amazon.awssdk.release.CreateNewServiceModuleMain.toList; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; /** * A command line application to create a new, empty service. * * Example usage: * <pre> * mvn exec:java -pl :release-scripts \ * -Dexec.mainClass="software.amazon.awssdk.release.NewServiceMain" \ * -Dexec.args="--maven-project-root /path/to/root * --maven-project-version 2.1.4-SNAPSHOT * --service-id 'Service Id' * --service-module-name service-module-name * --service-protocol json" * </pre> */ public class NewServiceMain extends Cli { private static final Set<String> DEFAULT_INTERNAL_DEPENDENCIES = defaultInternalDependencies(); private NewServiceMain() { super(requiredOption("service-module-name", "The name of the service module to be created."), requiredOption("service-id", "The service ID of the service module to be created."), requiredOption("service-protocol", "The protocol of the service module to be created."), requiredOption("maven-project-root", "The root directory for the maven project."), requiredOption("maven-project-version", "The maven version of the service module to be created."), optionalMultiValueOption("include-internal-dependency", "Includes an internal dependency from new service pom."), optionalMultiValueOption("exclude-internal-dependency", "Excludes an internal dependency from new service pom.")); } public static void main(String[] args) { new NewServiceMain().run(args); } private static Set<String> defaultInternalDependencies() { Set<String> defaultInternalDependencies = new LinkedHashSet<>(); defaultInternalDependencies.add("http-auth-aws"); return Collections.unmodifiableSet(defaultInternalDependencies); } @Override protected void run(CommandLine commandLine) throws Exception { new NewServiceCreator(commandLine).run(); } private static class NewServiceCreator { private final Path mavenProjectRoot; private final String mavenProjectVersion; private final String serviceModuleName; private final String serviceId; private final String serviceProtocol; private final Set<String> internalDependencies; private NewServiceCreator(CommandLine commandLine) { this.mavenProjectRoot = Paths.get(commandLine.getOptionValue("maven-project-root").trim()); this.mavenProjectVersion = commandLine.getOptionValue("maven-project-version").trim(); this.serviceModuleName = commandLine.getOptionValue("service-module-name").trim(); this.serviceId = commandLine.getOptionValue("service-id").trim(); this.serviceProtocol = transformSpecialProtocols(commandLine.getOptionValue("service-protocol").trim()); this.internalDependencies = computeInternalDependencies(toList(commandLine .getOptionValues("include-internal-dependency")), toList(commandLine .getOptionValues("exclude-internal-dependency"))); Validate.isTrue(Files.exists(mavenProjectRoot), "Project root does not exist: " + mavenProjectRoot); } private String transformSpecialProtocols(String protocol) { switch (protocol) { case "ec2": return "query"; case "rest-xml": return "xml"; case "rest-json": return "json"; default: return protocol; } } public void run() throws Exception { Path servicesRoot = mavenProjectRoot.resolve("services"); Path templateModulePath = servicesRoot.resolve("new-service-template"); Path newServiceModulePath = servicesRoot.resolve(serviceModuleName); createNewModuleFromTemplate(templateModulePath, newServiceModulePath); replaceTemplatePlaceholders(newServiceModulePath); Path servicesPomPath = mavenProjectRoot.resolve("services").resolve("pom.xml"); Path aggregatePomPath = mavenProjectRoot.resolve("aws-sdk-java").resolve("pom.xml"); Path bomPomPath = mavenProjectRoot.resolve("bom").resolve("pom.xml"); new AddSubmoduleTransformer().transform(servicesPomPath); new AddDependencyTransformer().transform(aggregatePomPath); new AddDependencyManagementDependencyTransformer().transform(bomPomPath); Path newServicePom = newServiceModulePath.resolve("pom.xml"); new CreateNewServiceModuleMain.AddInternalDependenciesTransformer(internalDependencies).transform(newServicePom); } private void createNewModuleFromTemplate(Path templateModulePath, Path newServiceModule) throws IOException { FileUtils.copyDirectory(templateModulePath.toFile(), newServiceModule.toFile()); } private void replaceTemplatePlaceholders(Path newServiceModule) throws IOException { Files.walkFileTree(newServiceModule, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { replacePlaceholdersInFile(file); return FileVisitResult.CONTINUE; } }); } private void replacePlaceholdersInFile(Path file) throws IOException { String fileContents = new String(Files.readAllBytes(file), UTF_8); String newFileContents = replacePlaceholders(fileContents); Files.write(file, newFileContents.getBytes(UTF_8)); } private String replacePlaceholders(String line) { String[] searchList = { "{{MVN_ARTIFACT_ID}}", "{{MVN_NAME}}", "{{MVN_VERSION}}", "{{PROTOCOL}}" }; String[] replaceList = { serviceModuleName, mavenName(serviceId), mavenProjectVersion, serviceProtocol }; return StringUtils.replaceEach(line, searchList, replaceList); } private String mavenName(String serviceId) { return Stream.of(CodegenNamingUtils.splitOnWordBoundaries(serviceId)) .map(StringUtils::capitalize) .collect(Collectors.joining(" ")); } private class AddSubmoduleTransformer extends PomTransformer { @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node modules = findChild(project, "modules"); modules.appendChild(textElement(doc, "module", serviceModuleName)); } } private class AddDependencyTransformer extends PomTransformer { @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node dependencies = findChild(project, "dependencies"); dependencies.appendChild(sdkDependencyElement(doc, serviceModuleName)); } } private class AddDependencyManagementDependencyTransformer extends PomTransformer { @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node dependencyManagement = findChild(project, "dependencyManagement"); Node dependencies = findChild(dependencyManagement, "dependencies"); dependencies.appendChild(sdkDependencyElement(doc, serviceModuleName)); } } } }
3,920
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/UpdateServiceMain.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.release; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * A command line application to update an existing service. * * Example usage: * <pre> mvn exec:java -pl :release-scripts \ -Dexec.mainClass="software.amazon.awssdk.release.UpdateServiceMain" \ -Dexec.args="--maven-project-root /path/to/root --service-module-name service-module-name --service-json /path/to/service-2.json [--paginators-json /path/to/paginators-1.json --waiters-json /path/to/waiters-2.json]" * </pre> */ public class UpdateServiceMain extends Cli { private static final Logger log = Logger.loggerFor(UpdateServiceMain.class); private UpdateServiceMain() { super(requiredOption("service-module-name", "The name of the service module to be created."), requiredOption("service-id", "The service ID of the service to be updated."), requiredOption("maven-project-root", "The root directory for the maven project."), requiredOption("service-json", "The service-2.json file for the service."), optionalOption("paginators-json", "The paginators-1.json file for the service."), optionalOption("waiters-json", "The waiters-2.json file for the service."), optionalOption("endpoint-rule-set-json", "The endpoint-rule-set.json file for the service."), optionalOption("endpoint-tests-json", "The endpoint-tests.json file for the service.")); } public static void main(String[] args) { new UpdateServiceMain().run(args); } @Override protected void run(CommandLine commandLine) throws Exception { new ServiceUpdater(commandLine).run(); } private static class ServiceUpdater { private final String serviceModuleName; private final String serviceId; private final Path mavenProjectRoot; private final Path serviceJson; private final Path paginatorsJson; private final Path waitersJson; private final Path endpointRuleSetJson; private final Path endpointTestsJson; private ServiceUpdater(CommandLine commandLine) { this.mavenProjectRoot = Paths.get(commandLine.getOptionValue("maven-project-root").trim()); this.serviceId = commandLine.getOptionValue("service-id").trim(); this.serviceModuleName = commandLine.getOptionValue("service-module-name").trim(); this.serviceJson = Paths.get(commandLine.getOptionValue("service-json").trim()); this.paginatorsJson = optionalPath(commandLine.getOptionValue("paginators-json")); this.waitersJson = optionalPath(commandLine.getOptionValue("waiters-json")); this.endpointRuleSetJson = optionalPath(commandLine.getOptionValue("endpoint-rule-set-json")); this.endpointTestsJson = optionalPath(commandLine.getOptionValue("endpoint-tests-json")); } private Path optionalPath(String path) { path = StringUtils.trimToNull(path); if (path != null) { return Paths.get(path); } return null; } public void run() throws Exception { Validate.isTrue(Files.isRegularFile(serviceJson), serviceJson + " is not a file."); Path codegenFileLocation = codegenFileLocation(serviceModuleName, serviceId); copyFile(serviceJson, codegenFileLocation.resolve("service-2.json")); copyFile(paginatorsJson, codegenFileLocation.resolve("paginators-1.json")); copyFile(waitersJson, codegenFileLocation.resolve("waiters-2.json")); copyFile(endpointRuleSetJson, codegenFileLocation.resolve("endpoint-rule-set.json")); copyFile(endpointTestsJson, codegenFileLocation.resolve("endpoint-tests.json")); } private Path codegenFileLocation(String serviceModuleName, String serviceId) { Path codegenPath = mavenProjectRoot.resolve("services") .resolve(serviceModuleName) .resolve("src") .resolve("main") .resolve("resources") .resolve("codegen-resources"); switch (serviceId) { case "WAF Regional": return codegenPath.resolve("wafregional"); case "WAF": return codegenPath.resolve("waf"); case "DynamoDB Streams": return codegenPath.resolve("dynamodbstreams"); case "DynamoDB": return codegenPath.resolve("dynamodb"); default: return codegenPath; } } private void copyFile(Path source, Path destination) throws IOException { if (source != null && Files.isRegularFile(source)) { log.info(() -> "Copying " + source + " to " + destination); FileUtils.copyFile(source.toFile(), destination.toFile()); } } } }
3,921
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/CreateNewServiceModuleMain.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.release; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; /** * A command line application to create a new, empty service. This *does not* add the new service to the shared pom.xmls, that * should be done via {@link FinalizeNewServiceModuleMain}. * * Example usage: * <pre> * mvn exec:java -pl :release-scripts \ * -Dexec.mainClass="software.amazon.awssdk.release.CreateNewServiceModuleMain" \ * -Dexec.args="--maven-project-root /path/to/root * --maven-project-version 2.1.4-SNAPSHOT * --service-id 'Service Id' * --service-module-name service-module-name * --service-protocol json" * </pre> * * <p>By default the service new pom will include a dependency to the http-auth-aws module, this is only needed if the service * has one or more operations signed by any of the aws algorithms, e.g., sigv4 or sigv4a, but not needed if the service uses, * say, bearer auth (e.g., codecatalyst at the moment). Excluding this can be done by adding the * {@code --exclude-internal-dependency http-auth-aws} switch. For example * <pre> * mvn exec:java -pl :release-scripts \ * -Dexec.mainClass="software.amazon.awssdk.release.CreateNewServiceModuleMain" \ * -Dexec.args="--maven-project-root /path/to/root * --maven-project-version 2.1.4-SNAPSHOT * --service-id 'Service Id' * --service-module-name service-module-name * --service-protocol json * --exclude-internal-dependency http-auth-aws" * </pre> */ public class CreateNewServiceModuleMain extends Cli { private static final Set<String> DEFAULT_INTERNAL_DEPENDENCIES = toSet("http-auth-aws"); private CreateNewServiceModuleMain() { super(requiredOption("service-module-name", "The name of the service module to be created."), requiredOption("service-id", "The service ID of the service module to be created."), requiredOption("service-protocol", "The protocol of the service module to be created."), requiredOption("maven-project-root", "The root directory for the maven project."), requiredOption("maven-project-version", "The maven version of the service module to be created."), optionalMultiValueOption("include-internal-dependency", "Includes an internal dependency from new service pom."), optionalMultiValueOption("exclude-internal-dependency", "Excludes an internal dependency from new service pom.")); } public static void main(String[] args) { new CreateNewServiceModuleMain().run(args); } static Set<String> toSet(String...args) { Set<String> result = new LinkedHashSet<>(); for (String arg : args) { result.add(arg); } return Collections.unmodifiableSet(result); } static List<String> toList(String[] optionValues) { if (optionValues == null) { return Collections.emptyList(); } return Arrays.asList(optionValues); } static Set<String> computeInternalDependencies(List<String> includes, List<String> excludes) { Set<String> result = new LinkedHashSet<>(DEFAULT_INTERNAL_DEPENDENCIES); result.addAll(includes); excludes.forEach(result::remove); return Collections.unmodifiableSet(result); } @Override protected void run(CommandLine commandLine) throws Exception { new NewServiceCreator(commandLine).run(); } private static class NewServiceCreator { private final Path mavenProjectRoot; private final String mavenProjectVersion; private final String serviceModuleName; private final String serviceId; private final String serviceProtocol; private final Set<String> internalDependencies; private NewServiceCreator(CommandLine commandLine) { this.mavenProjectRoot = Paths.get(commandLine.getOptionValue("maven-project-root").trim()); this.mavenProjectVersion = commandLine.getOptionValue("maven-project-version").trim(); this.serviceModuleName = commandLine.getOptionValue("service-module-name").trim(); this.serviceId = commandLine.getOptionValue("service-id").trim(); this.serviceProtocol = transformSpecialProtocols(commandLine.getOptionValue("service-protocol").trim()); this.internalDependencies = computeInternalDependencies(toList(commandLine .getOptionValues("include-internal-dependency")), toList(commandLine .getOptionValues("exclude-internal-dependency"))); Validate.isTrue(Files.exists(mavenProjectRoot), "Project root does not exist: " + mavenProjectRoot); } private String transformSpecialProtocols(String protocol) { switch (protocol) { case "ec2": return "query"; case "rest-xml": return "xml"; case "rest-json": return "json"; default: return protocol; } } public void run() throws Exception { Path servicesRoot = mavenProjectRoot.resolve("services"); Path templateModulePath = servicesRoot.resolve("new-service-template"); Path newServiceModulePath = servicesRoot.resolve(serviceModuleName); createNewModuleFromTemplate(templateModulePath, newServiceModulePath); replaceTemplatePlaceholders(newServiceModulePath); Path newServicePom = newServiceModulePath.resolve("pom.xml"); new AddInternalDependenciesTransformer(internalDependencies).transform(newServicePom); } private void createNewModuleFromTemplate(Path templateModulePath, Path newServiceModule) throws IOException { FileUtils.copyDirectory(templateModulePath.toFile(), newServiceModule.toFile()); } private void replaceTemplatePlaceholders(Path newServiceModule) throws IOException { Files.walkFileTree(newServiceModule, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { replacePlaceholdersInFile(file); return FileVisitResult.CONTINUE; } }); } private void replacePlaceholdersInFile(Path file) throws IOException { String fileContents = new String(Files.readAllBytes(file), UTF_8); String newFileContents = replacePlaceholders(fileContents); Files.write(file, newFileContents.getBytes(UTF_8)); } private String replacePlaceholders(String line) { String[] searchList = { "{{MVN_ARTIFACT_ID}}", "{{MVN_NAME}}", "{{MVN_VERSION}}", "{{PROTOCOL}}" }; String[] replaceList = { serviceModuleName, mavenName(serviceId), mavenProjectVersion, serviceProtocol }; return StringUtils.replaceEach(line, searchList, replaceList); } private String mavenName(String serviceId) { return Stream.of(CodegenNamingUtils.splitOnWordBoundaries(serviceId)) .map(StringUtils::capitalize) .collect(Collectors.joining(" ")); } } static class AddInternalDependenciesTransformer extends PomTransformer { private final Set<String> internalDependencies; AddInternalDependenciesTransformer(Set<String> internalDependencies) { this.internalDependencies = internalDependencies; } @Override protected void updateDocument(Document doc) { Node project = findChild(doc, "project"); Node dependencies = findChild(project, "dependencies"); for (String internalDependency : internalDependencies) { dependencies.appendChild(sdkDependencyElement(doc, internalDependency)); } } } }
3,922
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/PomTransformer.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.release; import java.nio.file.Path; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public abstract class PomTransformer { public final void transform(Path file) throws Exception { DocumentBuilderFactory docFactory = newSecureDocumentBuilderFactory(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file.toFile()); doc.normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } updateDocument(doc); TransformerFactory transformerFactory = newSecureTransformerFactory(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); } protected abstract void updateDocument(Document doc); protected final Node findChild(Node parent, String childName) { NodeList children = parent.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); if (childName.equals(child.getNodeName()) && child.getNodeType() == Node.ELEMENT_NODE) { return child; } } throw new IllegalArgumentException(parent + " has no child element named " + childName); } protected final void addChild(Node parent, Element childToAdd) { NodeList children = parent.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { Node existingChild = children.item(i); if (existingChild.isEqualNode(childToAdd)) { // Child already exists, skip. return; } } parent.appendChild(childToAdd); } protected final Element textElement(Document doc, String name, String value) { Element element = doc.createElement(name); element.setTextContent(value); return element; } protected final Element sdkDependencyElement(Document doc, String artifactId) { Element newDependency = doc.createElement("dependency"); newDependency.appendChild(textElement(doc, "groupId", "software.amazon.awssdk")); newDependency.appendChild(textElement(doc, "artifactId", artifactId)); newDependency.appendChild(textElement(doc, "version", "${awsjavasdk.version}")); return newDependency; } private DocumentBuilderFactory newSecureDocumentBuilderFactory() { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setXIncludeAware(false); docFactory.setExpandEntityReferences(false); trySetFeature(docFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true); trySetFeature(docFactory, "http://apache.org/xml/features/disallow-doctype-decl", true); trySetFeature(docFactory, "http://xml.org/sax/features/external-general-entities", false); trySetFeature(docFactory, "http://xml.org/sax/features/external-parameter-entities", false); trySetAttribute(docFactory, "http://javax.xml.XMLConstants/property/accessExternalDTD", ""); trySetAttribute(docFactory, "http://javax.xml.XMLConstants/property/accessExternalSchema", ""); return docFactory; } private TransformerFactory newSecureTransformerFactory() { TransformerFactory transformerFactory = TransformerFactory.newInstance(); trySetAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_DTD, ""); trySetAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); return transformerFactory; } private void trySetFeature(DocumentBuilderFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } private void trySetAttribute(DocumentBuilderFactory factory, String feature, String value) { try { factory.setAttribute(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } private void trySetAttribute(TransformerFactory factory, String feature, Object value) { try { factory.setAttribute(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } }
3,923
0
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/release-scripts/src/main/java/software/amazon/awssdk/release/Cli.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.release; import java.util.stream.Stream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import software.amazon.awssdk.utils.Logger; public abstract class Cli { private final Logger log = Logger.loggerFor(Cli.class); private final Option[] optionsToAdd; public Cli(Option... optionsToAdd) { this.optionsToAdd = optionsToAdd; } public final void run(String[] args) { Options options = new Options(); Stream.of(optionsToAdd).forEach(options::addOption); CommandLineParser parser = new DefaultParser(); HelpFormatter help = new HelpFormatter(); try { CommandLine commandLine = parser.parse(options, args); run(commandLine); } catch (ParseException e) { log.error(() -> "Invalid input: " + e.getMessage()); help.printHelp(getClass().getSimpleName(), options); throw new Error(); } catch (Exception e) { log.error(() -> "Script execution failed.", e); throw new Error(); } } protected static Option requiredOption(String longCommand, String description) { Option option = optionalOption(longCommand, description); option.setRequired(true); return option; } protected static Option optionalOption(String longCommand, String description) { return new Option(null, longCommand, true, description); } protected static Option optionalMultiValueOption(String longCommand, String description) { return Option.builder() .longOpt(longCommand) .desc(description) .hasArgs() .build(); } protected abstract void run(CommandLine commandLine) throws Exception; }
3,924
0
Create_ds/aws-sdk-java-v2/codegen-lite-maven-plugin/src/main/java/software/amazon/awssdk/codegen/lite/maven
Create_ds/aws-sdk-java-v2/codegen-lite-maven-plugin/src/main/java/software/amazon/awssdk/codegen/lite/maven/plugin/DefaultsModeGenerationMojo.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.maven.plugin; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import software.amazon.awssdk.codegen.lite.CodeGenerator; import software.amazon.awssdk.codegen.lite.defaultsmode.DefaultConfiguration; import software.amazon.awssdk.codegen.lite.defaultsmode.DefaultsLoader; import software.amazon.awssdk.codegen.lite.defaultsmode.DefaultsModeConfigurationGenerator; import software.amazon.awssdk.codegen.lite.defaultsmode.DefaultsModeGenerator; import software.amazon.awssdk.utils.StringUtils; /** * The Maven mojo to generate defaults mode related classes. */ @Mojo(name = "generate-defaults-mode") public class DefaultsModeGenerationMojo extends AbstractMojo { private static final String DEFAULTS_MODE_BASE = "software.amazon.awssdk.awscore.defaultsmode"; private static final String DEFAULTS_MODE_CONFIGURATION_BASE = "software.amazon.awssdk.awscore.internal.defaultsmode"; @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}") private String outputDirectory; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @Parameter(property = "defaultConfigurationFile", defaultValue = "${basedir}/src/main/resources/software/amazon/awssdk/awscore/internal/defaults/sdk-default-configuration.json") private File defaultConfigurationFile; public void execute() { Path baseSourcesDirectory = Paths.get(outputDirectory).resolve("generated-sources").resolve("sdk"); Path testsDirectory = Paths.get(outputDirectory).resolve("generated-test-sources").resolve("sdk-tests"); DefaultConfiguration configuration = DefaultsLoader.load(defaultConfigurationFile); generateDefaultsModeClass(baseSourcesDirectory, configuration); generateDefaultsModeConfiguartionClass(baseSourcesDirectory, configuration); project.addCompileSourceRoot(baseSourcesDirectory.toFile().getAbsolutePath()); project.addTestCompileSourceRoot(testsDirectory.toFile().getAbsolutePath()); } public void generateDefaultsModeClass(Path baseSourcesDirectory, DefaultConfiguration configuration) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(DEFAULTS_MODE_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new DefaultsModeGenerator(DEFAULTS_MODE_BASE, configuration)).generate(); } public void generateDefaultsModeConfiguartionClass(Path baseSourcesDirectory, DefaultConfiguration configuration) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(DEFAULTS_MODE_CONFIGURATION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new DefaultsModeConfigurationGenerator(DEFAULTS_MODE_CONFIGURATION_BASE, DEFAULTS_MODE_BASE, configuration)).generate(); } }
3,925
0
Create_ds/aws-sdk-java-v2/codegen-lite-maven-plugin/src/main/java/software/amazon/awssdk/codegen/lite/maven
Create_ds/aws-sdk-java-v2/codegen-lite-maven-plugin/src/main/java/software/amazon/awssdk/codegen/lite/maven/plugin/RegionGenerationMojo.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.maven.plugin; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import software.amazon.awssdk.codegen.lite.CodeGenerator; import software.amazon.awssdk.codegen.lite.regions.EndpointTagGenerator; import software.amazon.awssdk.codegen.lite.regions.PartitionMetadataGenerator; import software.amazon.awssdk.codegen.lite.regions.PartitionMetadataProviderGenerator; import software.amazon.awssdk.codegen.lite.regions.RegionGenerator; import software.amazon.awssdk.codegen.lite.regions.RegionMetadataGenerator; import software.amazon.awssdk.codegen.lite.regions.RegionMetadataLoader; import software.amazon.awssdk.codegen.lite.regions.RegionMetadataProviderGenerator; import software.amazon.awssdk.codegen.lite.regions.ServiceMetadataGenerator; import software.amazon.awssdk.codegen.lite.regions.ServiceMetadataProviderGenerator; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.StringUtils; /** * The Maven mojo to generate Java client code using software.amazon.awssdk:codegen module. */ @Mojo(name = "generate-regions") public class RegionGenerationMojo extends AbstractMojo { private static final String PARTITION_METADATA_BASE = "software.amazon.awssdk.regions.partitionmetadata"; 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 REGION_BASE = "software.amazon.awssdk.regions"; @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}") private String outputDirectory; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @Parameter(property = "endpoints", defaultValue = "${basedir}/src/main/resources/software/amazon/awssdk/regions/internal/region/endpoints.json") private File endpoints; @Override public void execute() throws MojoExecutionException { Path baseSourcesDirectory = Paths.get(outputDirectory).resolve("generated-sources").resolve("sdk"); Path testsDirectory = Paths.get(outputDirectory).resolve("generated-test-sources").resolve("sdk-tests"); Partitions partitions = RegionMetadataLoader.build(endpoints); generatePartitionMetadataClass(baseSourcesDirectory, partitions); generateRegionClass(baseSourcesDirectory, partitions); generateServiceMetadata(baseSourcesDirectory, partitions); generateRegions(baseSourcesDirectory, partitions); generatePartitionProvider(baseSourcesDirectory, partitions); generateRegionProvider(baseSourcesDirectory, partitions); generateServiceProvider(baseSourcesDirectory, partitions); generateEndpointTags(baseSourcesDirectory, partitions); project.addCompileSourceRoot(baseSourcesDirectory.toFile().getAbsolutePath()); project.addTestCompileSourceRoot(testsDirectory.toFile().getAbsolutePath()); } public void generatePartitionMetadataClass(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(PARTITION_METADATA_BASE, ".", "/")); partitions.getPartitions() .forEach(p -> new CodeGenerator(sourcesDirectory.toString(), new PartitionMetadataGenerator(p, PARTITION_METADATA_BASE, REGION_BASE)).generate()); } public void generateRegionClass(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new RegionGenerator(partitions, REGION_BASE)).generate(); } public void generateServiceMetadata(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(SERVICE_METADATA_BASE, ".", "/")); Set<String> services = new HashSet<>(); partitions.getPartitions().forEach(p -> services.addAll(p.getServices().keySet())); services.forEach(s -> new CodeGenerator(sourcesDirectory.toString(), new ServiceMetadataGenerator(partitions, s, SERVICE_METADATA_BASE, REGION_BASE)) .generate()); } public void generateRegions(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_METADATA_BASE, ".", "/")); partitions.getPartitions() .forEach(p -> p.getRegions().forEach((k, v) -> new CodeGenerator(sourcesDirectory.toString(), new RegionMetadataGenerator(p, k, v.getDescription(), REGION_METADATA_BASE, REGION_BASE)) .generate())); } public void generatePartitionProvider(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new PartitionMetadataProviderGenerator(partitions, PARTITION_METADATA_BASE, REGION_BASE)) .generate(); } public void generateRegionProvider(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new RegionMetadataProviderGenerator(partitions, REGION_METADATA_BASE, REGION_BASE)) .generate(); } public void generateServiceProvider(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new ServiceMetadataProviderGenerator(partitions, SERVICE_METADATA_BASE, REGION_BASE)) .generate(); } public void generateEndpointTags(Path baseSourcesDirectory, Partitions partitions) { Path sourcesDirectory = baseSourcesDirectory.resolve(StringUtils.replace(REGION_BASE, ".", "/")); new CodeGenerator(sourcesDirectory.toString(), new EndpointTagGenerator(partitions, REGION_BASE)).generate(); } }
3,926
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamConditionOperatorTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamConditionOperatorTest { @Test public void iamConditionOperatorValueNotNull() { assertThatThrownBy(() -> IamConditionOperator.create(null)).hasMessageMatching(".*[Cc]ondition.*[Oo]perator.*"); } }
3,927
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamStatementTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.policybuilder.iam.IamEffect.ALLOW; import java.util.function.Consumer; import org.junit.jupiter.api.Test; class IamStatementTest { private static final IamPrincipal PRINCIPAL_1 = IamPrincipal.create("1", "*"); private static final IamPrincipal PRINCIPAL_2 = IamPrincipal.create("2", "*"); private static final IamResource RESOURCE_1 = IamResource.create("1"); private static final IamResource RESOURCE_2 = IamResource.create("2"); private static final IamAction ACTION_1 = IamAction.create("1"); private static final IamAction ACTION_2 = IamAction.create("2"); private static final IamCondition CONDITION_1 = IamCondition.create("1", "K", "V"); private static final IamCondition CONDITION_2 = IamCondition.create("2", "K", "V"); private static final IamStatement FULL_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(singletonList(PRINCIPAL_1)) .notPrincipals(singletonList(PRINCIPAL_2)) .resources(singletonList(RESOURCE_1)) .notResources(singletonList(RESOURCE_2)) .actions(singletonList(ACTION_1)) .notActions(singletonList(ACTION_2)) .conditions(singletonList(CONDITION_1)) .build(); @Test public void simpleGettersSettersWork() { assertThat(FULL_STATEMENT.sid()).isEqualTo("Sid"); assertThat(FULL_STATEMENT.effect()).isEqualTo(ALLOW); assertThat(FULL_STATEMENT.principals()).containsExactly(PRINCIPAL_1); assertThat(FULL_STATEMENT.notPrincipals()).containsExactly(PRINCIPAL_2); assertThat(FULL_STATEMENT.resources()).containsExactly(RESOURCE_1); assertThat(FULL_STATEMENT.notResources()).containsExactly(RESOURCE_2); assertThat(FULL_STATEMENT.actions()).containsExactly(ACTION_1); assertThat(FULL_STATEMENT.notActions()).containsExactly(ACTION_2); assertThat(FULL_STATEMENT.conditions()).containsExactly(CONDITION_1); } @Test public void toBuilderPreservesValues() { assertThat(FULL_STATEMENT.toBuilder().build()).isEqualTo(FULL_STATEMENT); } @Test public void toStringIncludesAllValues() { assertThat(FULL_STATEMENT.toString()) .isEqualTo("IamStatement(" + "sid=Sid, " + "effect=IamEffect(value=Allow), " + "principals=[IamPrincipal(type=1, id=*)], " + "notPrincipals=[IamPrincipal(type=2, id=*)], " + "actions=[IamAction(value=1)], " + "notActions=[IamAction(value=2)], " + "resources=[IamResource(value=1)], " + "notResources=[IamResource(value=2)], " + "conditions=[IamCondition(operator=1, key=K, value=V)])"); } @Test public void effectIsRequired() { assertThatThrownBy(() -> IamStatement.builder().build()).hasMessageMatching(".*[Ee]ffect.*"); } @Test public void effectGettersSettersWork() { assertThat(statement(s -> s.effect(ALLOW)).effect()).isEqualTo(ALLOW); assertThat(statement(s -> s.effect("Allow")).effect()).isEqualTo(ALLOW); } @Test public void principalGettersSettersWork() { assertThat(statement(s -> s.principals(asList(PRINCIPAL_1, PRINCIPAL_2))).principals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addPrincipal(PRINCIPAL_1) .addPrincipal(PRINCIPAL_2)).principals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addPrincipal(p -> p.type("1").id("*")) .addPrincipal(p -> p.type("2").id("*"))).principals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addPrincipal("1", "*") .addPrincipal("2", "*")).principals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addPrincipal(IamPrincipalType.create("1"), "*") .addPrincipal(IamPrincipalType.create("2"), "*")).principals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addPrincipals(IamPrincipalType.create("1"), asList("x", "y"))).principals()) .containsExactly(IamPrincipal.create("1", "x"), IamPrincipal.create("1", "y")); assertThat(statement(s -> s.addPrincipals("1", asList("x", "y"))).principals()) .containsExactly(IamPrincipal.create("1", "x"), IamPrincipal.create("1", "y")); } @Test public void principalsCollectionSettersResetsList() { assertThat(statement(s -> s.principals(asList(PRINCIPAL_1, PRINCIPAL_2)) .principals(singletonList(PRINCIPAL_1))).principals()) .containsExactly(PRINCIPAL_1); } @Test public void notPrincipalGettersSettersWork() { assertThat(statement(s -> s.notPrincipals(asList(PRINCIPAL_1, PRINCIPAL_2))).notPrincipals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addNotPrincipal(PRINCIPAL_1) .addNotPrincipal(PRINCIPAL_2)).notPrincipals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addNotPrincipal(p -> p.type("1").id("*")) .addNotPrincipal(p -> p.type("2").id("*"))).notPrincipals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addNotPrincipal("1", "*") .addNotPrincipal("2", "*")).notPrincipals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addNotPrincipal(IamPrincipalType.create("1"), "*") .addNotPrincipal(IamPrincipalType.create("2"), "*")).notPrincipals()) .containsExactly(PRINCIPAL_1, PRINCIPAL_2); assertThat(statement(s -> s.addNotPrincipals(IamPrincipalType.create("1"), asList("x", "y"))).notPrincipals()) .containsExactly(IamPrincipal.create("1", "x"), IamPrincipal.create("1", "y")); assertThat(statement(s -> s.addNotPrincipals("1", asList("x", "y"))).notPrincipals()) .containsExactly(IamPrincipal.create("1", "x"), IamPrincipal.create("1", "y")); } @Test public void notPrincipalsCollectionSettersResetsList() { assertThat(statement(s -> s.notPrincipals(asList(PRINCIPAL_1, PRINCIPAL_2)) .notPrincipals(singletonList(PRINCIPAL_1))).notPrincipals()) .containsExactly(PRINCIPAL_1); } @Test public void actionGettersSettersWork() { assertThat(statement(s -> s.actions(asList(ACTION_1, ACTION_2))).actions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.actionIds(asList("1", "2"))).actions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.addAction(ACTION_1).addAction(ACTION_2)).actions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.addAction("1").addAction("2")).actions()) .containsExactly(ACTION_1, ACTION_2); } @Test public void actionCollectionSettersResetsList() { assertThat(statement(s -> s.actions(asList(ACTION_1, ACTION_2)) .actions(singletonList(ACTION_2))).actions()) .containsExactly(ACTION_2); } @Test public void notActionGettersSettersWork() { assertThat(statement(s -> s.notActions(asList(ACTION_1, ACTION_2))).notActions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.notActionIds(asList("1", "2"))).notActions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.addNotAction(ACTION_1).addNotAction(ACTION_2)).notActions()) .containsExactly(ACTION_1, ACTION_2); assertThat(statement(s -> s.addNotAction("1").addNotAction("2")).notActions()) .containsExactly(ACTION_1, ACTION_2); } @Test public void notActionCollectionSettersResetsList() { assertThat(statement(s -> s.notActions(asList(ACTION_1, ACTION_2)) .notActions(singletonList(ACTION_2))).notActions()) .containsExactly(ACTION_2); } @Test public void resourceGettersSettersWork() { assertThat(statement(s -> s.resources(asList(RESOURCE_1, RESOURCE_2))).resources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.resourceIds(asList("1", "2"))).resources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.addResource(RESOURCE_1).addResource(RESOURCE_2)).resources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.addResource("1").addResource("2")).resources()) .containsExactly(RESOURCE_1, RESOURCE_2); } @Test public void resourceCollectionSettersResetsList() { assertThat(statement(s -> s.resources(asList(RESOURCE_1, RESOURCE_2)) .resources(singletonList(RESOURCE_2))).resources()) .containsExactly(RESOURCE_2); } @Test public void notResourceGettersSettersWork() { assertThat(statement(s -> s.notResources(asList(RESOURCE_1, RESOURCE_2))).notResources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.notResourceIds(asList("1", "2"))).notResources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.addNotResource(RESOURCE_1).addNotResource(RESOURCE_2)).notResources()) .containsExactly(RESOURCE_1, RESOURCE_2); assertThat(statement(s -> s.addNotResource("1").addNotResource("2")).notResources()) .containsExactly(RESOURCE_1, RESOURCE_2); } @Test public void notResourceCollectionSettersResetsList() { assertThat(statement(s -> s.notResources(asList(RESOURCE_1, RESOURCE_2)) .notResources(singletonList(RESOURCE_2))).notResources()) .containsExactly(RESOURCE_2); } @Test public void conditionGettersSettersWork() { assertThat(statement(s -> s.conditions(asList(CONDITION_1, CONDITION_2))).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addCondition(CONDITION_1) .addCondition(CONDITION_2)).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addCondition(p -> p.operator("1").key("K").value("V")) .addCondition(p -> p.operator("2").key("K").value("V"))).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addCondition(IamConditionOperator.create("1"), IamConditionKey.create("K"), "V") .addCondition(IamConditionOperator.create("2"), IamConditionKey.create("K"), "V")).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addCondition(IamConditionOperator.create("1"), "K", "V") .addCondition(IamConditionOperator.create("2"), "K", "V")).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addCondition("1", "K", "V") .addCondition("2", "K", "V")).conditions()) .containsExactly(CONDITION_1, CONDITION_2); assertThat(statement(s -> s.addConditions(IamConditionOperator.create("1"), IamConditionKey.create("K"), asList("V1", "V2"))).conditions()) .containsExactly(IamCondition.create("1", "K", "V1"), IamCondition.create("1", "K", "V2")); assertThat(statement(s -> s.addConditions(IamConditionOperator.create("1"), "K", asList("V1", "V2"))).conditions()) .containsExactly(IamCondition.create("1", "K", "V1"), IamCondition.create("1", "K", "V2")); assertThat(statement(s -> s.addConditions("1", "K", asList("V1", "V2"))).conditions()) .containsExactly(IamCondition.create("1", "K", "V1"), IamCondition.create("1", "K", "V2")); } @Test public void conditionsCollectionSettersResetsList() { assertThat(statement(s -> s.conditions(asList(CONDITION_1, CONDITION_1)) .conditions(singletonList(CONDITION_1))).conditions()) .containsExactly(CONDITION_1); } private IamStatement statement(Consumer<IamStatement.Builder> statement) { return IamStatement.builder().effect(ALLOW).applyMutation(statement).build(); } }
3,928
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamConditionTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import java.util.function.Consumer; import org.junit.jupiter.api.Test; class IamConditionTest { private static final IamCondition FULL_CONDITION = IamCondition.builder() .operator("Operator") .key("Key") .value("Value") // TODO: Id? .build(); @Test public void constructorsWork() { assertThat(IamCondition.create("Operator", "Key", "Value")).isEqualTo(FULL_CONDITION); assertThat(IamCondition.create(IamConditionOperator.create("Operator"), IamConditionKey.create("Key"), "Value")) .isEqualTo(FULL_CONDITION); assertThat(IamCondition.create(IamConditionOperator.create("Operator"), "Key", "Value")) .isEqualTo(FULL_CONDITION); assertThat(IamCondition.createAll("Operator", "Key", asList("Value1", "Value2"))) .containsExactly(IamCondition.create("Operator", "Key", "Value1"), IamCondition.create("Operator", "Key", "Value2")); assertThat(IamCondition.createAll(IamConditionOperator.create("Operator"), "Key", asList("Value1", "Value2"))) .containsExactly(IamCondition.create("Operator", "Key", "Value1"), IamCondition.create("Operator", "Key", "Value2")); assertThat(IamCondition.createAll(IamConditionOperator.create("Operator"), IamConditionKey.create("Key"), asList("Value1", "Value2"))) .containsExactly(IamCondition.create("Operator", "Key", "Value1"), IamCondition.create("Operator", "Key", "Value2")); } @Test public void simpleGettersSettersWork() { assertThat(FULL_CONDITION.operator().value()).isEqualTo("Operator"); assertThat(FULL_CONDITION.key().value()).isEqualTo("Key"); assertThat(FULL_CONDITION.value()).isEqualTo("Value"); } @Test public void toBuilderPreservesValues() { assertThat(FULL_CONDITION.toBuilder().build()).isEqualTo(FULL_CONDITION); } @Test public void operatorSettersWork() { assertThat(condition(c -> c.operator("Operator")).operator().value()).isEqualTo("Operator"); assertThat(condition(c -> c.operator(IamConditionOperator.create("Operator"))).operator().value()).isEqualTo("Operator"); } @Test public void keySettersWork() { assertThat(condition(c -> c.key("Key")).key().value()).isEqualTo("Key"); assertThat(condition(c -> c.key(IamConditionKey.create("Key"))).key().value()).isEqualTo("Key"); } public IamCondition condition(Consumer<IamCondition.Builder> condition) { return IamCondition.builder() .operator("Operator") .key("Key") .value("Value") .applyMutation(condition) .build(); } }
3,929
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamPrincipalTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; class IamPrincipalTest { private static final IamPrincipal FULL_PRINCIPAL = IamPrincipal.builder() .type("Type") .id("Id") .build(); @Test public void constructorsWork() { assertThat(IamPrincipal.create("Type", "Id")).isEqualTo(FULL_PRINCIPAL); assertThat(IamPrincipal.create(IamPrincipalType.create("Type"), "Id")).isEqualTo(FULL_PRINCIPAL); assertThat(IamPrincipal.createAll("Type", asList("Id1", "Id2"))) .containsExactly(IamPrincipal.create("Type", "Id1"), IamPrincipal.create("Type", "Id2")); assertThat(IamPrincipal.createAll(IamPrincipalType.create("Type"), asList("Id1", "Id2"))) .containsExactly(IamPrincipal.create("Type", "Id1"), IamPrincipal.create("Type", "Id2")); } @Test public void simpleGettersSettersWork() { assertThat(FULL_PRINCIPAL.id()).isEqualTo("Id"); assertThat(FULL_PRINCIPAL.type().value()).isEqualTo("Type"); } @Test public void toBuilderPreservesValues() { IamPrincipal principal = FULL_PRINCIPAL.toBuilder().build(); assertThat(principal.id()).isEqualTo("Id"); assertThat(principal.type().value()).isEqualTo("Type"); } @Test public void typeSettersWork() { assertThat(IamPrincipal.builder().type("Type").id("Id").build().type().value()).isEqualTo("Type"); assertThat(IamPrincipal.builder().type(IamPrincipalType.create("Type")).id("Id").build().type().value()).isEqualTo("Type"); } }
3,930
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamResourceTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamResourceTest { @Test public void iamResourceValueNotNull() { assertThatThrownBy(() -> IamResource.create(null)).hasMessageMatching(".*[Rr]esource.*"); } }
3,931
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/EqualsHashCodeTest.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.policybuilder.iam; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class EqualsHashCodeTest { @Test public void allClasses_equalsHashCode_isCorrect() { EqualsVerifier.forPackage("software.amazon.awssdk.policybuilder.iam", true) .except(c -> c.isMemberClass() || c.isAnonymousClass()) .verify(); } }
3,932
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamConditionKeyTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamConditionKeyTest { @Test public void iamConditionKeyValueNotNull() { assertThatThrownBy(() -> IamConditionKey.create(null)).hasMessageMatching(".*[Cc]ondition.*[Kk]ey.*"); } }
3,933
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamActionTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamActionTest { @Test public void iamActionValueNotNull() { assertThatThrownBy(() -> IamAction.create(null)).hasMessageMatching(".*[Aa]ction.*"); } }
3,934
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamEffectTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamEffectTest { @Test public void iamEffectValueNotNull() { assertThatThrownBy(() -> IamEffect.create(null)).hasMessageMatching(".*[Ee]ffect.*"); } }
3,935
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamPolicyTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.policybuilder.iam.IamEffect.ALLOW; import static software.amazon.awssdk.policybuilder.iam.IamEffect.DENY; import java.util.function.Consumer; import org.junit.jupiter.api.Test; class IamPolicyTest { private static final IamStatement ALLOW_STATEMENT = IamStatement.builder().effect(ALLOW).build(); private static final IamStatement DENY_STATEMENT = IamStatement.builder().effect(DENY).build(); private static final String SMALLEST_POLICY_JSON = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\"}}"; private static final IamPolicy SMALLEST_POLICY = IamPolicy.builder().addStatement(ALLOW_STATEMENT).build(); private static final IamPolicy FULL_POLICY = IamPolicy.builder() .id("Id") .version("Version") .statements(singletonList(ALLOW_STATEMENT)) .build(); @Test public void fromJson_delegatesToIamPolicyReader() { IamPolicy iamPolicy = IamPolicy.fromJson(SMALLEST_POLICY_JSON); assertThat(iamPolicy.version()).isNotNull(); assertThat(iamPolicy.statements()).containsExactly(ALLOW_STATEMENT); } @Test public void toJson_delegatesToIamPolicyWriter() { assertThat(SMALLEST_POLICY.toJson()).isEqualTo(SMALLEST_POLICY_JSON); } @Test public void simpleGettersSettersWork() { assertThat(FULL_POLICY.id()).isEqualTo("Id"); assertThat(FULL_POLICY.version()).isEqualTo("Version"); assertThat(FULL_POLICY.statements()).containsExactly(ALLOW_STATEMENT); } @Test public void toBuilderPreservesValues() { assertThat(FULL_POLICY.toBuilder().build()).isEqualTo(FULL_POLICY); } @Test public void toStringIncludesAllValues() { assertThat(FULL_POLICY.toString()) .isEqualTo("IamPolicy(id=Id, version=Version, statements=[IamStatement(effect=IamEffect(value=Allow))])"); } @Test public void statementGettersSettersWork() { assertThat(policy(p -> p.statements(asList(ALLOW_STATEMENT, DENY_STATEMENT))).statements()) .containsExactly(ALLOW_STATEMENT, DENY_STATEMENT); assertThat(policy(p -> p.addStatement(ALLOW_STATEMENT).addStatement(DENY_STATEMENT)).statements()) .containsExactly(ALLOW_STATEMENT, DENY_STATEMENT); assertThat(policy(p -> p.addStatement(s -> s.effect(ALLOW)).addStatement(s -> s.effect(DENY))).statements()) .containsExactly(ALLOW_STATEMENT, DENY_STATEMENT); } @Test public void statementCollectionSettersResetsList() { assertThat(policy(p -> p.statements(asList(ALLOW_STATEMENT, DENY_STATEMENT)) .statements(singletonList(DENY_STATEMENT))).statements()) .containsExactly(DENY_STATEMENT); } private IamPolicy policy(Consumer<IamPolicy.Builder> policy) { return IamPolicy.builder().applyMutation(policy).build(); } }
3,936
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamPolicyReaderTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.policybuilder.iam.IamEffect.ALLOW; import org.junit.jupiter.api.Test; class IamPolicyReaderTest { private static final IamPrincipal PRINCIPAL_1 = IamPrincipal.create("P1", "*"); private static final IamPrincipal PRINCIPAL_1B = IamPrincipal.create("P1", "B"); private static final IamPrincipal PRINCIPAL_2 = IamPrincipal.create("P2", "*"); private static final IamPrincipal NOT_PRINCIPAL_1 = IamPrincipal.create("NP1", "*"); private static final IamPrincipal NOT_PRINCIPAL_1B = IamPrincipal.create("NP1", "B"); private static final IamPrincipal NOT_PRINCIPAL_2 = IamPrincipal.create("NP2", "*"); private static final IamResource RESOURCE_1 = IamResource.create("R1"); private static final IamResource RESOURCE_2 = IamResource.create("R2"); private static final IamResource NOT_RESOURCE_1 = IamResource.create("NR1"); private static final IamResource NOT_RESOURCE_2 = IamResource.create("NR2"); private static final IamAction ACTION_1 = IamAction.create("A1"); private static final IamAction ACTION_2 = IamAction.create("A2"); private static final IamAction NOT_ACTION_1 = IamAction.create("NA1"); private static final IamAction NOT_ACTION_2 = IamAction.create("NA2"); private static final IamCondition CONDITION_1 = IamCondition.create("1", "K1", "V1"); private static final IamCondition CONDITION_2 = IamCondition.create("1", "K2", "V1"); private static final IamCondition CONDITION_3 = IamCondition.create("1", "K2", "V2"); private static final IamCondition CONDITION_4 = IamCondition.create("2", "K1", "V1"); private static final IamStatement FULL_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(asList(PRINCIPAL_1, PRINCIPAL_2)) .notPrincipals(asList(NOT_PRINCIPAL_1, NOT_PRINCIPAL_2)) .resources(asList(RESOURCE_1, RESOURCE_2)) .notResources(asList(NOT_RESOURCE_1, NOT_RESOURCE_2)) .actions(asList(ACTION_1, ACTION_2)) .notActions(asList(NOT_ACTION_1, NOT_ACTION_2)) .conditions(asList(CONDITION_1, CONDITION_2, CONDITION_3, CONDITION_4)) .build(); private static final IamPolicy FULL_POLICY = IamPolicy.builder() .id("Id") .version("Version") .statements(asList(FULL_STATEMENT, FULL_STATEMENT)) .build(); private static final IamStatement MINIMAL_STATEMENT = IamStatement.builder().effect(ALLOW).build(); private static final IamPolicy MINIMAL_POLICY = IamPolicy.builder() .version("Version") .statements(singletonList(MINIMAL_STATEMENT)) .build(); private static final IamStatement ONE_ELEMENT_LISTS_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(singletonList(IamPrincipal.ALL)) .notPrincipals(singletonList(IamPrincipal.ALL)) .resources(singletonList(RESOURCE_1)) .notResources(singletonList(NOT_RESOURCE_1)) .actions(singletonList(ACTION_1)) .notActions(singletonList(NOT_ACTION_1)) .conditions(singletonList(CONDITION_1)) .build(); private static final IamPolicy ONE_ELEMENT_LISTS_POLICY = IamPolicy.builder() .version("Version") .statements(singletonList(ONE_ELEMENT_LISTS_STATEMENT)) .build(); private static final IamStatement COMPOUND_PRINCIPAL_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(asList(PRINCIPAL_1, PRINCIPAL_1B)) .notPrincipals(asList(NOT_PRINCIPAL_1, NOT_PRINCIPAL_1B)) .build(); private static final IamPolicy COMPOUND_PRINCIPAL_POLICY = IamPolicy.builder() .version("Version") .statements(singletonList(COMPOUND_PRINCIPAL_STATEMENT)) .build(); private static final IamPolicyReader READER = IamPolicyReader.create(); @Test public void readFullPolicyWorks() { assertThat(READER.read("{\n" + " \"Version\" : \"Version\",\n" + " \"Id\" : \"Id\",\n" + " \"Statement\" : [ {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : {\n" + " \"P1\" : \"*\",\n" + " \"P2\" : \"*\"\n" + " },\n" + " \"NotPrincipal\" : {\n" + " \"NP1\" : \"*\",\n" + " \"NP2\" : \"*\"\n" + " },\n" + " \"Action\" : [ \"A1\", \"A2\" ],\n" + " \"NotAction\" : [ \"NA1\", \"NA2\" ],\n" + " \"Resource\" : [ \"R1\", \"R2\" ],\n" + " \"NotResource\" : [ \"NR1\", \"NR2\" ],\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\",\n" + " \"K2\" : [ \"V1\", \"V2\" ]\n" + " },\n" + " \"2\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " }, {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : {\n" + " \"P1\" : \"*\",\n" + " \"P2\" : \"*\"\n" + " },\n" + " \"NotPrincipal\" : {\n" + " \"NP1\" : \"*\",\n" + " \"NP2\" : \"*\"\n" + " },\n" + " \"Action\" : [ \"A1\", \"A2\" ],\n" + " \"NotAction\" : [ \"NA1\", \"NA2\" ],\n" + " \"Resource\" : [ \"R1\", \"R2\" ],\n" + " \"NotResource\" : [ \"NR1\", \"NR2\" ],\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\",\n" + " \"K2\" : [ \"V1\", \"V2\" ]\n" + " },\n" + " \"2\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " } ]\n" + "}")) .isEqualTo(FULL_POLICY); } @Test public void readMinimalPolicyWorks() { assertThat(READER.read("{\n" + " \"Version\" : \"Version\",\n" + " \"Statement\" : {\n" + " \"Effect\" : \"Allow\"\n" + " }\n" + "}")) .isEqualTo(MINIMAL_POLICY); } @Test public void readCompoundPrincipalsWorks() { assertThat(READER.read("{\n" + " \"Version\": \"Version\",\n" + " \"Statement\": [\n" + " {\n" + " \"Sid\": \"Sid\",\n" + " \"Effect\": \"Allow\",\n" + " \"Principal\": {\n" + " \"P1\": [\n" + " \"*\",\n" + " \"B\"\n" + " ]\n" + " },\n" + " \"NotPrincipal\": {\n" + " \"NP1\": [\n" + " \"*\",\n" + " \"B\"\n" + " ]\n" + " }\n" + " }\n" + " ]\n" + "}")).isEqualTo(COMPOUND_PRINCIPAL_POLICY); } @Test public void singleElementListsAreSupported() { assertThat(READER.read("{\n" + " \"Version\" : \"Version\",\n" + " \"Statement\" : {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : \"*\",\n" + " \"NotPrincipal\" : \"*\",\n" + " \"Action\" : \"A1\",\n" + " \"NotAction\" : \"NA1\",\n" + " \"Resource\" : \"R1\",\n" + " \"NotResource\" : \"NR1\",\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " }\n" + "}")) .isEqualTo(ONE_ELEMENT_LISTS_POLICY); } }
3,937
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamPolicyWriterTest.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.policybuilder.iam; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.policybuilder.iam.IamEffect.ALLOW; import org.junit.jupiter.api.Test; class IamPolicyWriterTest { private static final IamPrincipal PRINCIPAL_1 = IamPrincipal.create("P1", "*"); private static final IamPrincipal PRINCIPAL_2 = IamPrincipal.create("P2", "*"); private static final IamPrincipal NOT_PRINCIPAL_1 = IamPrincipal.create("NP1", "*"); private static final IamPrincipal NOT_PRINCIPAL_2 = IamPrincipal.create("NP2", "*"); private static final IamResource RESOURCE_1 = IamResource.create("R1"); private static final IamResource RESOURCE_2 = IamResource.create("R2"); private static final IamResource NOT_RESOURCE_1 = IamResource.create("NR1"); private static final IamResource NOT_RESOURCE_2 = IamResource.create("NR2"); private static final IamAction ACTION_1 = IamAction.create("A1"); private static final IamAction ACTION_2 = IamAction.create("A2"); private static final IamAction NOT_ACTION_1 = IamAction.create("NA1"); private static final IamAction NOT_ACTION_2 = IamAction.create("NA2"); private static final IamCondition CONDITION_1 = IamCondition.create("1", "K1", "V1"); private static final IamCondition CONDITION_2 = IamCondition.create("2", "K1", "V1"); private static final IamCondition CONDITION_3 = IamCondition.create("1", "K2", "V1"); private static final IamCondition CONDITION_4 = IamCondition.create("1", "K2", "V2"); private static final IamStatement FULL_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(asList(PRINCIPAL_1, PRINCIPAL_2)) .notPrincipals(asList(NOT_PRINCIPAL_1, NOT_PRINCIPAL_2)) .resources(asList(RESOURCE_1, RESOURCE_2)) .notResources(asList(NOT_RESOURCE_1, NOT_RESOURCE_2)) .actions(asList(ACTION_1, ACTION_2)) .notActions(asList(NOT_ACTION_1, NOT_ACTION_2)) .conditions(asList(CONDITION_1, CONDITION_2, CONDITION_3, CONDITION_4)) .build(); private static final IamPolicy FULL_POLICY = IamPolicy.builder() .id("Id") .version("Version") .statements(asList(FULL_STATEMENT, FULL_STATEMENT)) .build(); private static final IamStatement MINIMAL_STATEMENT = IamStatement.builder().effect(ALLOW).build(); private static final IamPolicy MINIMAL_POLICY = IamPolicy.builder() .version("Version") .statements(singletonList(MINIMAL_STATEMENT)) .build(); private static final IamStatement ONE_ELEMENT_LISTS_STATEMENT = IamStatement.builder() .effect(ALLOW) .sid("Sid") .principals(singletonList(IamPrincipal.ALL)) .notPrincipals(singletonList(IamPrincipal.ALL)) .resources(singletonList(RESOURCE_1)) .notResources(singletonList(NOT_RESOURCE_1)) .actions(singletonList(ACTION_1)) .notActions(singletonList(NOT_ACTION_1)) .conditions(singletonList(CONDITION_1)) .build(); private static final IamPolicy ONE_ELEMENT_LISTS_POLICY = IamPolicy.builder() .version("Version") .statements(singletonList(ONE_ELEMENT_LISTS_STATEMENT)) .build(); private static final IamPolicyWriter DEFAULT_WRITER = IamPolicyWriter.create(); private static final IamPolicyWriter PRETTY_WRITER = IamPolicyWriter.builder().prettyPrint(true).build(); @Test public void toBuilderPreservesSettings() { assertThat(PRETTY_WRITER.toBuilder().build()).isEqualTo(PRETTY_WRITER); } @Test public void writeFullPolicyWorks() { assertThat(DEFAULT_WRITER.writeToString(FULL_POLICY)) .isEqualTo("{\"Version\":\"Version\"," + "\"Id\":\"Id\"," + "\"Statement\":[" + "{\"Sid\":\"Sid\",\"Effect\":\"Allow\",\"Principal\":{\"P1\":\"*\",\"P2\":\"*\"},\"NotPrincipal\":{\"NP1\":\"*\",\"NP2\":\"*\"},\"Action\":[\"A1\",\"A2\"],\"NotAction\":[\"NA1\",\"NA2\"],\"Resource\":[\"R1\",\"R2\"],\"NotResource\":[\"NR1\",\"NR2\"],\"Condition\":{\"1\":{\"K1\":\"V1\",\"K2\":[\"V1\",\"V2\"]},\"2\":{\"K1\":\"V1\"}}}," + "{\"Sid\":\"Sid\",\"Effect\":\"Allow\",\"Principal\":{\"P1\":\"*\",\"P2\":\"*\"},\"NotPrincipal\":{\"NP1\":\"*\",\"NP2\":\"*\"},\"Action\":[\"A1\",\"A2\"],\"NotAction\":[\"NA1\",\"NA2\"],\"Resource\":[\"R1\",\"R2\"],\"NotResource\":[\"NR1\",\"NR2\"],\"Condition\":{\"1\":{\"K1\":\"V1\",\"K2\":[\"V1\",\"V2\"]},\"2\":{\"K1\":\"V1\"}}}" + "]}"); } @Test public void prettyWriteFullPolicyWorks() { assertThat(PRETTY_WRITER.writeToString(FULL_POLICY)) .isEqualTo("{\n" + " \"Version\" : \"Version\",\n" + " \"Id\" : \"Id\",\n" + " \"Statement\" : [ {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : {\n" + " \"P1\" : \"*\",\n" + " \"P2\" : \"*\"\n" + " },\n" + " \"NotPrincipal\" : {\n" + " \"NP1\" : \"*\",\n" + " \"NP2\" : \"*\"\n" + " },\n" + " \"Action\" : [ \"A1\", \"A2\" ],\n" + " \"NotAction\" : [ \"NA1\", \"NA2\" ],\n" + " \"Resource\" : [ \"R1\", \"R2\" ],\n" + " \"NotResource\" : [ \"NR1\", \"NR2\" ],\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\",\n" + " \"K2\" : [ \"V1\", \"V2\" ]\n" + " },\n" + " \"2\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " }, {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : {\n" + " \"P1\" : \"*\",\n" + " \"P2\" : \"*\"\n" + " },\n" + " \"NotPrincipal\" : {\n" + " \"NP1\" : \"*\",\n" + " \"NP2\" : \"*\"\n" + " },\n" + " \"Action\" : [ \"A1\", \"A2\" ],\n" + " \"NotAction\" : [ \"NA1\", \"NA2\" ],\n" + " \"Resource\" : [ \"R1\", \"R2\" ],\n" + " \"NotResource\" : [ \"NR1\", \"NR2\" ],\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\",\n" + " \"K2\" : [ \"V1\", \"V2\" ]\n" + " },\n" + " \"2\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " } ]\n" + "}"); } @Test public void writeMinimalPolicyWorks() { assertThat(PRETTY_WRITER.writeToString(MINIMAL_POLICY)) .isEqualTo("{\n" + " \"Version\" : \"Version\",\n" + " \"Statement\" : {\n" + " \"Effect\" : \"Allow\"\n" + " }\n" + "}"); } @Test public void singleElementListsAreWrittenAsNonArrays() { assertThat(PRETTY_WRITER.writeToString(ONE_ELEMENT_LISTS_POLICY)) .isEqualTo("{\n" + " \"Version\" : \"Version\",\n" + " \"Statement\" : {\n" + " \"Sid\" : \"Sid\",\n" + " \"Effect\" : \"Allow\",\n" + " \"Principal\" : \"*\",\n" + " \"NotPrincipal\" : \"*\",\n" + " \"Action\" : \"A1\",\n" + " \"NotAction\" : \"NA1\",\n" + " \"Resource\" : \"R1\",\n" + " \"NotResource\" : \"NR1\",\n" + " \"Condition\" : {\n" + " \"1\" : {\n" + " \"K1\" : \"V1\"\n" + " }\n" + " }\n" + " }\n" + "}"); } }
3,938
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/test/java/software/amazon/awssdk/policybuilder/iam/IamPrincipalTypeTest.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.policybuilder.iam; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class IamPrincipalTypeTest { @Test public void iamPrincipalTypeValueNotNull() { assertThatThrownBy(() -> IamPrincipalType.create(null)).hasMessageMatching(".*[Pp]rincipal.*[Tt]ype.*"); } }
3,939
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamPolicy.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.policybuilder.iam; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamPolicy; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An AWS access control policy is a object that acts as a container for one or * more statements, which specify fine grained rules for allowing or denying * various types of actions from being performed on your AWS resources. * <p> * By default, all requests to use your resource coming from anyone but you are * denied. Access control polices can override that by allowing different types * of access to your resources, or by explicitly denying different types of * access. * <p> * Each statement in an AWS access control policy takes the form: * "A has permission to do B to C where D applies". * <ul> * <li>A is the <b>principal</b> - the AWS account that is making a request to * access or modify one of your AWS resources. * <li>B is the <b>action</b> - the way in which your AWS resource is being accessed or modified, such * as sending a message to an Amazon SQS queue, or storing an object in an Amazon S3 bucket. * <li>C is the <b>resource</b> - your AWS entity that the principal wants to access, such * as an Amazon SQS queue, or an object stored in Amazon S3. * <li>D is the set of <b>conditions</b> - optional constraints that specify when to allow or deny * access for the principal to access your resource. Many expressive conditions are available, * some specific to each service. For example you can use date conditions to allow access to * your resources only after or before a specific time. * </ul> * <p> * For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/">The IAM User Guide</a> * * <h2>Usage Examples</h2> * <b>Create a new IAM identity policy that allows a role to write items to an Amazon DynamoDB table.</b> * {@snippet : * // IamClient requires a dependency on software.amazon.awssdk:iam * try (IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build()) { * IamPolicy policy = * IamPolicy.builder() * .addStatement(IamStatement.builder() * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build()) * .build(); * iam.createPolicy(r -> r.policyName("AllowWriteBookMetadata") * .policyDocument(policy.toJson())); * } * } * * <p> * <b>Download the policy uploaded in the previous example and create a new policy with "read" access added to it.</b> * {@snippet : * // IamClient requires a dependency on software.amazon.awssdk:iam * try (IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build()) { * String policyArn = "arn:aws:iam::123456789012:policy/AllowWriteBookMetadata"; * GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn)); * * String policyVersion = getPolicyResponse.defaultVersionId(); * GetPolicyVersionResponse getPolicyVersionResponse = * iam.getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion)); * * String decodedPolicy = URLDecoder.decode(getPolicyVersionResponse.policyVersion().document(), StandardCharsets.UTF_8); * IamPolicy policy = IamPolicy.fromJson(decodedPolicy); * * IamStatement newStatement = policy.statements().get(0).copy(s -> s.addAction("dynamodb:GetItem")); * IamPolicy newPolicy = policy.copy(p -> p.statements(Arrays.asList(newStatement))); * * iam.createPolicy(r -> r.policyName("AllowReadWriteBookMetadata") * .policyDocument(newPolicy.toJson())); * } * } * * @see IamPolicyReader * @see IamPolicyWriter * @see IamStatement * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/">IAM User Guide</a> */ @SdkPublicApi @ThreadSafe public interface IamPolicy extends ToCopyableBuilder<IamPolicy.Builder, IamPolicy> { /** * Create an {@code IamPolicy} from an IAM policy in JSON form. * <p> * This will raise an exception if the provided JSON is invalid or does not appear to represent a valid policy document. * <p> * This is equivalent to {@code IamPolicyReader.create().read(json)}. */ static IamPolicy fromJson(String json) { return IamPolicyReader.create().read(json); } /** * Create an {@code IamPolicy} containing the provided statements. * <p> * At least one statement is required. * <p> * This is equivalent to {@code IamPolicy.builder().statements(statements).build()} */ static IamPolicy create(Collection<IamStatement> statements) { return builder().statements(statements).build(); } /** * Create a {@link Builder} for an {@code IamPolicy}. */ static Builder builder() { return DefaultIamPolicy.builder(); } /** * Retrieve the value set by {@link Builder#id(String)}. */ String id(); /** * Retrieve the value set by {@link Builder#version(String)}. */ String version(); /** * Retrieve the value set by {@link Builder#statements(Collection)}. */ List<IamStatement> statements(); /** * Convert this policy to the JSON format that is accepted by AWS services. * <p> * This is equivalent to {@code IamPolicyWriter.create().writeToString(policy)} * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * .addStatement(IamStatement.builder() * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build()) * .build(); * System.out.println("Policy:\n" + policy.toJson()); * } */ String toJson(); /** * Convert this policy to the JSON format that is accepted by AWS services, using the provided writer. * <p> * This is equivalent to {@code writer.writeToString(policy)} * <p> * {@snippet : * IamPolicyWriter prettyWriter = * IamPolicyWriter.builder() * .prettyPrint(true) * .build(); * IamPolicy policy = * IamPolicy.builder() * .addStatement(IamStatement.builder() * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build()) * .build(); * System.out.println("Policy:\n" + policy.toJson(prettyWriter)); * } */ String toJson(IamPolicyWriter writer); /** * @see #builder() */ interface Builder extends CopyableBuilder<Builder, IamPolicy> { /** * Configure the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_id.html">{@code * Id}</a> element of the policy, specifying an optional identifier for the policy. * <p> * The ID is used differently in different services. ID is allowed in resource-based policies, but not in * identity-based policies. * <p> * For services that let you set an ID element, we recommend you use a UUID (GUID) for the value, or incorporate a UUID * as part of the ID to ensure uniqueness. * <p> * This value is optional. * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * .id("cd3ad3d9-2776-4ef1-a904-4c229d1642ee") // An identifier for the policy * .addStatement(IamStatement.builder() * .effect(IamEffect.DENY) * .addAction(IamAction.ALL) * .build()) * .build(); *} * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_id.html">ID user guide</a> */ Builder id(String id); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html">{@code Version} * </a> element of the policy, specifying the language syntax rules that are to be used to * process the policy. * <p> * By default, this value is {@code 2012-10-17}. * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * .version("2012-10-17") // The IAM policy language syntax version to use * .addStatement(IamStatement.builder() * .effect(IamEffect.DENY) * .addAction(IamAction.ALL) * .build()) * .build(); * } * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html">Version * user guide</a> */ Builder version(String version); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html">{@code * Statement}</a> element of the policy, specifying the access rules for this policy. * <p> * This will replace any other statements already added to the policy. At least one statement is required to * create a policy. * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * // Add a statement to this policy that denies all actions: * .statements(Arrays.asList(IamStatement.builder() * .effect(IamEffect.DENY) * .addAction(IamAction.ALL) * .build())) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html"> * Statement user guide</a> */ Builder statements(Collection<IamStatement> statements); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html">{@code * Statement}</a> element to this policy to specify additional access rules. * <p> * At least one statement is required to create a policy. * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * // Add a statement to this policy that denies all actions: * .addStatement(IamStatement.builder() * .effect(IamEffect.DENY) * .addAction(IamAction.ALL) * .build()) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html"> * Statement user guide</a> */ Builder addStatement(IamStatement statement); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html">{@code * Statement}</a> element to this policy to specify additional access rules. * <p> * This works the same as {@link #addStatement(IamStatement)}, except you do not need to specify {@code IamStatement * .builder()} or {@code build()}. At least one statement is required to create a policy. * <p> * {@snippet : * IamPolicy policy = * IamPolicy.builder() * // Add a statement to this policy that denies all actions: * .addStatement(s -> s.effect(IamEffect.DENY) * .addAction(IamAction.ALL)) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html"> * Statement user guide</a> */ Builder addStatement(Consumer<IamStatement.Builder> statement); } }
3,940
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamConditionOperator.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamConditionOperator; /** * The {@code IamConditionOperator} specifies the operator that should be applied to compare the {@link IamConditionKey} to an * expected value in an {@link IamCondition}. * * @see IamCondition * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamConditionOperator extends IamValue { /** * A string comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_EQUALS = create("StringEquals"); /** * A negated string comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_NOT_EQUALS = create("StringNotEquals"); /** * A string comparison, ignoring casing, of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_EQUALS_IGNORE_CASE = create("StringEqualsIgnoreCase"); /** * A negated string comparison, ignoring casing, of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_NOT_EQUALS_IGNORE_CASE = create("StringNotEqualsIgnoreCase"); /** * A case-sensitive pattern match between the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_LIKE = create("StringLike"); /** * A negated case-sensitive pattern match between the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String"> * String conditions</a> */ IamConditionOperator STRING_NOT_LIKE = create("StringNotLike"); /** * A numeric comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_EQUALS = create("NumericEquals"); /** * A negated numeric comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_NOT_EQUALS = create("NumericNotEquals"); /** * A numeric comparison of whether the {@link IamCondition#key()} is "less than" the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_LESS_THAN = create("NumericLessThan"); /** * A numeric comparison of whether the {@link IamCondition#key()} is "less than or equal to" the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_LESS_THAN_EQUALS = create("NumericLessThanEquals"); /** * A numeric comparison of whether the {@link IamCondition#key()} is "greater than" the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_GREATER_THAN = create("NumericGreaterThan"); /** * A numeric comparison of whether the {@link IamCondition#key()} is "greater than or equal to" the * {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric"> * Numeric conditions</a> */ IamConditionOperator NUMERIC_GREATER_THAN_EQUALS = create("NumericGreaterThanEquals"); /** * A date comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_EQUALS = create("DateEquals"); /** * A negated date comparison of the {@link IamCondition#key()} and {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_NOT_EQUALS = create("DateNotEquals"); /** * A date comparison of whether the {@link IamCondition#key()} "is earlier than" the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_LESS_THAN = create("DateLessThan"); /** * A date comparison of whether the {@link IamCondition#key()} "is earlier than or the same date as" the * {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_LESS_THAN_EQUALS = create("DateLessThanEquals"); /** * A date comparison of whether the {@link IamCondition#key()} "is later than" the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_GREATER_THAN = create("DateGreaterThan"); /** * A date comparison of whether the {@link IamCondition#key()} "is later than or the same date as" the * {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date"> * Date conditions</a> */ IamConditionOperator DATE_GREATER_THAN_EQUALS = create("DateGreaterThanEquals"); /** * A boolean comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Boolean"> * Boolean conditions</a> */ IamConditionOperator BOOL = create("Bool"); /** * A binary comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_BinaryEquals"> * Binary conditions</a> */ IamConditionOperator BINARY_EQUALS = create("BinaryEquals"); /** * An IP address comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress"> * IP Address conditions</a> */ IamConditionOperator IP_ADDRESS = create("IpAddress"); /** * A negated IP address comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress"> * IP Address conditions</a> */ IamConditionOperator NOT_IP_ADDRESS = create("NotIpAddress"); /** * An Amazon Resource Name (ARN) comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN"> * ARN conditions</a> */ IamConditionOperator ARN_EQUALS = create("ArnEquals"); /** * A negated Amazon Resource Name (ARN) comparison of the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN"> * ARN conditions</a> */ IamConditionOperator ARN_NOT_EQUALS = create("ArnNotEquals"); /** * A pattern match of the Amazon Resource Names (ARNs) in the {@link IamCondition#key()} and the {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN"> * ARN conditions</a> */ IamConditionOperator ARN_LIKE = create("ArnLike"); /** * A negated pattern match of the Amazon Resource Names (ARNs) in the {@link IamCondition#key()} and the * {@link IamCondition#value()}. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN"> * ARN conditions</a> */ IamConditionOperator ARN_NOT_LIKE = create("ArnNotLike"); /** * A check to determine whether the {@link IamCondition#key()} is present (use "false" in the {@link IamCondition#value()}) * or not present (use "true" in the {@link IamCondition#value()}). * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Null"> * ARN conditions</a> */ IamConditionOperator NULL = create("Null"); /** * Create a new {@link IamConditionOperator} with the provided string added as a prefix. * <p> * This is useful when adding * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_multi-value-conditions.html">the * "ForAllValues:" or "ForAnyValues:" prefixes</a> to an operator. */ IamConditionOperator addPrefix(String prefix); /** * Create a new {@link IamConditionOperator} with the provided string added as a suffix. * <p> * This is useful when adding * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IfExists"> * the "IfExists" suffix</a> to an operator. */ IamConditionOperator addSuffix(String suffix); /** * Create a new {@code IamConditionOperator} element with the provided {@link #value()}. */ static IamConditionOperator create(String value) { return new DefaultIamConditionOperator(value); } }
3,941
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamAction.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamAction; /** * The {@code Action} element of a {@link IamStatement}, specifying which service actions the statement applies to. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">Action user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamAction extends IamValue { /** * An {@link IamAction} representing ALL actions. When used on a statement, it means the policy should apply to * every action. */ IamAction ALL = create("*"); /** * Create a new {@code IamAction} element with the provided {@link #value()}. */ static IamAction create(String value) { return new DefaultIamAction(value); } }
3,942
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamPrincipal.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.policybuilder.iam; import static java.util.Collections.emptyList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamPrincipal; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * The {@code Principal} element of a {@link IamStatement}, specifying who the statement should apply to. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamPrincipal extends ToCopyableBuilder<IamPrincipal.Builder, IamPrincipal> { /** * An {@link IamPrincipal} representing ALL principals. When used on a statement, it means the policy should apply to * everyone. */ IamPrincipal ALL = create("*", "*"); /** * Create an {@link IamPrincipal} of the supplied type and ID (see {@link Builder#type(IamPrincipalType)} and * {@link Builder#id(String)}). * <p> * Both type and ID are required. This is equivalent to {@code IamPrincipal.builder().type(principalType).id(principalId) * .build()}. */ static IamPrincipal create(IamPrincipalType principalType, String principalId) { return builder().type(principalType).id(principalId).build(); } /** * Create an {@link IamPrincipal} of the supplied type and ID (see {@link Builder#type(String)} and * {@link Builder#id(String)}). * <p> * Both type and ID are required. This is equivalent to {@link #create(IamPrincipalType, String)}, except you do not need * to call {@code IamPrincipalType.create()}. */ static IamPrincipal create(String principalType, String principalId) { return builder().type(principalType).id(principalId).build(); } /** * Create multiple {@link IamPrincipal}s with the same {@link IamPrincipalType} and different IDs (see * {@link Builder#type(IamPrincipalType)} and {@link Builder#id(String)}). * <p> * Type is required, and the IDs in the IDs list must not be null. This is equivalent to calling * {@link #create(IamPrincipalType, String)} multiple times and collecting the results into a list. */ static List<IamPrincipal> createAll(IamPrincipalType principalType, Collection<String> principalIds) { Validate.paramNotNull(principalType, "principalType"); if (principalIds == null) { return emptyList(); } return principalIds.stream() .map(principalId -> create(principalType, principalId)) .collect(Collectors.toCollection(ArrayList::new)); } /** * Create multiple {@link IamPrincipal}s with the same {@link IamPrincipalType} and different IDs (see * {@link Builder#type(String)} and {@link Builder#id(String)}). * <p> * Type is required, and the IDs in the IDs list must not be null. This is equivalent to calling * {@link #create(String, String)} multiple times and collecting the results into a list. */ static List<IamPrincipal> createAll(String principalType, Collection<String> principalIds) { Validate.paramNotNull(principalType, "principalType"); if (principalIds == null) { return emptyList(); } return principalIds.stream() .map(principalId -> create(principalType, principalId)) .collect(Collectors.toCollection(ArrayList::new)); } /** * Create a {@link IamStatement.Builder} for an {@code IamPrincipal}. */ static Builder builder() { return DefaultIamPrincipal.builder(); } /** * Retrieve the value set by {@link Builder#type(IamPrincipalType)}. */ IamPrincipalType type(); /** * Retrieve the value set by {@link Builder#id(String)}. */ String id(); /** * @see #builder() */ interface Builder extends CopyableBuilder<Builder, IamPrincipal> { /** * Set the {@link IamPrincipalType} associated with this principal. * <p> * This value is required. * * @see IamPrincipalType * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder type(IamPrincipalType type); /** * Set the {@link IamPrincipalType} associated with this principal. * <p> * This is the same as {@link #type(IamPrincipalType)}, except you do not need to call {@code IamPrincipalType.create()}. * This value is required. * * @see IamPrincipalType * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder type(String type); /** * Set the identifier of the principal. * <p> * The identifiers that can be used depend on the {@link #type(IamPrincipalType)} of the principal. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder id(String id); } }
3,943
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamPrincipalType.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamPrincipalType; /** * The {@code IamPrincipalType} identifies what type of entity that the {@link IamPrincipal} refers to. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamPrincipalType extends IamValue { /** * An {@code AWS} principal. * <p> * For example, this includes AWS accounts, IAM users, IAM roles, IAM role sessions or STS federated users. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ IamPrincipalType AWS = create("AWS"); /** * A {@code Federated} principal. * <p> * This grants an external web identity, SAML identity provider, etc. permission to perform actions on your resources. For * example, cognito-identity.amazonaws.com or www.amazon.com. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ IamPrincipalType FEDERATED = create("Federated"); /** * A {@code Service} principal. * <p> * This grants other AWS services permissions to perform actions on your resources. Identifiers are usually in the format * service-name.amazonaws.com. For example, ecs.amazonaws.com or lambda.amazonaws.com. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ IamPrincipalType SERVICE = create("Service"); /** * A {@code CanonicalUser} principal. * <p> * Some services support a canonical user ID to identify your account without requiring your account ID to be shared. Such * identifiers are often a 64-digit alphanumeric value. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ IamPrincipalType CANONICAL_USER = create("CanonicalUser"); /** * Create a new {@code IamPrincipalType} element with the provided {@link #value()}. */ static IamPrincipalType create(String value) { return new DefaultIamPrincipalType(value); } }
3,944
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamCondition.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.policybuilder.iam; import static java.util.Collections.emptyList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamCondition; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * The {@code Condition} element of a {@link IamStatement}, specifying the conditions in which the statement is in effect. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamCondition extends ToCopyableBuilder<IamCondition.Builder, IamCondition> { /** * Create an {@link IamCondition} of the supplied operator, key and value (see * {@link Builder#operator(IamConditionOperator)}}, {@link Builder#key(IamConditionKey)} and {@link Builder#value(String)}). * <p> * All of operator, key and value are required. This is equivalent to {@code IamCondition.builder().operator(operator) * .key(key).value(value).build()}. */ static IamCondition create(IamConditionOperator operator, IamConditionKey key, String value) { return builder().operator(operator).key(key).value(value).build(); } /** * Create an {@link IamCondition} of the supplied operator, key and value (see * {@link Builder#operator(IamConditionOperator)}}, {@link Builder#key(String)} and {@link Builder#value(String)}). * <p> * All of operator, key and value are required. This is equivalent to {@code IamCondition.builder().operator(operator) * .key(key).value(value).build()}. */ static IamCondition create(IamConditionOperator operator, String key, String value) { return builder().operator(operator).key(key).value(value).build(); } /** * Create an {@link IamCondition} of the supplied operator, key and value (see * {@link Builder#operator(String)}}, {@link Builder#key(String)} and {@link Builder#value(String)}). * <p> * All of operator, key and value are required. This is equivalent to {@code IamCondition.builder().operator(operator) * .key(key).value(value).build()}. */ static IamCondition create(String operator, String key, String value) { return builder().operator(operator).key(key).value(value).build(); } /** * Create multiple {@link IamCondition}s with the same {@link IamConditionOperator} and {@link IamConditionKey}, but * different values (see {@link Builder#operator(IamConditionOperator)}}, {@link Builder#key(IamConditionKey)} and * {@link Builder#value(String)}). * <p> * Operator and key are required, and the values in the value list must not be null. This is equivalent to calling * {@link #create(IamConditionOperator, IamConditionKey, String)} multiple times and collecting the results into a list. */ static List<IamCondition> createAll(IamConditionOperator operator, IamConditionKey key, Collection<String> values) { if (values == null) { return emptyList(); } return values.stream().map(value -> create(operator, key, value)).collect(Collectors.toCollection(ArrayList::new)); } /** * Create multiple {@link IamCondition}s with the same {@link IamConditionOperator} and {@link IamConditionKey}, but * different values (see {@link Builder#operator(IamConditionOperator)}}, {@link Builder#key(String)} and * {@link Builder#value(String)}). * <p> * Operator and key are required, and the values in the value list must not be null. This is equivalent to calling * {@link #create(IamConditionOperator, String, String)} multiple times and collecting the results into a list. */ static List<IamCondition> createAll(IamConditionOperator operator, String key, Collection<String> values) { if (values == null) { return emptyList(); } return values.stream().map(value -> create(operator, key, value)).collect(Collectors.toCollection(ArrayList::new)); } /** * Create multiple {@link IamCondition}s with the same {@link IamConditionOperator} and {@link IamConditionKey}, but * different values (see {@link Builder#operator(String)}}, {@link Builder#key(String)} and {@link Builder#value(String)}). * <p> * Operator and key are required, and the values in the value list must not be null. This is equivalent to calling * {@link #create(String, String, String)} multiple times and collecting the results into a list. */ static List<IamCondition> createAll(String operator, String key, Collection<String> values) { if (values == null) { return emptyList(); } return values.stream().map(value -> create(operator, key, value)).collect(Collectors.toCollection(ArrayList::new)); } /** * Create a {@link Builder} for an {@code IamCondition}. */ static Builder builder() { return DefaultIamCondition.builder(); } /** * Retrieve the value set by {@link Builder#operator(IamConditionOperator)}. */ IamConditionOperator operator(); /** * Retrieve the value set by {@link Builder#key(IamConditionKey)}. */ IamConditionKey key(); /** * Retrieve the value set by {@link Builder#value(String)}. */ String value(); /** * @see #builder() */ interface Builder extends CopyableBuilder<Builder, IamCondition> { /** * Set the {@link IamConditionOperator} of this condition. * <p> * This value is required. * * @see IamConditionOperator * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder operator(IamConditionOperator operator); /** * Set the {@link IamConditionOperator} of this condition. * <p> * This is the same as {@link #operator(IamConditionOperator)}, except you do not need to call * {@code IamConditionOperator.create()}. This value is required. * * @see IamConditionOperator * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder operator(String operator); /** * Set the {@link IamConditionKey} of this condition. * <p> * This value is required. * * @see IamConditionKey * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder key(IamConditionKey key); /** * Set the {@link IamConditionKey} of this condition. * <p> * This is the same as {@link #key(IamConditionKey)}, except you do not need to call * {@code IamConditionKey.create()}. This value is required. * * @see IamConditionKey * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder key(String key); /** * Set the "right hand side" value of this condition. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder value(String value); } }
3,945
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamPolicyReader.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.policybuilder.iam; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamPolicyReader; /** * The {@link IamPolicyReader} converts a JSON policy into an {@link IamPolicy}. * * <h2>Usage Examples</h2> * <b>Log the number of statements in a policy downloaded from IAM.</b> * {@snippet : * // IamClient requires a dependency on software.amazon.awssdk:iam * try (IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build()) { * String policyArn = "arn:aws:iam::123456789012:policy/AllowWriteBookMetadata"; * GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn)); * * String policyVersion = getPolicyResponse.defaultVersionId(); * GetPolicyVersionResponse getPolicyVersionResponse = * iam.getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion)); * * IamPolicy policy = IamPolicyReader.create().read(getPolicyVersionResponse.policyVersion().document()); * * System.out.println("Number of statements in the " + policyArn + ": " + policy.statements().size()); * } * } * * @see IamPolicy#fromJson(String) */ @SdkPublicApi @ThreadSafe public interface IamPolicyReader { /** * Create a new {@link IamPolicyReader}. * <p> * This method is inexpensive, allowing the creation of readers wherever they are needed. */ static IamPolicyReader create() { return new DefaultIamPolicyReader(); } /** * Read a policy from a {@link String}. * <p> * This only performs minimal validation on the provided policy. * * @throws RuntimeException If the provided policy is not valid JSON or is missing a minimal set of required fields. */ IamPolicy read(String policy); /** * Read a policy from an {@link InputStream}. * <p> * The stream must provide a UTF-8 encoded string representing the policy. This only performs minimal validation on the * provided policy. * * @throws RuntimeException If the provided policy is not valid JSON or is missing a minimal set of required fields. */ IamPolicy read(InputStream policy); /** * Read a policy from a {@code byte} array. * <p> * The stream must provide a UTF-8 encoded string representing the policy. This only performs minimal validation on the * provided policy. * * @throws RuntimeException If the provided policy is not valid JSON or is missing a minimal set of required fields. */ IamPolicy read(byte[] policy); }
3,946
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamConditionKey.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamConditionKey; /** * The {@code IamConditionKey} specifies the "left hand side" of an {@link IamCondition}. * * @see IamCondition * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamConditionKey extends IamValue { /** * Create a new {@code IamConditionKey} element with the provided {@link #value()}. */ static IamConditionKey create(String value) { return new DefaultIamConditionKey(value); } }
3,947
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamPolicyWriter.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamPolicyWriter; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * The {@link IamPolicyReader} converts an {@link IamPolicy} into JSON. * * <h2>Usage Examples</h2> * <b>Create a new IAM identity policy that allows a role to write items to an Amazon DynamoDB table.</b> * {@snippet : * // IamClient requires a dependency on software.amazon.awssdk:iam * try (IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build()) { * IamPolicy policy = * IamPolicy.builder() * .addStatement(IamStatement.builder() * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build()) * .build(); * * IamPolicyWriter writer = IamPolicyWriter.create(); * iam.createPolicy(r -> r.policyName("AllowWriteBookMetadata") * .policyDocument(writer.writeToString(policy))); * } * } * * <b>Create and use a writer that pretty-prints the IAM policy JSON:</b> * {@snippet : * IamPolicyWriter prettyWriter = * IamPolicyWriter.builder() * .prettyPrint(true) * .build(); * IamPolicy policy = * IamPolicy.builder() * .addStatement(IamStatement.builder() * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build()) * .build(); * System.out.println("Policy:\n" + policy.toJson(prettyWriter)); * } * * @see IamPolicy#toJson() * @see IamPolicy#toJson(IamPolicyWriter) */ @SdkPublicApi @ThreadSafe public interface IamPolicyWriter extends ToCopyableBuilder<IamPolicyWriter.Builder, IamPolicyWriter> { /** * Create a new {@link IamPolicyReader}. * <p> * This method is inexpensive, allowing the creation of writers wherever they are needed. */ static IamPolicyWriter create() { return DefaultIamPolicyWriter.create(); } /** * Create a {@link Builder} for an {@code IamPolicyWriter}. */ static Builder builder() { return DefaultIamPolicyWriter.builder(); } /** * Write a policy to a {@link String}. * <p> * This does not validate that the provided policy is correct or valid. */ String writeToString(IamPolicy policy); /** * Write a policy to a {@code byte} array. * <p> * This does not validate that the provided policy is correct or valid. */ byte[] writeToBytes(IamPolicy policy); /** * @see #builder() */ interface Builder extends CopyableBuilder<Builder, IamPolicyWriter> { /** * Configure whether the writer should "pretty-print" the output. * <p> * When set to true, this will add new lines and indentation to the output to make it easier for a human to read, at * the expense of extra data (white space) being output. * <p> * By default, this is {@code false}. */ Builder prettyPrint(Boolean prettyPrint); } }
3,948
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamStatement.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.policybuilder.iam; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamStatement; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A statement is the formal description of a single permission, and is always * contained within a policy object. * <p> * A statement describes a rule for allowing or denying access to a specific AWS * resource based on how the resource is being accessed, and who is attempting * to access the resource. Statements can also optionally contain a list of * conditions that specify when a statement is to be honored. * <p> * For example, consider a statement that: * <ul> * <li>allows access (the effect) * <li>for a list of specific AWS account IDs (the principals) * <li>when accessing an SQS queue (the resource) * <li>using the SendMessage operation (the action) * <li>and the request occurs before a specific date (a condition) * </ul> * * <p> * Statements takes the form: "A has permission to do B to C where D applies". * <ul> * <li>A is the <b>principal</b> - the AWS account that is making a request to * access or modify one of your AWS resources. * <li>B is the <b>action</b> - the way in which your AWS resource is being accessed or modified, such * as sending a message to an Amazon SQS queue, or storing an object in an Amazon S3 bucket. * <li>C is the <b>resource</b> - your AWS entity that the principal wants to access, such * as an Amazon SQS queue, or an object stored in Amazon S3. * <li>D is the set of <b>conditions</b> - optional constraints that specify when to allow or deny * access for the principal to access your resource. Many expressive conditions are available, * some specific to each service. For example you can use date conditions to allow access to * your resources only after or before a specific time. * </ul> * * <p> * There are many resources and conditions available for use in statements, and * you can combine them to form fine grained custom access control polices. * * <p> * Statements are typically attached to a {@link IamPolicy}. * * <p> * For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/">The IAM User guide</a> * * <h2>Usage Examples</h2> * <b>Create an * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_id-based">identity-based policy * statement</a> that allows a role to write items to an Amazon DynamoDB table.</b> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantWriteBookMetadata") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:PutItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * * <p> * <b>Create a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_resource-based">resource-based policy * </a> statement that denies access to all users.</b> * {@snippet : * IamStatement statement = * IamStatement.builder() * .effect(IamEffect.DENY) * .addPrincipal(IamPrincipal.ALL) * .build(); * } * * @see IamPolicy * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html">Statement user * guide</a> */ @SdkPublicApi @ThreadSafe public interface IamStatement extends ToCopyableBuilder<IamStatement.Builder, IamStatement> { /** * Create a {@link Builder} for an {@code IamStatement}. */ static Builder builder() { return DefaultIamStatement.builder(); } /** * Retrieve the value set by {@link Builder#sid(String)}. */ String sid(); /** * Retrieve the value set by {@link Builder#effect(IamEffect)}. */ IamEffect effect(); /** * Retrieve the value set by {@link Builder#principals(Collection)}. */ List<IamPrincipal> principals(); /** * Retrieve the value set by {@link Builder#notPrincipals(Collection)}. */ List<IamPrincipal> notPrincipals(); /** * Retrieve the value set by {@link Builder#actions(Collection)}. */ List<IamAction> actions(); /** * Retrieve the value set by {@link Builder#notActions(Collection)}. */ List<IamAction> notActions(); /** * Retrieve the value set by {@link Builder#resources(Collection)}. */ List<IamResource> resources(); /** * Retrieve the value set by {@link Builder#notResources(Collection)}. */ List<IamResource> notResources(); /** * Retrieve the value set by {@link Builder#conditions(Collection)}. */ List<IamCondition> conditions(); /** * @see #builder() */ interface Builder extends CopyableBuilder<Builder, IamStatement> { /** * Configure the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html">{@code * Sid}</a> element of the policy, specifying an identifier for the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") // An identifier for the statement * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html">Sid user * guide</a> */ Builder sid(String sid); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html">{@code Effect}</a> * element of the policy, specifying whether the statement results in an allow or deny. * <p> * This value is required. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect(IamEffect.ALLOW) // The statement ALLOWS access * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * * @see IamEffect * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html">Effect user * guide</a> */ Builder effect(IamEffect effect); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html">{@code Effect}</a> * element of the policy, specifying whether the statement results in an allow or deny. * <p> * This works the same as {@link #effect(IamEffect)}, except you do not need to {@link IamEffect}. This value is required. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect("Allow") // The statement ALLOWs access * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * * @see IamEffect * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html">Effect user * guide</a> */ Builder effect(String effect); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}</a> element of the statement, specifying the principals that are allowed or denied * access to a resource. * <p> * This will replace any other principals already added to the statement. * <p> * {@snippet : * List<IamPrincipal> bookReaderRoles = * IamPrincipal.createAll("AWS", * Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")); * * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * .principals(bookReaderRoles) // This statement allows access to the books service and operators * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * * @see IamPrincipal * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder principals(Collection<IamPrincipal> principals); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}</a> to this statement, specifying a principal that is allowed or denied access to * a resource. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service: * .addPrincipal(IamPrincipal.create("AWS", "arn:aws:iam::123456789012:role/books-service")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipal(IamPrincipal principal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}</a> to this statement, specifying a principal that is allowed or denied access to * a resource. * <p> * This works the same as {@link #addPrincipal(IamPrincipal)}, except you do not need to specify {@code IamPrincipal * .builder()} or {@code build()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service: * .addPrincipal(p -> p.type("AWS").id("arn:aws:iam::123456789012:role/books-service")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipal(Consumer<IamPrincipal.Builder> principal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}</a> to this statement, specifying a principal that is allowed or denied access to * a resource. * <p> * This works the same as {@link #addPrincipal(IamPrincipal)}, except you do not need to specify {@code IamPrincipal * .create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service: * .addPrincipal(IamPrincipalType.AWS, "arn:aws:iam::123456789012:role/books-service") * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipal(IamPrincipalType iamPrincipalType, String principal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}</a> to this statement, specifying a principal that is allowed or denied access to * a resource. * <p> * This works the same as {@link #addPrincipal(IamPrincipalType, String)}, except you do not need to specify {@code * IamPrincipalType.create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service: * .addPrincipal("AWS", "arn:aws:iam::123456789012:role/books-service") * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipal(String iamPrincipalType, String principal); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}s</a> to this statement, specifying principals that are allowed or denied access to * a resource. * <p> * This works the same as calling {@link #addPrincipal(IamPrincipalType, String)} multiple times with the same * {@link IamPrincipalType}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service and operators: * .addPrincipals(IamPrincipalType.AWS, * Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipals(IamPrincipalType iamPrincipalType, Collection<String> principals); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">{@code * Principal}s</a> to this statement, specifying principals that are allowed or denied access to * a resource. * <p> * This works the same as calling {@link #addPrincipal(String, String)} multiple times with the same * {@link IamPrincipalType}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.ALLOW) * // This statement allows access to the books service and operators: * .addPrincipals("AWS", Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">Principal * user guide</a> */ Builder addPrincipals(String iamPrincipalType, Collection<String> principals); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}</a> element of the statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This will replace any other not-principals already added to the statement. * <p> * {@snippet : * List<IamPrincipal> bookReaderRoles = * IamPrincipal.createAll("AWS", * Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")); * * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service and operators: * .notPrincipals(bookReaderRoles) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder notPrincipals(Collection<IamPrincipal> notPrincipals); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service: * .addNotPrincipal(IamPrincipal.create("AWS", "arn:aws:iam::123456789012:role/books-service")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipal(IamPrincipal notPrincipal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This works the same as {@link #addNotPrincipal(IamPrincipal)}, except you do not need to specify {@code IamPrincipal * .builder()} or {@code build()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service: * .addNotPrincipal(p -> p.type("AWS").id("arn:aws:iam::123456789012:role/books-service")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipal(Consumer<IamPrincipal.Builder> notPrincipal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This works the same as {@link #addNotPrincipal(IamPrincipal)}, except you do not need to specify {@code IamPrincipal * .create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service: * .addNotPrincipal(IamPrincipalType.AWS, "arn:aws:iam::123456789012:role/books-service") * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipal(IamPrincipalType iamPrincipalType, String notPrincipal); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This works the same as {@link #addNotPrincipal(IamPrincipalType, String)}, except you do not need to specify {@code * IamPrincipalType.create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service: * .addNotPrincipal("AWS", "arn:aws:iam::123456789012:role/books-service") * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipal(String iamPrincipalType, String notPrincipal); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}s</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This works the same as calling {@link #addNotPrincipal(IamPrincipalType, String)} multiple times with the same * {@link IamPrincipalType}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service and operators: * .addNotPrincipals(IamPrincipalType.AWS, * Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipals(IamPrincipalType iamPrincipalType, Collection<String> notPrincipals); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html">{@code * NotPrincipal}s</a> to this statement, specifying that all principals are affected by the policy except the * ones listed. * <p> * Very few scenarios require the use of {@code NotPrincipal}. We recommend that you explore other authorization options * before you decide to use {@code NotPrincipal}. {@code NotPrincipal} can only be used with {@link IamEffect#DENY} * statements. * <p> * This works the same as calling {@link #addNotPrincipal(String, String)} multiple times with the same * {@link IamPrincipalType}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookContent") * .effect(IamEffect.DENY) * // This statement denies access to everyone except the books service and operators: * .addNotPrincipals("AWS", Arrays.asList("arn:aws:iam::123456789012:role/books-service", * "arn:aws:iam::123456789012:role/books-operator")) * .addAction("s3:GetObject") * .addResource("arn:aws:s3:us-west-2:123456789012:accesspoint/book-content/object/*") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html"> * NotPrincipal user guide</a> */ Builder addNotPrincipals(String iamPrincipalType, Collection<String> notPrincipals); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">{@code Action}</a> * element of the statement, specifying the actions that are allowed or denied. * <p> * This will replace any other actions already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadWriteBookMetadata") * .effect(IamEffect.ALLOW) * // This statement grants access to read and write items in Amazon DynamoDB: * .actions(Arrays.asList(IamAction.create("dynamodb:PutItem"), * IamAction.create("dynamodb:GetItem"))) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">Action user * guide</a> */ Builder actions(Collection<IamAction> actions); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">{@code Action}</a> * element of the statement, specifying the actions that are allowed or denied. * <p> * This works the same as {@link #actions(Collection)}, except you do not need to call {@code IamAction.create() * } on each action. This will replace any other actions already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadWriteBookMetadata") * .effect(IamEffect.ALLOW) * // This statement grants access to read and write items in Amazon DynamoDB: * .actionIds(Arrays.asList("dynamodb:PutItem", "dynamodb:GetItem")) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">Action user * guide</a> */ Builder actionIds(Collection<String> actions); /** * Append an <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">{@code * Action}</a> element to this statement, specifying an action that is allowed or denied. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect(IamEffect.ALLOW) * // This statement grants access to read items in Amazon DynamoDB: * .addAction(IamAction.create("dynamodb:GetItem")) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">Action user * guide</a> */ Builder addAction(IamAction action); /** * Append an <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">{@code * Action}</a> element to this statement, specifying an action that is allowed or denied. * <p> * This works the same as {@link #addAction(IamAction)}, except you do not need to call {@code IamAction.create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect(IamEffect.ALLOW) * // This statement grants access to read items in Amazon DynamoDB: * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html">Action user * guide</a> */ Builder addAction(String action); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">{@code * NotAction}</a> element of the statement, specifying actions that are denied or allowed. * <p> * This will replace any other not-actions already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantAllButDeleteBookMetadataTable") * .effect(IamEffect.ALLOW) * // This statement grants access to do ALL CURRENT AND FUTURE actions against the books table, except * // dynamodb:DeleteTable * .notActions(Arrays.asList(IamAction.create("dynamodb:DeleteTable"))) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">NotAction * user guide</a> */ Builder notActions(Collection<IamAction> actions); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">{@code * NotAction}</a> element of the statement, specifying actions that are denied or allowed. * <p> * This works the same as {@link #notActions(Collection)}, except you do not need to call {@code IamAction.create()} * on each action. This will replace any other not-actions already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantAllButDeleteBookMetadataTable") * .effect(IamEffect.ALLOW) * // This statement grants access to do ALL CURRENT AND FUTURE actions against the books table, except * // dynamodb:DeleteTable * .notActionIds(Arrays.asList("dynamodb:DeleteTable")) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">NotAction * user guide</a> */ Builder notActionIds(Collection<String> actions); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">{@code * NotAction}</a> element to this statement, specifying an action that is denied or allowed. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantAllButDeleteBookMetadataTable") * .effect(IamEffect.ALLOW) * // This statement grants access to do ALL CURRENT AND FUTURE actions against the books table, except * // dynamodb:DeleteTable * .addNotAction(IamAction.create("dynamodb:DeleteTable")) * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">NotAction * user guide</a> */ Builder addNotAction(IamAction action); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">{@code * NotAction}</a> element to this statement, specifying an action that is denied or allowed. * <p> * This works the same as {@link #addNotAction(IamAction)}, except you do not need to call {@code IamAction.create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantAllButDeleteBookMetadataTable") * .effect(IamEffect.ALLOW) * // This statement grants access to do ALL CURRENT AND FUTURE actions against the books table, except * // dynamodb:DeleteTable * .addNotAction("dynamodb:DeleteTable") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html">NotAction * user guide</a> */ Builder addNotAction(String action); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">{@code Resource} * </a> element of the statement, specifying the resource(s) that the statement covers. * <p> * This will replace any other resources already added to the statement. * <p> * {@snippet : * List<IamResource> resources = * Arrays.asList(IamResource.create("arn:aws:dynamodb:us-east-2:123456789012:table/books"), * IamResource.create("arn:aws:dynamodb:us-east-2:123456789012:table/customers")); * * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookAndCustomersMetadata") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to the books and customers tables: * .resources(resources) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">Resource * user guide</a> */ Builder resources(Collection<IamResource> resources); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">{@code Resource} * </a> element of the statement, specifying the resource(s) that the statement covers. * <p> * This works the same as {@link #resources(Collection)}, except you do not need to call {@code IamResource.create()} * on each resource. This will replace any other resources already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookAndCustomersMetadata") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to the books and customers tables: * .resourceIds(Arrays.asList("arn:aws:dynamodb:us-east-2:123456789012:table/books", * "arn:aws:dynamodb:us-east-2:123456789012:table/customers")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">Resource * user guide</a> */ Builder resourceIds(Collection<String> resources); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">{@code Resource} * </a> element to the statement, specifying a resource that the statement covers. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to the books table: * .addResource(IamResource.create("arn:aws:dynamodb:us-east-2:123456789012:table/books")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">Resource * user guide</a> */ Builder addResource(IamResource resource); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">{@code Resource} * </a> element to the statement, specifying a resource that the statement covers. * <p> * This works the same as {@link #addResource(IamResource)}, except you do not need to call {@code IamResource.create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBookMetadata") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to the books table: * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">Resource * user guide</a> */ Builder addResource(String resource); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html">{@code * NotResource}</a> element of the statement, specifying that the statement should apply to every resource except the * ones listed. * <p> * This will replace any other not-resources already added to the statement. * <p> * {@snippet : * List<IamResource> notResources = * Arrays.asList(IamResource.create("arn:aws:dynamodb:us-east-2:123456789012:table/customers")); * * IamStatement statement = * IamStatement.builder() * .sid("GrantReadNotCustomers") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to EVERY CURRENT AND FUTURE RESOURCE except the customers table: * .notResources(notResources) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html"> * NotResource user guide</a> */ Builder notResources(Collection<IamResource> resources); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html">{@code * NotResource}</a> element of the statement, specifying that the statement should apply to every resource except the * ones listed. * <p> * This works the same as {@link #notResources(Collection)}, except you do not need to call {@code IamResource.create()} * on each resource. This will replace any other not-resources already added to the statement. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadNotCustomers") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to EVERY CURRENT AND FUTURE RESOURCE except the customers table: * .notResourceIds(Arrays.asList("arn:aws:dynamodb:us-east-2:123456789012:table/customers")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html"> * NotResource user guide</a> */ Builder notResourceIds(Collection<String> resources); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html">{@code * NotResource} </a> element to the statement, specifying that the statement should apply to every resource except the * ones listed. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadNotCustomers") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to EVERY CURRENT AND FUTURE RESOURCE except the customers table: * .addNotResource(IamResource.create("arn:aws:dynamodb:us-east-2:123456789012:table/customers")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html"> * NotResource user guide</a> */ Builder addNotResource(IamResource resource); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html">{@code * NotResource} </a> element to the statement, specifying that the statement should apply to every resource except the * ones listed. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadNotCustomers") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * // This statement grants access to EVERY CURRENT AND FUTURE RESOURCE except the customers table: * .addNotResource("arn:aws:dynamodb:us-east-2:123456789012:table/customers") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html"> * NotResource user guide</a> */ Builder addNotResource(String resource); /** * Configure the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> element of the statement, specifying the conditions in which the statement is in effect. * <p> * This will replace any other conditions already added to the statement. * <p> * {@snippet : * IamCondition startTime = IamCondition.create(IamConditionOperator.DATE_GREATER_THAN, * "aws:CurrentTime", * "1988-05-21T00:00:00Z"); * IamCondition endTime = IamCondition.create(IamConditionOperator.DATE_LESS_THAN, * "aws:CurrentTime", * "2065-09-01T00:00:00Z"); * * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access between the specified start and end times: * .conditions(Arrays.asList(startTime, endTime)) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder conditions(Collection<IamCondition> conditions); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> to the statement, specifying a condition in which the statement is in effect. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access after a specified start time: * .addCondition(IamCondition.create(IamConditionOperator.DATE_GREATER_THAN, * "aws:CurrentTime", * "1988-05-21T00:00:00Z")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addCondition(IamCondition condition); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> to the statement, specifying a condition in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamCondition)}, except you do not need to specify {@code IamCondition * .builder()} or {@code build()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access after a specified start time: * .addCondition(c -> c.operator(IamConditionOperator.DATE_GREATER_THAN) * .key("aws:CurrentTime") * .value("1988-05-21T00:00:00Z")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addCondition(Consumer<IamCondition.Builder> condition); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> to the statement, specifying a condition in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamCondition)}, except you do not need to specify {@code IamCondition * .create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access after a specified start time: * .addCondition(IamConditionOperator.DATE_GREATER_THAN, * IamConditionKey.create("aws:CurrentTime"), * "1988-05-21T00:00:00Z") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addCondition(IamConditionOperator operator, IamConditionKey key, String value); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> to the statement, specifying a condition in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamCondition)}, except you do not need to specify {@code IamCondition * .create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access after a specified start time: * .addCondition(IamConditionOperator.DATE_GREATER_THAN, "aws:CurrentTime", "1988-05-21T00:00:00Z") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addCondition(IamConditionOperator operator, String key, String value); /** * Append a * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}</a> to the statement, specifying a condition in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamCondition)}, except you do not need to specify {@code IamCondition * .create()}. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access after a specified start time: * .addCondition("DateGreaterThan", "aws:CurrentTime", "1988-05-21T00:00:00Z") * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addCondition(String operator, String key, String values); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}s</a> to the statement, specifying conditions in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamConditionOperator, IamConditionKey, String)} multiple times with the * same operator and key, but different values. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access only in the us-east-1 and us-west-2 regions: * .addConditions(IamConditionOperator.STRING_EQUALS, * IamConditionKey.create("aws:RequestedRegion"), * Arrays.asList("us-east-1", "us-west-2")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addConditions(IamConditionOperator operator, IamConditionKey key, Collection<String> values); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}s</a> to the statement, specifying conditions in which the statement is in effect. * <p> * This works the same as {@link #addCondition(IamConditionOperator, String, String)} multiple times with the * same operator and key, but different values. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access only in the us-east-1 and us-west-2 regions: * .addConditions(IamConditionOperator.STRING_EQUALS, * "aws:RequestedRegion", * Arrays.asList("us-east-1", "us-west-2")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addConditions(IamConditionOperator operator, String key, Collection<String> values); /** * Append multiple * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">{@code * Condition}s</a> to the statement, specifying conditions in which the statement is in effect. * <p> * This works the same as {@link #addCondition(String, String, String)} multiple times with the * same operator and key, but different values. * <p> * {@snippet : * IamStatement statement = * IamStatement.builder() * .sid("GrantReadBooks") * .effect(IamEffect.ALLOW) * .addAction("dynamodb:GetItem") * .addResource("arn:aws:dynamodb:us-east-2:123456789012:table/books") * // This statement grants access only in the us-east-1 and us-west-2 regions: * .addConditions("StringEquals", "aws:RequestedRegion", Arrays.asList("us-east-1", "us-west-2")) * .build(); * } * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Condition * user guide</a> */ Builder addConditions(String operator, String key, Collection<String> values); } }
3,949
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamEffect.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamEffect; /** * The {@code Effect} element of a {@link IamStatement}, specifying whether the statement should ALLOW or DENY certain actions. * * @see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html">Effect user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamEffect extends IamValue { /** * The {@link IamStatement} to which this effect is attached should ALLOW the actions described in the policy, and DENY * everything else. */ IamEffect ALLOW = create("Allow"); /** * The {@link IamStatement} to which this effect is attached should DENY the actions described in the policy. This takes * precedence over any other ALLOW statements. See the * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html">policy evaluation * logic guide</a> for more information on how to use the DENY effect. */ IamEffect DENY = create("Deny"); /** * Create a new {@code IamEffect} element with the provided {@link #value()}. */ static IamEffect create(String value) { return new DefaultIamEffect(value); } }
3,950
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamValue.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface IamValue { /** * Retrieve the string that should represent this element in the serialized IAM policy when it is marshalled via * {@link IamPolicyWriter}. */ String value(); }
3,951
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/IamResource.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.policybuilder.iam; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.policybuilder.iam.internal.DefaultIamResource; /** * The {@code Resource} element of a {@link IamStatement}, specifying which resource the statement applies to. * * @see * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html">Resource user guide</a> */ @SdkPublicApi @ThreadSafe public interface IamResource extends IamValue { /** * An {@link IamResource} representing ALL resources. When used on a statement, it means the policy should apply to * every resource. */ IamResource ALL = create("*"); /** * Create a new {@code IamResource} element with the provided {@link #value()}. */ static IamResource create(String value) { return new DefaultIamResource(value); } }
3,952
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamPolicy.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.policybuilder.iam.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamPolicy; import software.amazon.awssdk.policybuilder.iam.IamPolicyWriter; import software.amazon.awssdk.policybuilder.iam.IamStatement; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamPolicy}. * * @see IamPolicy#create * @see IamPolicy#fromJson(String) * @see IamPolicy#builder() */ @SdkInternalApi public final class DefaultIamPolicy implements IamPolicy { private final String id; @NotNull private final String version; @NotNull private final List<IamStatement> statements; public DefaultIamPolicy(Builder builder) { this.id = builder.id; this.version = builder.version != null ? builder.version : "2012-10-17"; this.statements = new ArrayList<>(Validate.notEmpty(builder.statements, "At least one policy statement is required.")); } public static Builder builder() { return new Builder(); } @Override public String id() { return id; } @Override public String version() { return version; } @Override public List<IamStatement> statements() { return Collections.unmodifiableList(statements); } @Override public String toJson() { return toJson(IamPolicyWriter.create()); } @Override public String toJson(IamPolicyWriter writer) { return writer.writeToString(this); } @Override public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamPolicy that = (DefaultIamPolicy) o; if (!Objects.equals(id, that.id)) { return false; } if (!version.equals(that.version)) { return false; } if (!statements.equals(that.statements)) { return false; } return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + version.hashCode(); result = 31 * result + statements.hashCode(); return result; } @Override public String toString() { return ToString.builder("IamPolicy") .add("id", id) .add("version", version) .add("statements", statements.isEmpty() ? null : statements) .build(); } public static class Builder implements IamPolicy.Builder { private String id; private String version; private final List<IamStatement> statements = new ArrayList<>(); private Builder() { } private Builder(DefaultIamPolicy policy) { this.id = policy.id; this.version = policy.version; this.statements.addAll(policy.statements); } @Override public IamPolicy.Builder id(String id) { this.id = id; return this; } @Override public IamPolicy.Builder version(String version) { this.version = version; return this; } @Override public IamPolicy.Builder statements(Collection<IamStatement> statements) { this.statements.clear(); if (statements != null) { this.statements.addAll(statements); } return this; } @Override public IamPolicy.Builder addStatement(IamStatement statement) { Validate.paramNotNull(statement, "statement"); this.statements.add(statement); return this; } @Override public IamPolicy.Builder addStatement(Consumer<IamStatement.Builder> statement) { Validate.paramNotNull(statement, "statement"); this.statements.add(IamStatement.builder().applyMutation(statement).build()); return this; } @Override public IamPolicy build() { return new DefaultIamPolicy(this); } } }
3,953
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamPolicyReader.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.policybuilder.iam.internal; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamCondition; import software.amazon.awssdk.policybuilder.iam.IamPolicy; import software.amazon.awssdk.policybuilder.iam.IamPolicyReader; import software.amazon.awssdk.policybuilder.iam.IamPrincipal; import software.amazon.awssdk.policybuilder.iam.IamStatement; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamPolicyReader}. * * @see IamPolicyReader#create */ @SdkInternalApi public final class DefaultIamPolicyReader implements IamPolicyReader { private static final JsonNodeParser JSON_NODE_PARSER = JsonNodeParser.create(); @Override public IamPolicy read(String policy) { return read(policy.getBytes(StandardCharsets.UTF_8)); } @Override public IamPolicy read(byte[] policy) { return read(new ByteArrayInputStream(policy)); } @Override public IamPolicy read(InputStream policy) { return readPolicy(JSON_NODE_PARSER.parse(policy)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return true; } @Override public int hashCode() { return 0; } private IamPolicy readPolicy(JsonNode policyNode) { Map<String, JsonNode> policyObject = expectObject(policyNode, "Policy did not start with {"); return IamPolicy.builder() .version(getString(policyObject, "Version")) .id(getString(policyObject, "Id")) .statements(readStatements(policyObject.get("Statement"))) .build(); } private List<IamStatement> readStatements(JsonNode statementsNode) { if (statementsNode == null) { return null; } if (statementsNode.isArray()) { return statementsNode.asArray() .stream() .map(n -> expectObject(n, "Statement entry")) .map(this::readStatement) .collect(toList()); } if (statementsNode.isObject()) { return singletonList(readStatement(statementsNode.asObject())); } throw new IllegalArgumentException("Statement was not an array or object."); } private IamStatement readStatement(Map<String, JsonNode> statementObject) { return IamStatement.builder() .sid(getString(statementObject, "Sid")) .effect(getString(statementObject, "Effect")) .principals(readPrincipals(statementObject, "Principal")) .notPrincipals(readPrincipals(statementObject, "NotPrincipal")) .actionIds(readStringOrArrayAsList(statementObject, "Action")) .notActionIds(readStringOrArrayAsList(statementObject, "NotAction")) .resourceIds(readStringOrArrayAsList(statementObject, "Resource")) .notResourceIds(readStringOrArrayAsList(statementObject, "NotResource")) .conditions(readConditions(statementObject.get("Condition"))) .build(); } private List<IamPrincipal> readPrincipals(Map<String, JsonNode> statementObject, String name) { JsonNode principalsNode = statementObject.get(name); if (principalsNode == null) { return null; } if (principalsNode.isString() && principalsNode.asString().equals(IamPrincipal.ALL.id())) { return singletonList(IamPrincipal.ALL); } if (principalsNode.isObject()) { List<IamPrincipal> result = new ArrayList<>(); Map<String, JsonNode> principalsNodeObject = principalsNode.asObject(); principalsNodeObject.keySet().forEach( k -> result.addAll(IamPrincipal.createAll(k, readStringOrArrayAsList(principalsNodeObject, k))) ); return result; } throw new IllegalArgumentException(name + " was not \"" + IamPrincipal.ALL.id() + "\" or an object"); } private List<IamCondition> readConditions(JsonNode conditionNode) { if (conditionNode == null) { return null; } Map<String, JsonNode> conditionObject = expectObject(conditionNode, "Condition"); List<IamCondition> result = new ArrayList<>(); conditionObject.forEach((operator, keyValueNode) -> { Map<String, JsonNode> keyValueObject = expectObject(keyValueNode, "Condition key"); keyValueObject.forEach((key, value) -> { if (value.isString()) { result.add(IamCondition.create(operator, key, value.asString())); } else if (value.isArray()) { List<String> values = value.asArray() .stream() .map(valueNode -> expectString(valueNode, "Condition values entry")) .collect(toList()); result.addAll(IamCondition.createAll(operator, key, values)); } }); }); return result; } private List<String> readStringOrArrayAsList(Map<String, JsonNode> statementObject, String nodeKey) { JsonNode node = statementObject.get(nodeKey); if (node == null) { return null; } if (node.isString()) { return singletonList(node.asString()); } if (node.isArray()) { return node.asArray() .stream() .map(n -> expectString(n, nodeKey + " entry")) .collect(toList()); } throw new IllegalArgumentException(nodeKey + " was not an array or string"); } private String getString(Map<String, JsonNode> object, String key) { JsonNode node = object.get(key); if (node == null) { return null; } return expectString(node, key); } private String expectString(JsonNode node, String name) { Validate.isTrue(node.isString(), "%s was not a string", name); return node.asString(); } private Map<String, JsonNode> expectObject(JsonNode node, String name) { Validate.isTrue(node.isObject(), "%s was not an object", name); return node.asObject(); } }
3,954
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamAction.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamAction; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamAction}. * * @see IamAction#create */ @SdkInternalApi public final class DefaultIamAction implements IamAction { @NotNull private final String value; public DefaultIamAction(String value) { this.value = Validate.paramNotNull(value, "actionValue"); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamAction that = (DefaultIamAction) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamAction") .add("value", value) .build(); } }
3,955
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamPolicyWriter.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.policybuilder.iam.internal; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamCondition; import software.amazon.awssdk.policybuilder.iam.IamConditionKey; import software.amazon.awssdk.policybuilder.iam.IamConditionOperator; import software.amazon.awssdk.policybuilder.iam.IamPolicy; import software.amazon.awssdk.policybuilder.iam.IamPolicyWriter; import software.amazon.awssdk.policybuilder.iam.IamPrincipal; import software.amazon.awssdk.policybuilder.iam.IamPrincipalType; import software.amazon.awssdk.policybuilder.iam.IamStatement; import software.amazon.awssdk.policybuilder.iam.IamValue; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.protocols.jsoncore.JsonWriter; import software.amazon.awssdk.protocols.jsoncore.JsonWriter.JsonGeneratorFactory; import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamPolicyWriter}. * * @see IamPolicyWriter#create */ @SdkInternalApi public final class DefaultIamPolicyWriter implements IamPolicyWriter { private static final IamPolicyWriter INSTANCE = IamPolicyWriter.builder().build(); private final Boolean prettyPrint; @NotNull private final transient JsonGeneratorFactory jsonGeneratorFactory; public DefaultIamPolicyWriter(Builder builder) { this.prettyPrint = builder.prettyPrint; if (Boolean.TRUE.equals(builder.prettyPrint)) { this.jsonGeneratorFactory = os -> { JsonGenerator generator = JsonNodeParser.DEFAULT_JSON_FACTORY.createGenerator(os); generator.useDefaultPrettyPrinter(); return generator; }; } else { this.jsonGeneratorFactory = null; } } public static IamPolicyWriter create() { return INSTANCE; } public static Builder builder() { return new Builder(); } @Override public String writeToString(IamPolicy policy) { return new String(writeToBytes(policy), StandardCharsets.UTF_8); } @Override public byte[] writeToBytes(IamPolicy policy) { return writePolicy(policy).getBytes(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamPolicyWriter that = (DefaultIamPolicyWriter) o; return Objects.equals(prettyPrint, that.prettyPrint); } @Override public int hashCode() { return prettyPrint != null ? prettyPrint.hashCode() : 0; } private JsonWriter writePolicy(IamPolicy policy) { JsonWriter writer = JsonWriter.builder() .jsonGeneratorFactory(jsonGeneratorFactory) .build(); writer.writeStartObject(); writeFieldIfNotNull(writer, "Version", policy.version()); writeFieldIfNotNull(writer, "Id", policy.id()); writeStatements(writer, policy.statements()); writer.writeEndObject(); return writer; } private void writeStatements(JsonWriter writer, List<IamStatement> statements) { if (statements.isEmpty()) { return; } writer.writeFieldName("Statement"); if (statements.size() == 1) { writeStatement(writer, statements.get(0)); return; } writer.writeStartArray(); statements.forEach(statement -> { writeStatement(writer, statement); }); writer.writeEndArray(); } private void writeStatement(JsonWriter writer, IamStatement statement) { writer.writeStartObject(); writeFieldIfNotNull(writer, "Sid", statement.sid()); writeFieldIfNotNull(writer, "Effect", statement.effect()); writePrincipals(writer, "Principal", statement.principals()); writePrincipals(writer, "NotPrincipal", statement.notPrincipals()); writeValueArrayField(writer, "Action", statement.actions()); writeValueArrayField(writer, "NotAction", statement.notActions()); writeValueArrayField(writer, "Resource", statement.resources()); writeValueArrayField(writer, "NotResource", statement.notResources()); writeConditions(writer, statement.conditions()); writer.writeEndObject(); } private void writePrincipals(JsonWriter writer, String fieldName, List<IamPrincipal> principals) { if (principals.isEmpty()) { return; } if (principals.size() == 1 && principals.get(0).equals(IamPrincipal.ALL)) { writeFieldIfNotNull(writer, fieldName, IamPrincipal.ALL.id()); return; } principals.forEach(p -> Validate.isTrue(!IamPrincipal.ALL.equals(p), "IamPrincipal.ALL must not be combined with other principals.")); Map<IamPrincipalType, List<String>> aggregatedPrincipals = new LinkedHashMap<>(); principals.forEach(principal -> { aggregatedPrincipals.computeIfAbsent(principal.type(), t -> new ArrayList<>()) .add(principal.id()); }); writer.writeFieldName(fieldName); writer.writeStartObject(); aggregatedPrincipals.forEach((principalType, ids) -> { writeArrayField(writer, principalType.value(), ids); }); writer.writeEndObject(); } private void writeConditions(JsonWriter writer, List<IamCondition> conditions) { if (conditions.isEmpty()) { return; } Map<IamConditionOperator, Map<IamConditionKey, List<String>>> aggregatedConditions = new LinkedHashMap<>(); conditions.forEach(condition -> { aggregatedConditions.computeIfAbsent(condition.operator(), t -> new LinkedHashMap<>()) .computeIfAbsent(condition.key(), t -> new ArrayList<>()) .add(condition.value()); }); writer.writeFieldName("Condition"); writer.writeStartObject(); aggregatedConditions.forEach((operator, keyValues) -> { writer.writeFieldName(operator.value()); writer.writeStartObject(); keyValues.forEach((key, values) -> { writeArrayField(writer, key.value(), values); }); writer.writeEndObject(); }); writer.writeEndObject(); } private void writeValueArrayField(JsonWriter writer, String fieldName, List<? extends IamValue> fieldValues) { List<String> values = new ArrayList<>(fieldValues.size()); fieldValues.forEach(v -> values.add(v.value())); writeArrayField(writer, fieldName, values); } private void writeArrayField(JsonWriter writer, String fieldName, List<String> fieldValues) { if (fieldValues.isEmpty()) { return; } if (fieldValues.size() == 1) { writeFieldIfNotNull(writer, fieldName, fieldValues.get(0)); return; } writer.writeFieldName(fieldName); writer.writeStartArray(); fieldValues.forEach(writer::writeValue); writer.writeEndArray(); } private void writeFieldIfNotNull(JsonWriter writer, String key, IamValue value) { if (value == null) { return; } writeFieldIfNotNull(writer, key, value.value()); } private void writeFieldIfNotNull(JsonWriter writer, String key, String value) { if (value != null) { writer.writeFieldName(key); writer.writeValue(value); } } @Override public Builder toBuilder() { return new Builder(this); } public static class Builder implements IamPolicyWriter.Builder { private Boolean prettyPrint; private Builder() { } private Builder(DefaultIamPolicyWriter writer) { this.prettyPrint = writer.prettyPrint; } @Override public IamPolicyWriter.Builder prettyPrint(Boolean prettyPrint) { this.prettyPrint = prettyPrint; return this; } @Override public IamPolicyWriter build() { return new DefaultIamPolicyWriter(this); } } }
3,956
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamConditionKey.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamConditionKey; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamConditionKey}. * * @see IamConditionKey#create */ @SdkInternalApi public final class DefaultIamConditionKey implements IamConditionKey { @NotNull private final String value; public DefaultIamConditionKey(String value) { this.value = Validate.paramNotNull(value, "conditionKeyValue"); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamConditionKey that = (DefaultIamConditionKey) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamConditionKey") .add("value", value) .build(); } }
3,957
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamResource.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamResource; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamResource}. * * @see IamResource#create */ @SdkInternalApi public final class DefaultIamResource implements IamResource { @NotNull private final String value; public DefaultIamResource(String value) { this.value = Validate.paramNotNull(value, "resourceValue"); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamResource that = (DefaultIamResource) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamResource") .add("value", value) .build(); } }
3,958
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamStatement.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.policybuilder.iam.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamAction; import software.amazon.awssdk.policybuilder.iam.IamCondition; import software.amazon.awssdk.policybuilder.iam.IamConditionKey; import software.amazon.awssdk.policybuilder.iam.IamConditionOperator; import software.amazon.awssdk.policybuilder.iam.IamEffect; import software.amazon.awssdk.policybuilder.iam.IamPrincipal; import software.amazon.awssdk.policybuilder.iam.IamPrincipalType; import software.amazon.awssdk.policybuilder.iam.IamResource; import software.amazon.awssdk.policybuilder.iam.IamStatement; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamStatement}. * * @see IamStatement#builder */ @SdkInternalApi public final class DefaultIamStatement implements IamStatement { private final String sid; @NotNull private final IamEffect effect; @NotNull private final List<IamPrincipal> principals; @NotNull private final List<IamPrincipal> notPrincipals; @NotNull private final List<IamAction> actions; @NotNull private final List<IamAction> notActions; @NotNull private final List<IamResource> resources; @NotNull private final List<IamResource> notResources; @NotNull private final List<IamCondition> conditions; public DefaultIamStatement(Builder builder) { this.sid = builder.sid; this.effect = Validate.paramNotNull(builder.effect, "statementEffect"); this.principals = new ArrayList<>(builder.principals); this.notPrincipals = new ArrayList<>(builder.notPrincipals); this.actions = new ArrayList<>(builder.actions); this.notActions = new ArrayList<>(builder.notActions); this.resources = new ArrayList<>(builder.resources); this.notResources = new ArrayList<>(builder.notResources); this.conditions = new ArrayList<>(builder.conditions); } public static Builder builder() { return new Builder(); } @Override public String sid() { return sid; } @Override public IamEffect effect() { return effect; } @Override public List<IamPrincipal> principals() { return Collections.unmodifiableList(principals); } @Override public List<IamPrincipal> notPrincipals() { return Collections.unmodifiableList(notPrincipals); } @Override public List<IamAction> actions() { return Collections.unmodifiableList(actions); } @Override public List<IamAction> notActions() { return Collections.unmodifiableList(notActions); } @Override public List<IamResource> resources() { return Collections.unmodifiableList(resources); } @Override public List<IamResource> notResources() { return Collections.unmodifiableList(notResources); } @Override public List<IamCondition> conditions() { return Collections.unmodifiableList(conditions); } @Override public IamStatement.Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamStatement that = (DefaultIamStatement) o; if (!Objects.equals(sid, that.sid)) { return false; } if (!effect.equals(that.effect)) { return false; } if (!principals.equals(that.principals)) { return false; } if (!notPrincipals.equals(that.notPrincipals)) { return false; } if (!actions.equals(that.actions)) { return false; } if (!notActions.equals(that.notActions)) { return false; } if (!resources.equals(that.resources)) { return false; } if (!notResources.equals(that.notResources)) { return false; } if (!conditions.equals(that.conditions)) { return false; } return true; } @Override public int hashCode() { int result = sid != null ? sid.hashCode() : 0; result = 31 * result + effect.hashCode(); result = 31 * result + principals.hashCode(); result = 31 * result + notPrincipals.hashCode(); result = 31 * result + actions.hashCode(); result = 31 * result + notActions.hashCode(); result = 31 * result + resources.hashCode(); result = 31 * result + notResources.hashCode(); result = 31 * result + conditions.hashCode(); return result; } @Override public String toString() { return ToString.builder("IamStatement") .add("sid", sid) .add("effect", effect) .add("principals", principals.isEmpty() ? null : principals) .add("notPrincipals", notPrincipals.isEmpty() ? null : notPrincipals) .add("actions", actions.isEmpty() ? null : actions) .add("notActions", notActions.isEmpty() ? null : notActions) .add("resources", resources.isEmpty() ? null : resources) .add("notResources", notResources.isEmpty() ? null : notResources) .add("conditions", conditions.isEmpty() ? null : conditions) .build(); } public static class Builder implements IamStatement.Builder { private String sid; private IamEffect effect; private final List<IamPrincipal> principals = new ArrayList<>(); private final List<IamPrincipal> notPrincipals = new ArrayList<>(); private final List<IamAction> actions = new ArrayList<>(); private final List<IamAction> notActions = new ArrayList<>(); private final List<IamResource> resources = new ArrayList<>(); private final List<IamResource> notResources = new ArrayList<>(); private final List<IamCondition> conditions = new ArrayList<>(); private Builder() { } private Builder(DefaultIamStatement statement) { this.sid = statement.sid; this.effect = statement.effect; this.principals.addAll(statement.principals); this.notPrincipals.addAll(statement.notPrincipals); this.actions.addAll(statement.actions); this.notActions.addAll(statement.notActions); this.resources.addAll(statement.resources); this.notResources.addAll(statement.notResources); this.conditions.addAll(statement.conditions); } @Override public IamStatement.Builder sid(String sid) { this.sid = sid; return this; } @Override public IamStatement.Builder effect(IamEffect effect) { this.effect = effect; return this; } @Override public IamStatement.Builder effect(String effect) { this.effect = IamEffect.create(effect); return this; } @Override public IamStatement.Builder principals(Collection<IamPrincipal> principals) { this.principals.clear(); if (principals != null) { this.principals.addAll(principals); } return this; } @Override public IamStatement.Builder addPrincipal(IamPrincipal principal) { Validate.paramNotNull(principal, "principal"); this.principals.add(principal); return this; } @Override public IamStatement.Builder addPrincipal(Consumer<IamPrincipal.Builder> principal) { Validate.paramNotNull(principal, "principal"); this.principals.add(IamPrincipal.builder().applyMutation(principal).build()); return this; } @Override public IamStatement.Builder addPrincipal(IamPrincipalType iamPrincipalType, String principal) { return addPrincipal(IamPrincipal.create(iamPrincipalType, principal)); } @Override public IamStatement.Builder addPrincipal(String iamPrincipalType, String principal) { return addPrincipal(IamPrincipal.create(iamPrincipalType, principal)); } @Override public IamStatement.Builder addPrincipals(IamPrincipalType principalType, Collection<String> principals) { Validate.paramNotNull(principalType, "principals"); for (String principal : principals) { this.principals.add(IamPrincipal.create(principalType, principal)); } return this; } @Override public IamStatement.Builder addPrincipals(String principalType, Collection<String> principals) { return addPrincipals(IamPrincipalType.create(principalType), principals); } @Override public IamStatement.Builder notPrincipals(Collection<IamPrincipal> notPrincipals) { this.notPrincipals.clear(); if (notPrincipals != null) { this.notPrincipals.addAll(notPrincipals); } return this; } @Override public IamStatement.Builder addNotPrincipal(IamPrincipal notPrincipal) { Validate.paramNotNull(notPrincipal, "notPrincipal"); this.notPrincipals.add(notPrincipal); return this; } @Override public IamStatement.Builder addNotPrincipal(Consumer<IamPrincipal.Builder> notPrincipal) { Validate.paramNotNull(notPrincipal, "notPrincipal"); this.notPrincipals.add(IamPrincipal.builder().applyMutation(notPrincipal).build()); return this; } @Override public IamStatement.Builder addNotPrincipal(IamPrincipalType iamPrincipalType, String principal) { return addNotPrincipal(IamPrincipal.create(iamPrincipalType, principal)); } @Override public IamStatement.Builder addNotPrincipal(String iamPrincipalType, String principal) { return addNotPrincipal(IamPrincipal.create(iamPrincipalType, principal)); } @Override public IamStatement.Builder addNotPrincipals(IamPrincipalType notPrincipalType, Collection<String> notPrincipals) { Validate.paramNotNull(notPrincipals, "notPrincipals"); for (String notPrincipal : notPrincipals) { this.notPrincipals.add(IamPrincipal.create(notPrincipalType, notPrincipal)); } return this; } @Override public IamStatement.Builder addNotPrincipals(String notPrincipalType, Collection<String> notPrincipals) { return addNotPrincipals(IamPrincipalType.create(notPrincipalType), notPrincipals); } @Override public IamStatement.Builder actions(Collection<IamAction> actions) { this.actions.clear(); if (actions != null) { this.actions.addAll(actions); } return this; } @Override public IamStatement.Builder actionIds(Collection<String> actions) { this.actions.clear(); if (actions != null) { actions.forEach(this::addAction); } return this; } @Override public IamStatement.Builder addAction(IamAction action) { Validate.paramNotNull(action, "action"); this.actions.add(action); return this; } @Override public IamStatement.Builder addAction(String action) { this.actions.add(IamAction.create(action)); return this; } @Override public IamStatement.Builder notActions(Collection<IamAction> notActions) { this.notActions.clear(); if (notActions != null) { this.notActions.addAll(notActions); } return this; } @Override public IamStatement.Builder notActionIds(Collection<String> notActions) { this.notActions.clear(); if (notActions != null) { notActions.forEach(this::addNotAction); } return this; } @Override public IamStatement.Builder addNotAction(IamAction notAction) { Validate.paramNotNull(notAction, "notAction"); this.notActions.add(notAction); return this; } @Override public IamStatement.Builder addNotAction(String notAction) { this.notActions.add(IamAction.create(notAction)); return this; } @Override public IamStatement.Builder resources(Collection<IamResource> resources) { this.resources.clear(); if (resources != null) { this.resources.addAll(resources); } return this; } @Override public IamStatement.Builder resourceIds(Collection<String> resources) { this.resources.clear(); if (resources != null) { resources.forEach(this::addResource); } return this; } @Override public IamStatement.Builder addResource(IamResource resource) { Validate.paramNotNull(resource, "resource"); this.resources.add(resource); return this; } @Override public IamStatement.Builder addResource(String resource) { this.resources.add(IamResource.create(resource)); return this; } @Override public IamStatement.Builder notResources(Collection<IamResource> notResources) { this.notResources.clear(); if (notResources != null) { this.notResources.addAll(notResources); } return this; } @Override public IamStatement.Builder notResourceIds(Collection<String> notResources) { this.notResources.clear(); if (notResources != null) { notResources.forEach(this::addNotResource); } return this; } @Override public IamStatement.Builder addNotResource(IamResource notResource) { this.notResources.add(notResource); return this; } @Override public IamStatement.Builder addNotResource(String notResource) { this.notResources.add(IamResource.create(notResource)); return this; } @Override public IamStatement.Builder conditions(Collection<IamCondition> conditions) { this.conditions.clear(); if (conditions != null) { this.conditions.addAll(conditions); } return this; } @Override public IamStatement.Builder addCondition(IamCondition condition) { Validate.paramNotNull(condition, "condition"); this.conditions.add(condition); return this; } @Override public IamStatement.Builder addCondition(Consumer<IamCondition.Builder> condition) { Validate.paramNotNull(condition, "condition"); this.conditions.add(IamCondition.builder().applyMutation(condition).build()); return this; } @Override public IamStatement.Builder addCondition(IamConditionOperator operator, IamConditionKey key, String value) { this.conditions.add(IamCondition.create(operator, key, value)); return this; } @Override public IamStatement.Builder addCondition(IamConditionOperator operator, String key, String value) { return addCondition(operator, IamConditionKey.create(key), value); } @Override public IamStatement.Builder addCondition(String operator, String key, String value) { this.conditions.add(IamCondition.create(operator, key, value)); return this; } @Override public IamStatement.Builder addConditions(IamConditionOperator operator, IamConditionKey key, Collection<String> values) { Validate.paramNotNull(values, "values"); for (String value : values) { this.conditions.add(IamCondition.create(operator, key, value)); } return this; } @Override public IamStatement.Builder addConditions(IamConditionOperator operator, String key, Collection<String> values) { return addConditions(operator, IamConditionKey.create(key), values); } @Override public IamStatement.Builder addConditions(String operator, String key, Collection<String> values) { return addConditions(IamConditionOperator.create(operator), IamConditionKey.create(key), values); } @Override public IamStatement build() { return new DefaultIamStatement(this); } } }
3,959
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamPrincipalType.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamPrincipalType; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamPrincipalType}. * * @see IamPrincipalType#create */ @SdkInternalApi public final class DefaultIamPrincipalType implements IamPrincipalType { @NotNull private final String value; public DefaultIamPrincipalType(String value) { this.value = Validate.paramNotNull(value, "principalTypeValue"); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamPrincipalType that = (DefaultIamPrincipalType) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamPrincipalType") .add("value", value) .build(); } }
3,960
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamConditionOperator.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamConditionOperator; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamConditionOperator}. * * @see IamConditionOperator#create */ @SdkInternalApi public final class DefaultIamConditionOperator implements IamConditionOperator { @NotNull private final String value; public DefaultIamConditionOperator(String value) { this.value = Validate.paramNotNull(value, "conditionOperatorValue"); } @Override public IamConditionOperator addPrefix(String prefix) { Validate.paramNotNull(prefix, "prefix"); return IamConditionOperator.create(prefix + value); } @Override public IamConditionOperator addSuffix(String suffix) { Validate.paramNotNull(suffix, "suffix"); return IamConditionOperator.create(value + suffix); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamConditionOperator that = (DefaultIamConditionOperator) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamConditionOperator") .add("value", value) .build(); } }
3,961
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamEffect.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamEffect; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamEffect}. * * @see IamEffect#create */ @SdkInternalApi public final class DefaultIamEffect implements IamEffect { @NotNull private final String value; public DefaultIamEffect(String value) { this.value = Validate.paramNotNull(value, "effectValue"); } @Override public String value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamEffect that = (DefaultIamEffect) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return ToString.builder("IamEffect") .add("value", value) .build(); } }
3,962
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamPrincipal.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamPrincipal; import software.amazon.awssdk.policybuilder.iam.IamPrincipalType; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamPrincipal}. * * @see IamPrincipal#create */ @SdkInternalApi public final class DefaultIamPrincipal implements IamPrincipal { @NotNull private final IamPrincipalType type; @NotNull private final String id; private DefaultIamPrincipal(Builder builder) { this.type = Validate.paramNotNull(builder.type, "principalType"); this.id = Validate.paramNotNull(builder.id, "principalId"); } public static Builder builder() { return new Builder(); } @Override public IamPrincipalType type() { return type; } @Override public String id() { return id; } @Override public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamPrincipal that = (DefaultIamPrincipal) o; if (!type.equals(that.type)) { return false; } return id.equals(that.id); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + id.hashCode(); return result; } @Override public String toString() { return ToString.builder("IamPrincipal") .add("type", type.value()) .add("id", id) .build(); } public static class Builder implements IamPrincipal.Builder { private IamPrincipalType type; private String id; private Builder() { } private Builder(DefaultIamPrincipal principal) { this.type = principal.type; this.id = principal.id; } @Override public IamPrincipal.Builder type(IamPrincipalType type) { this.type = type; return this; } @Override public IamPrincipal.Builder type(String type) { this.type = type == null ? null : IamPrincipalType.create(type); return this; } @Override public IamPrincipal.Builder id(String id) { this.id = id; return this; } @Override public IamPrincipal build() { return new DefaultIamPrincipal(this); } } }
3,963
0
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam
Create_ds/aws-sdk-java-v2/services-custom/iam-policy-builder/src/main/java/software/amazon/awssdk/policybuilder/iam/internal/DefaultIamCondition.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.policybuilder.iam.internal; import software.amazon.awssdk.annotations.NotNull; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.policybuilder.iam.IamCondition; import software.amazon.awssdk.policybuilder.iam.IamConditionKey; import software.amazon.awssdk.policybuilder.iam.IamConditionOperator; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link IamCondition}. * * @see IamCondition#create */ @SdkInternalApi public final class DefaultIamCondition implements IamCondition { @NotNull private final IamConditionOperator operator; @NotNull private final IamConditionKey key; @NotNull private final String value; private DefaultIamCondition(Builder builder) { this.operator = Validate.paramNotNull(builder.operator, "conditionOperator"); this.key = Validate.paramNotNull(builder.key, "conditionKey"); this.value = Validate.paramNotNull(builder.value, "conditionValue"); } public static Builder builder() { return new Builder(); } @Override public IamConditionOperator operator() { return operator; } @Override public IamConditionKey key() { return key; } @Override public String value() { return value; } @Override public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIamCondition that = (DefaultIamCondition) o; if (!operator.equals(that.operator)) { return false; } if (!key.equals(that.key)) { return false; } return value.equals(that.value); } @Override public int hashCode() { int result = operator.hashCode(); result = 31 * result + key.hashCode(); result = 31 * result + value.hashCode(); return result; } @Override public String toString() { return ToString.builder("IamCondition") .add("operator", operator.value()) .add("key", key.value()) .add("value", value) .build(); } public static class Builder implements IamCondition.Builder { private IamConditionOperator operator; private IamConditionKey key; private String value; private Builder() { } private Builder(DefaultIamCondition condition) { this.operator = condition.operator; this.key = condition.key; this.value = condition.value; } @Override public IamCondition.Builder operator(IamConditionOperator operator) { this.operator = operator; return this; } @Override public IamCondition.Builder operator(String operator) { this.operator = operator == null ? null : IamConditionOperator.create(operator); return this; } @Override public IamCondition.Builder key(IamConditionKey key) { this.key = key; return this; } @Override public IamCondition.Builder key(String key) { this.key = key == null ? null : IamConditionKey.create(key); return this; } @Override public IamCondition.Builder value(String value) { this.value = value; return this; } @Override public IamCondition build() { return new DefaultIamCondition(this); } } }
3,964
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/progress/LoggingTransferListenerTest.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.transfer.s3.progress; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.List; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LogEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.testutils.LogCaptor; import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer; import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgress; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.internal.progress.TransferListenerContext; public class LoggingTransferListenerTest { private static final long TRANSFER_SIZE_IN_BYTES = 1024L; private DefaultTransferProgress progress; private TransferListenerContext context; private LoggingTransferListener listener; @BeforeEach public void setUp() throws Exception { TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .totalBytes(TRANSFER_SIZE_IN_BYTES) .build(); progress = new DefaultTransferProgress(snapshot); context = TransferListenerContext.builder() .request(mock(TransferObjectRequest.class)) .progressSnapshot(snapshot) .build(); listener = LoggingTransferListener.create(); } @Test public void test_defaultListener_successfulTransfer() { try (LogCaptor logCaptor = LogCaptor.create()) { invokeSuccessfulLifecycle(); List<LogEvent> events = logCaptor.loggedEvents(); assertLogged(events, Level.INFO, "Transfer initiated..."); assertLogged(events, Level.INFO, "| | 0.0%"); assertLogged(events, Level.INFO, "|= | 5.0%"); assertLogged(events, Level.INFO, "|== | 10.0%"); assertLogged(events, Level.INFO, "|=== | 15.0%"); assertLogged(events, Level.INFO, "|==== | 20.0%"); assertLogged(events, Level.INFO, "|===== | 25.0%"); assertLogged(events, Level.INFO, "|====== | 30.0%"); assertLogged(events, Level.INFO, "|======= | 35.0%"); assertLogged(events, Level.INFO, "|======== | 40.0%"); assertLogged(events, Level.INFO, "|========= | 45.0%"); assertLogged(events, Level.INFO, "|========== | 50.0%"); assertLogged(events, Level.INFO, "|=========== | 55.0%"); assertLogged(events, Level.INFO, "|============ | 60.0%"); assertLogged(events, Level.INFO, "|============= | 65.0%"); assertLogged(events, Level.INFO, "|============== | 70.0%"); assertLogged(events, Level.INFO, "|=============== | 75.0%"); assertLogged(events, Level.INFO, "|================ | 80.0%"); assertLogged(events, Level.INFO, "|================= | 85.0%"); assertLogged(events, Level.INFO, "|================== | 90.0%"); assertLogged(events, Level.INFO, "|=================== | 95.0%"); assertLogged(events, Level.INFO, "|====================| 100.0%"); assertLogged(events, Level.INFO, "Transfer complete!"); assertThat(events).isEmpty(); } } @Test public void test_customTicksListener_successfulTransfer() { try (LogCaptor logCaptor = LogCaptor.create()) { listener = LoggingTransferListener.create(5); invokeSuccessfulLifecycle(); List<LogEvent> events = logCaptor.loggedEvents(); assertLogged(events, Level.INFO, "Transfer initiated..."); assertLogged(events, Level.INFO, "| | 0.0%"); assertLogged(events, Level.INFO, "|= | 20.0%"); assertLogged(events, Level.INFO, "|== | 40.0%"); assertLogged(events, Level.INFO, "|=== | 60.0%"); assertLogged(events, Level.INFO, "|==== | 80.0%"); assertLogged(events, Level.INFO, "|=====| 100.0%"); assertLogged(events, Level.INFO, "Transfer complete!"); assertThat(events).isEmpty(); } } private void invokeSuccessfulLifecycle() { listener.transferInitiated(context); for (int i = 0; i <= TRANSFER_SIZE_IN_BYTES; i++) { int bytes = i; listener.bytesTransferred(context.copy(c -> c.progressSnapshot( progress.updateAndGet(p -> p.transferredBytes((long) bytes))))); } listener.transferComplete(context.copy(b -> b.progressSnapshot(progress.snapshot()) .completedTransfer(mock(CompletedObjectTransfer.class)))); } private static void assertLogged(List<LogEvent> events, org.apache.logging.log4j.Level level, String message) { assertThat(events).withFailMessage("Expecting events to not be empty").isNotEmpty(); LogEvent event = events.remove(0); String msg = event.getMessage().getFormattedMessage(); assertThat(msg).isEqualTo(message); assertThat(event.getLevel()).isEqualTo(level); } }
3,965
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/util/ChecksumUtils.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.transfer.s3.util; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; /** * Utilities for computing the SHA-256 checksums of various binary objects. */ public final class ChecksumUtils { public static byte[] computeCheckSum(InputStream is) throws IOException { MessageDigest instance = createMessageDigest(); byte buff[] = new byte[16384]; int read; while ((read = is.read(buff)) != -1) { instance.update(buff, 0, read); } return instance.digest(); } public static byte[] computeCheckSum(byte[] bytes) { MessageDigest instance = createMessageDigest(); instance.update(bytes); return instance.digest(); } public static byte[] computeCheckSum(ByteBuffer bb) { MessageDigest instance = createMessageDigest(); instance.update(bb); bb.rewind(); return instance.digest(); } public static byte[] computeCheckSum(List<ByteBuffer> buffers) { MessageDigest instance = createMessageDigest(); buffers.forEach(bb -> { instance.update(bb); bb.rewind(); }); return instance.digest(); } private static MessageDigest createMessageDigest() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Unable to create SHA-256 MessageDigest instance", e); } } }
3,966
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/util/ResumableRequestConverterTest.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.transfer.s3.util; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.transfer.s3.internal.utils.ResumableRequestConverter.toDownloadFileRequestAndTransformer; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.time.Instant; import java.util.UUID; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload; import software.amazon.awssdk.utils.Pair; class ResumableRequestConverterTest { private File file; @BeforeEach public void methodSetup() throws IOException { file = RandomTempFile.createTempFile("test", UUID.randomUUID().toString()); Files.write(file.toPath(), RandomStringUtils.randomAlphanumeric(1000).getBytes(StandardCharsets.UTF_8)); } @AfterEach public void methodTeardown() { file.delete(); } @Test void toDownloadFileAndTransformer_notModified_shouldSetRangeAccordingly() { Instant s3ObjectLastModified = Instant.now(); GetObjectRequest getObjectRequest = getObjectRequest(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); ResumableFileDownload resumableFileDownload = ResumableFileDownload.builder() .bytesTransferred(file.length()) .s3ObjectLastModified(s3ObjectLastModified) .fileLastModified(fileLastModified) .downloadFileRequest(downloadFileRequest) .build(); Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>> actual = toDownloadFileRequestAndTransformer(resumableFileDownload, headObjectResponse(s3ObjectLastModified), downloadFileRequest); verifyActualGetObjectRequest(getObjectRequest, actual.left().getObjectRequest(), "bytes=1000-2000"); } @Test void toDownloadFileAndTransformer_s3ObjectModified_shouldStartFromBeginning() { Instant s3ObjectLastModified = Instant.now().minusSeconds(5); GetObjectRequest getObjectRequest = getObjectRequest(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); ResumableFileDownload resumableFileDownload = ResumableFileDownload.builder() .bytesTransferred(1000L) .s3ObjectLastModified(s3ObjectLastModified) .fileLastModified(fileLastModified) .downloadFileRequest(downloadFileRequest) .build(); Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>> actual = toDownloadFileRequestAndTransformer(resumableFileDownload, headObjectResponse(Instant.now()), downloadFileRequest); verifyActualGetObjectRequest(getObjectRequest, actual.left().getObjectRequest(), null); } @Test void toDownloadFileAndTransformer_fileLastModifiedTimeChanged_shouldStartFromBeginning() throws IOException { Instant s3ObjectLastModified = Instant.now(); GetObjectRequest getObjectRequest = getObjectRequest(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); Instant fileLastModified = Instant.now().minusSeconds(10); ResumableFileDownload resumableFileDownload = ResumableFileDownload.builder() .bytesTransferred(1000L) .s3ObjectLastModified(s3ObjectLastModified) .fileLastModified(fileLastModified) .downloadFileRequest(downloadFileRequest) .build(); Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>> actual = toDownloadFileRequestAndTransformer(resumableFileDownload, headObjectResponse(s3ObjectLastModified), downloadFileRequest); verifyActualGetObjectRequest(getObjectRequest, actual.left().getObjectRequest(), null); } @Test void toDownloadFileAndTransformer_fileLengthChanged_shouldStartFromBeginning() { Instant s3ObjectLastModified = Instant.now(); GetObjectRequest getObjectRequest = getObjectRequest(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); Instant fileLastModified = Instant.now().minusSeconds(10); ResumableFileDownload resumableFileDownload = ResumableFileDownload.builder() .bytesTransferred(1100L) .s3ObjectLastModified(s3ObjectLastModified) .fileLastModified(fileLastModified) .downloadFileRequest(downloadFileRequest) .build(); Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>> actual = toDownloadFileRequestAndTransformer(resumableFileDownload, headObjectResponse(s3ObjectLastModified), downloadFileRequest); verifyActualGetObjectRequest(getObjectRequest, actual.left().getObjectRequest(), null); } private static void verifyActualGetObjectRequest(GetObjectRequest originalRequest, GetObjectRequest actualRequest, String range) { assertThat(actualRequest.bucket()).isEqualTo(originalRequest.bucket()); assertThat(actualRequest.key()).isEqualTo(originalRequest.key()); assertThat(actualRequest.range()).isEqualTo(range); } private static HeadObjectResponse headObjectResponse(Instant s3ObjectLastModified) { return HeadObjectResponse .builder() .contentLength(2000L) .lastModified(s3ObjectLastModified) .build(); } private static GetObjectRequest getObjectRequest() { return GetObjectRequest.builder() .key("key") .bucket("bucket") .build(); } }
3,967
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/util/S3ApiCallMockUtils.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.transfer.s3.util; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.transfer.s3.internal.ListObjectsHelper; public class S3ApiCallMockUtils { private S3ApiCallMockUtils() { } public static void stubSuccessfulListObjects(ListObjectsHelper helper, String... keys) { List<S3Object> s3Objects = Arrays.stream(keys).map(k -> S3Object.builder().key(k).build()).collect(Collectors.toList()); when(helper.listS3ObjectsRecursively(any(ListObjectsV2Request.class))).thenReturn(SdkPublisher.adapt(Flowable.fromIterable(s3Objects))); } }
3,968
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/AsyncBufferingSubscriberTckTest.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.transfer.s3.internal; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class AsyncBufferingSubscriberTckTest extends SubscriberWhiteboxVerification<String> { protected AsyncBufferingSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<String> createSubscriber(SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<String> whiteboxSubscriberProbe) { return new AsyncBufferingSubscriber<String>(s -> CompletableFuture.completedFuture("test"), new CompletableFuture<>(), 1) { @Override public void onSubscribe(Subscription s) { super.onSubscribe(s); whiteboxSubscriberProbe.registerOnSubscribe(new SubscriberWhiteboxVerification.SubscriberPuppet() { @Override public void triggerRequest(long l) { s.request(l); } @Override public void signalCancel() { s.cancel(); } }); } @Override public void onNext(String item) { super.onNext(item); whiteboxSubscriberProbe.registerOnNext(item); } @Override public void onError(Throwable t) { super.onError(t); whiteboxSubscriberProbe.registerOnError(t); } @Override public void onComplete() { super.onComplete(); whiteboxSubscriberProbe.registerOnComplete(); } }; } @Override public String createElement(int i) { return "test"; } }
3,969
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultFileUploadTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Paths; import java.util.concurrent.CompletableFuture; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileUpload; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.progress.TransferProgress; class DefaultFileUploadTest { @Test void equals_hashcode() { EqualsVerifier.forClass(DefaultFileUpload.class) .withNonnullFields("completionFuture", "progress", "request") .verify(); } @Test void pause_shouldThrowUnsupportedOperation() { TransferProgress transferProgress = Mockito.mock(TransferProgress.class); UploadFileRequest request = UploadFileRequest.builder() .source(Paths.get("test")) .putObjectRequest(p -> p.key("test").bucket("bucket")) .build(); FileUpload fileUpload = new DefaultFileUpload(new CompletableFuture<>(), transferProgress, request); assertThatThrownBy(() -> fileUpload.pause()).isInstanceOf(UnsupportedOperationException.class); } }
3,970
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3CrtTransferProgressListenerTest.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.transfer.s3.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.io.IOException; import java.net.URI; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.CaptureTransferListener; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; import software.amazon.awssdk.transfer.s3.progress.TransferListener; @WireMockTest public class S3CrtTransferProgressListenerTest { public static final String ERROR_CODE = "NoSuchBucket"; public static final String ERROR_MESSAGE = "We encountered an internal error. Please try again."; public static final String ERROR_BODY = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + " <Code>" + ERROR_CODE + "</Code>\n" + " <Message>" + ERROR_MESSAGE + "</Message>\n" + "</Error>"; private static final String EXAMPLE_BUCKET = "Example-Bucket"; private static final String TEST_KEY = "16mib_file.dat"; private static final int OBJ_SIZE = 16 * 1024; private RandomTempFile testFile; @BeforeEach public void setUp() throws IOException { testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE); } private static void assertMockOnFailure(TransferListener transferListenerMock) { Mockito.verify(transferListenerMock, times(1)).bytesTransferred(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(1)).transferFailed(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(1)).transferInitiated(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(0)).transferComplete(ArgumentMatchers.any()); } private S3CrtAsyncClientBuilder getAsyncClientBuilder(WireMockRuntimeInfo wm) { return S3AsyncClient.crtBuilder() .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @Test void listeners_reports_ErrorsWithValidPayload(WireMockRuntimeInfo wm) throws InterruptedException { TransferListener transferListenerMock = mock(TransferListener.class); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(404).withBody(ERROR_BODY))); S3TransferManager tm = new GenericS3TransferManager(getAsyncClientBuilder(wm).build(), mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class), mock(DownloadDirectoryHelper.class)); CaptureTransferListener transferListener = new CaptureTransferListener(); FileUpload fileUpload = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket(EXAMPLE_BUCKET).key("KEY")) .source(testFile) .addTransferListener(LoggingTransferListener.create()) .addTransferListener(transferListener) .addTransferListener(transferListenerMock) .build()); assertThatExceptionOfType(CompletionException.class).isThrownBy(() -> fileUpload.completionFuture().join()); Thread.sleep(500); assertThat(transferListener.getExceptionCaught()).isInstanceOf(NoSuchBucketException.class); assertThat(transferListener.isTransferComplete()).isFalse(); assertThat(transferListener.isTransferInitiated()).isTrue(); assertMockOnFailure(transferListenerMock); } @Test void listeners_reports_ErrorsWithValidInValidPayload(WireMockRuntimeInfo wm) throws InterruptedException { TransferListener transferListenerMock = mock(TransferListener.class); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(404).withBody("?"))); S3TransferManager tm = new GenericS3TransferManager(getAsyncClientBuilder(wm).build(), mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class), mock(DownloadDirectoryHelper.class)); CaptureTransferListener transferListener = new CaptureTransferListener(); FileUpload fileUpload = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket(EXAMPLE_BUCKET).key("KEY")) .source(testFile) .addTransferListener(LoggingTransferListener.create()) .addTransferListener(transferListener) .addTransferListener(transferListenerMock) .build()); assertThatExceptionOfType(CompletionException.class).isThrownBy(() -> fileUpload.completionFuture().join()); Thread.sleep(500); assertThat(transferListener.getExceptionCaught()).isInstanceOf(S3Exception.class); assertThat(transferListener.isTransferComplete()).isFalse(); assertThat(transferListener.isTransferInitiated()).isTrue(); assertMockOnFailure(transferListenerMock); } @Test void listeners_reports_ErrorsWhenCancelled(WireMockRuntimeInfo wm) throws InterruptedException { TransferListener transferListenerMock = mock(TransferListener.class); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); S3TransferManager tm = new GenericS3TransferManager(getAsyncClientBuilder(wm).build(), mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class), mock(DownloadDirectoryHelper.class)); CaptureTransferListener transferListener = new CaptureTransferListener(); tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket(EXAMPLE_BUCKET).key("KEY")) .source(testFile) .addTransferListener(LoggingTransferListener.create()) .addTransferListener(transferListener) .addTransferListener(transferListenerMock) .build()).completionFuture().cancel(true); Thread.sleep(500); assertThat(transferListener.getExceptionCaught()).isInstanceOf(CancellationException.class); assertThat(transferListener.isTransferComplete()).isFalse(); assertThat(transferListener.isTransferInitiated()).isTrue(); assertMockOnFailure(transferListenerMock); } @Test void listeners_reports_ProgressWhenSuccess(WireMockRuntimeInfo wm) throws InterruptedException { TransferListener transferListenerMock = mock(TransferListener.class); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); S3TransferManager tm = new GenericS3TransferManager(getAsyncClientBuilder(wm).build(), mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class), mock(DownloadDirectoryHelper.class)); CaptureTransferListener transferListener = new CaptureTransferListener(); tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket(EXAMPLE_BUCKET).key("KEY")) .source(testFile) .addTransferListener(LoggingTransferListener.create()) .addTransferListener(transferListener) .addTransferListener(transferListenerMock) .build()).completionFuture().join(); Thread.sleep(500); assertThat(transferListener.getExceptionCaught()).isNull(); assertThat(transferListener.isTransferComplete()).isTrue(); assertThat(transferListener.isTransferInitiated()).isTrue(); Mockito.verify(transferListenerMock, times(1)).bytesTransferred(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(0)).transferFailed(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(1)).transferInitiated(ArgumentMatchers.any()); Mockito.verify(transferListenerMock, times(1)).transferComplete(ArgumentMatchers.any()); } }
3,971
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultFileDownloadTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.jimfs.Jimfs; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.time.Instant; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileDownload; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.internal.progress.ResumeTransferProgress; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload; import software.amazon.awssdk.transfer.s3.progress.TransferProgress; class DefaultFileDownloadTest { private static final long OBJECT_CONTENT_LENGTH = 1024L; private static FileSystem fileSystem; private static File file; @BeforeAll public static void setUp() throws IOException { fileSystem = Jimfs.newFileSystem(); file = File.createTempFile("test", UUID.randomUUID().toString()); Files.write(file.toPath(), RandomStringUtils.random(2000).getBytes(StandardCharsets.UTF_8)); } @AfterAll public static void tearDown() throws IOException { file.delete(); } @Test void pause_shouldReturnCorrectly() { CompletableFuture<CompletedFileDownload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); GetObjectResponse sdkResponse = getObjectResponse(); Mockito.when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(1000L) .sdkResponse(sdkResponse) .build()); DownloadFileRequest request = getDownloadFileRequest(); DefaultFileDownload fileDownload = new DefaultFileDownload(future, transferProgress, () -> request, null); ResumableFileDownload pause = fileDownload.pause(); assertThat(pause.downloadFileRequest()).isEqualTo(request); assertThat(pause.bytesTransferred()).isEqualTo(file.length()); assertThat(pause.s3ObjectLastModified()).hasValue(sdkResponse.lastModified()); assertThat(pause.totalSizeInBytes()).hasValue(sdkResponse.contentLength()); } @Test void pause_transferAlreadyFinished_shouldReturnNormally() { GetObjectResponse getObjectResponse = GetObjectResponse.builder() .contentLength(OBJECT_CONTENT_LENGTH) .build(); CompletableFuture<CompletedFileDownload> future = CompletableFuture.completedFuture(CompletedFileDownload.builder() .response(getObjectResponse) .build()); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); Mockito.when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(OBJECT_CONTENT_LENGTH) .totalBytes(OBJECT_CONTENT_LENGTH) .sdkResponse(getObjectResponse) .build()); DefaultFileDownload fileDownload = new DefaultFileDownload(future, transferProgress, this::getDownloadFileRequest, null); ResumableFileDownload resumableFileDownload = fileDownload.pause(); assertThat(resumableFileDownload.bytesTransferred()).isEqualTo(file.length()); assertThat(resumableFileDownload.totalSizeInBytes()).hasValue(OBJECT_CONTENT_LENGTH); } @Test void pauseTwice_shouldReturnTheSame() { CompletableFuture<CompletedFileDownload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); Mockito.when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(1000L) .build()); DownloadFileRequest request = getDownloadFileRequest(); DefaultFileDownload fileDownload = new DefaultFileDownload(future, transferProgress, () -> request, null); ResumableFileDownload resumableFileDownload = fileDownload.pause(); ResumableFileDownload resumableFileDownload2 = fileDownload.pause(); assertThat(resumableFileDownload).isEqualTo(resumableFileDownload2); } @Test void progress_progressNotFinished_shouldReturnDefaultProgress() { CompletableFuture<CompletedFileDownload> completedFileDownloadFuture = new CompletableFuture<>(); CompletableFuture<TransferProgress> progressFuture = new CompletableFuture<>(); CompletableFuture<DownloadFileRequest> requestFuture = new CompletableFuture<>(); DefaultTransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(1000L) .build(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); Mockito.when(transferProgress.snapshot()).thenReturn(snapshot); DefaultFileDownload fileDownload = new DefaultFileDownload(completedFileDownloadFuture, new ResumeTransferProgress(progressFuture), () -> requestFuture.getNow(null), null); assertThat(fileDownload.progress().snapshot()).isEqualTo(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()); progressFuture.complete(transferProgress); assertThat(fileDownload.progress().snapshot()).isEqualTo(snapshot); } private DownloadFileRequest getDownloadFileRequest() { return DownloadFileRequest.builder() .destination(file) .getObjectRequest(GetObjectRequest.builder().key("KEY").bucket("BUCKET").build()) .build(); } private GetObjectResponse getObjectResponse() { return GetObjectResponse.builder() .lastModified(Instant.now()) .contentLength(OBJECT_CONTENT_LENGTH) .build(); } }
3,972
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferManagerLoggingTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LogEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.testutils.LogCaptor; import software.amazon.awssdk.transfer.s3.S3TransferManager; class TransferManagerLoggingTest { @Test void transferManager_withCrtClient_shouldNotLogWarnMessages() { try (S3AsyncClient s3Crt = S3AsyncClient.crtBuilder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar")) .build(); LogCaptor logCaptor = LogCaptor.create(Level.WARN); S3TransferManager tm = S3TransferManager.builder().s3Client(s3Crt).build()) { List<LogEvent> events = logCaptor.loggedEvents(); assertThat(events).isEmpty(); } } @Test void transferManager_withJavaClient_shouldLogWarnMessage() { try (S3AsyncClient s3Crt = S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar")) .build(); LogCaptor logCaptor = LogCaptor.create(Level.WARN); S3TransferManager tm = S3TransferManager.builder().s3Client(s3Crt).build()) { List<LogEvent> events = logCaptor.loggedEvents(); assertLogged(events, Level.WARN, "The provided DefaultS3AsyncClient is not an instance of S3CrtAsyncClient, and " + "thus multipart upload/download feature is not enabled and resumable file upload" + " is " + "not supported. To benefit from maximum throughput, consider using " + "S3AsyncClient.crtBuilder().build() instead."); } } private static void assertLogged(List<LogEvent> events, org.apache.logging.log4j.Level level, String message) { assertThat(events).withFailMessage("Expecting events to not be empty").isNotEmpty(); LogEvent event = events.remove(0); String msg = event.getMessage().getFormattedMessage(); assertThat(msg).isEqualTo(message); assertThat(event.getLevel()).isEqualTo(level); } }
3,973
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDownloadTest.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.transfer.s3.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.model.DefaultDownload; public class DefaultDownloadTest { @Test public void equals_hashcode() { EqualsVerifier.forClass(DefaultDownload.class) .withNonnullFields("completionFuture", "progress") .verify(); } }
3,974
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferProgressUpdaterTest.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.transfer.s3.internal; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.CaptureTransferListener; import software.amazon.awssdk.transfer.s3.internal.progress.TransferProgressUpdater; import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer; import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; import software.amazon.awssdk.transfer.s3.progress.TransferListener; class TransferProgressUpdaterTest { private static final long OBJ_SIZE = 16 * MB; private static File sourceFile; private CaptureTransferListener captureTransferListener; private static Stream<Arguments> contentLength() { return Stream.of( Arguments.of(OBJ_SIZE, "Total bytes equals transferred, future complete through subscriberOnNext()"), Arguments.of(OBJ_SIZE / 2, "Total bytes less than transferred, future complete through subscriberOnNext()"), Arguments.of(OBJ_SIZE * 2, "Total bytes more than transferred, future complete through subscriberOnComplete()")); } private static CompletableFuture<CompletedObjectTransfer> completedObjectResponse(long millis) { return CompletableFuture.supplyAsync(() -> { quietSleep(millis); return new CompletedObjectTransfer() { @Override public SdkResponse response() { return PutObjectResponse.builder().eTag("ABCD").build(); } }; }); } private static void quietSleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Restore interrupted status throw new RuntimeException(e); } } @BeforeEach void initiate() { captureTransferListener = new CaptureTransferListener(); } @ParameterizedTest(name = "{index} - {1}, total bytes = {0}") @MethodSource("contentLength") void registerCompletion_differentTransferredByteRatios_alwaysCompletesOnce(Long givenContentLength, String description) throws Exception { TransferObjectRequest transferRequest = Mockito.mock(TransferObjectRequest.class); CaptureTransferListener mockListener = Mockito.mock(CaptureTransferListener.class); when(transferRequest.transferListeners()).thenReturn(Arrays.asList(LoggingTransferListener.create(), mockListener, captureTransferListener)); sourceFile = new RandomTempFile(OBJ_SIZE); AsyncRequestBody requestBody = AsyncRequestBody.fromFile(sourceFile); TransferProgressUpdater transferProgressUpdater = new TransferProgressUpdater(transferRequest, givenContentLength); AsyncRequestBody asyncRequestBody = transferProgressUpdater.wrapRequestBody(requestBody); CompletableFuture<CompletedObjectTransfer> completionFuture = completedObjectResponse(10); transferProgressUpdater.registerCompletion(completionFuture); AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); captureTransferListener.getCompletionFuture().get(5, TimeUnit.SECONDS); Mockito.verify(mockListener, never()).transferFailed(ArgumentMatchers.any(TransferListener.Context.TransferFailed.class)); Mockito.verify(mockListener, times(1)).transferComplete(ArgumentMatchers.any(TransferListener.Context.TransferComplete.class)); } @Test void transferFailedWhenSubscriptionErrors() throws Exception { Long contentLength = 51L; String inputString = RandomStringUtils.randomAlphanumeric(contentLength.intValue()); TransferObjectRequest transferRequest = Mockito.mock(TransferObjectRequest.class); CaptureTransferListener mockListener = Mockito.mock(CaptureTransferListener.class); when(transferRequest.transferListeners()).thenReturn(Arrays.asList(LoggingTransferListener.create(), mockListener, captureTransferListener)); sourceFile = new RandomTempFile(OBJ_SIZE); AsyncRequestBody requestFileBody = AsyncRequestBody.fromInputStream( new ExceptionThrowingByteArrayInputStream(inputString.getBytes(), 3), contentLength, Executors.newSingleThreadExecutor()); TransferProgressUpdater transferProgressUpdater = new TransferProgressUpdater(transferRequest, contentLength); AsyncRequestBody asyncRequestBody = transferProgressUpdater.wrapRequestBody(requestFileBody); CompletableFuture<CompletedObjectTransfer> future = completedObjectResponse(10); transferProgressUpdater.registerCompletion(future); AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); assertThatExceptionOfType(ExecutionException.class).isThrownBy( () -> captureTransferListener.getCompletionFuture().get(5, TimeUnit.SECONDS)); Mockito.verify(mockListener, times(1)).transferFailed(ArgumentMatchers.any(TransferListener.Context.TransferFailed.class)); Mockito.verify(mockListener, never()).transferComplete(ArgumentMatchers.any(TransferListener.Context.TransferComplete.class)); } private static class ExceptionThrowingByteArrayInputStream extends ByteArrayInputStream { private final int exceptionPosition; public ExceptionThrowingByteArrayInputStream(byte[] buf, int exceptionPosition) { super(buf); this.exceptionPosition = exceptionPosition; } @Override public int read() { return (exceptionPosition == pos + 1) ? exceptionThrowingRead() : super.read(); } @Override public int read(byte[] b, int off, int len) { return (exceptionPosition >= pos && exceptionPosition < (pos + len)) ? exceptionThrowingReadByteArr(b, off, len) : super.read(b, off, len); } private int exceptionThrowingRead() { throw new RuntimeException("Exception occurred at position " + (pos + 1)); } private int exceptionThrowingReadByteArr(byte[] b, int off, int len) { throw new RuntimeException("Exception occurred in read(byte[]) at position " + exceptionPosition); } } }
3,975
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/ApplyUserAgentInterceptorTest.java
/* * Copyright 2010-2020 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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.services.s3.model.GetObjectRequest; class ApplyUserAgentInterceptorTest { private final ApplyUserAgentInterceptor interceptor = new ApplyUserAgentInterceptor(); @Test void s3Request_shouldModifyRequest() { GetObjectRequest getItemRequest = GetObjectRequest.builder().build(); SdkRequest sdkRequest = interceptor.modifyRequest(() -> getItemRequest, new ExecutionAttributes()); RequestOverrideConfiguration requestOverrideConfiguration = sdkRequest.overrideConfiguration().get(); assertThat(requestOverrideConfiguration.apiNames().stream().anyMatch(a -> a.name().equals("ft") && a.version().equals( "s3-transfer"))).isTrue(); } @Test void otherRequest_shouldThrowAssertionError() { SdkRequest someOtherRequest = new SdkRequest() { @Override public List<SdkField<?>> sdkFields() { return null; } @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return null; } }; assertThatThrownBy(() -> interceptor.modifyRequest(() -> someOtherRequest, new ExecutionAttributes())) .isInstanceOf(AssertionError.class); } }
3,976
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.nio.file.Paths; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.transfer.s3.model.CompletedCopy; import software.amazon.awssdk.transfer.s3.model.CompletedDownload; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.CompletedUpload; import software.amazon.awssdk.transfer.s3.model.CopyRequest; import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.DownloadRequest; import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; class S3TransferManagerTest { private S3CrtAsyncClient mockS3Crt; private S3TransferManager tm; private UploadDirectoryHelper uploadDirectoryHelper; private DownloadDirectoryHelper downloadDirectoryHelper; private TransferManagerConfiguration configuration; @BeforeEach public void methodSetup() { mockS3Crt = mock(S3CrtAsyncClient.class); uploadDirectoryHelper = mock(UploadDirectoryHelper.class); configuration = mock(TransferManagerConfiguration.class); downloadDirectoryHelper = mock(DownloadDirectoryHelper.class); tm = new GenericS3TransferManager(mockS3Crt, uploadDirectoryHelper, configuration, downloadDirectoryHelper); } @AfterEach public void methodTeardown() { tm.close(); } @Test void defaultTransferManager_shouldNotThrowException() { S3TransferManager transferManager = S3TransferManager.create(); transferManager.close(); } @Test void uploadFile_returnsResponse() { PutObjectResponse response = PutObjectResponse.builder().build(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenReturn(CompletableFuture.completedFuture(response)); CompletedFileUpload completedFileUpload = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket("bucket") .key("key")) .source(Paths.get("."))) .completionFuture() .join(); assertThat(completedFileUpload.response()).isEqualTo(response); } @Test public void upload_returnsResponse() { PutObjectResponse response = PutObjectResponse.builder().build(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenReturn(CompletableFuture.completedFuture(response)); CompletedUpload completedUpload = tm.upload(u -> u.putObjectRequest(p -> p.bucket("bucket") .key("key")) .requestBody(AsyncRequestBody.fromString("foo"))) .completionFuture() .join(); assertThat(completedUpload.response()).isEqualTo(response); } @Test public void copy_returnsResponse() { CopyObjectResponse response = CopyObjectResponse.builder().build(); when(mockS3Crt.copyObject(any(CopyObjectRequest.class))) .thenReturn(CompletableFuture.completedFuture(response)); CompletedCopy completedCopy = tm.copy(u -> u.copyObjectRequest(p -> p.sourceBucket("bucket") .sourceKey("sourceKey") .destinationBucket("bucket") .destinationKey("destKey"))) .completionFuture() .join(); assertThat(completedCopy.response()).isEqualTo(response); } @Test void uploadFile_cancel_shouldForwardCancellation() { CompletableFuture<PutObjectResponse> s3CrtFuture = new CompletableFuture<>(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenReturn(s3CrtFuture); CompletableFuture<CompletedFileUpload> future = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket("bucket") .key("key")) .source(Paths.get("."))) .completionFuture(); future.cancel(true); assertThat(s3CrtFuture).isCancelled(); } @Test void upload_cancel_shouldForwardCancellation() { CompletableFuture<PutObjectResponse> s3CrtFuture = new CompletableFuture<>(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenReturn(s3CrtFuture); CompletableFuture<CompletedUpload> future = tm.upload(u -> u.putObjectRequest(p -> p.bucket("bucket") .key("key")) .requestBody(AsyncRequestBody.fromString("foo"))) .completionFuture(); future.cancel(true); assertThat(s3CrtFuture).isCancelled(); } @Test void copy_cancel_shouldForwardCancellation() { CompletableFuture<CopyObjectResponse> s3CrtFuture = new CompletableFuture<>(); when(mockS3Crt.copyObject(any(CopyObjectRequest.class))) .thenReturn(s3CrtFuture); CompletableFuture<CompletedCopy> future = tm.copy(u -> u.copyObjectRequest(p -> p.sourceBucket("bucket") .sourceKey("sourceKey") .destinationBucket("bucket") .destinationKey("destKey"))) .completionFuture(); future.cancel(true); assertThat(s3CrtFuture).isCancelled(); } @Test void downloadFile_returnsResponse() { GetObjectResponse response = GetObjectResponse.builder().build(); when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))) .thenReturn(CompletableFuture.completedFuture(response)); CompletedFileDownload completedFileDownload = tm.downloadFile(d -> d.getObjectRequest(g -> g.bucket("bucket") .key("key")) .destination(Paths.get("."))) .completionFuture() .join(); assertThat(completedFileDownload.response()).isEqualTo(response); } @Test void downloadFile_cancel_shouldForwardCancellation() { CompletableFuture<GetObjectResponse> s3CrtFuture = new CompletableFuture<>(); when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))) .thenReturn(s3CrtFuture); CompletableFuture<CompletedFileDownload> future = tm.downloadFile(d -> d .getObjectRequest(g -> g.bucket( "bucket") .key("key")) .destination(Paths.get("."))) .completionFuture(); future.cancel(true); assertThat(s3CrtFuture).isCancelled(); } @Test void download_cancel_shouldForwardCancellation() { CompletableFuture<GetObjectResponse> s3CrtFuture = new CompletableFuture<>(); when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))) .thenReturn(s3CrtFuture); DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest = DownloadRequest.builder() .getObjectRequest(g -> g.bucket("bucket").key("key")) .responseTransformer(AsyncResponseTransformer.toBytes()).build(); CompletableFuture<CompletedDownload<ResponseBytes<GetObjectResponse>>> future = tm.download(downloadRequest).completionFuture(); future.cancel(true); assertThat(s3CrtFuture).isCancelled(); } @Test void objectLambdaArnBucketProvided_shouldThrowException() { String objectLambdaArn = "arn:xxx:s3-object-lambda"; assertThatThrownBy(() -> tm.uploadFile(b -> b.putObjectRequest(p -> p.bucket(objectLambdaArn).key("key")) .source(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.upload(b -> b.putObjectRequest(p -> p.bucket(objectLambdaArn).key("key")) .requestBody(AsyncRequestBody.fromString("foo"))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.downloadFile(b -> b.getObjectRequest(p -> p.bucket(objectLambdaArn).key("key")) .destination(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest = DownloadRequest.builder() .getObjectRequest(g -> g.bucket(objectLambdaArn).key("key")) .responseTransformer(AsyncResponseTransformer.toBytes()) .build(); assertThatThrownBy(() -> tm.download(downloadRequest) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.uploadDirectory(b -> b.bucket(objectLambdaArn) .source(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket(objectLambdaArn) .sourceKey("sourceKey") .destinationBucket("bucket") .destinationKey("destKey"))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket("bucket") .sourceKey("sourceKey") .destinationBucket(objectLambdaArn) .destinationKey("destKey"))) .completionFuture().join()) .hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class); } @Test void mrapArnProvided_shouldThrowException() { String mrapArn = "arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap"; assertThatThrownBy(() -> tm.uploadFile(b -> b.putObjectRequest(p -> p.bucket(mrapArn).key("key")) .source(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.upload(b -> b.putObjectRequest(p -> p.bucket(mrapArn).key("key")) .requestBody(AsyncRequestBody.fromString("foo"))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.downloadFile(b -> b.getObjectRequest(p -> p.bucket(mrapArn).key("key")) .destination(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest = DownloadRequest.builder() .getObjectRequest(g -> g.bucket(mrapArn).key("key")) .responseTransformer(AsyncResponseTransformer.toBytes()).build(); assertThatThrownBy(() -> tm.download(downloadRequest).completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.uploadDirectory(b -> b.bucket(mrapArn) .source(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.downloadDirectory(b -> b.bucket(mrapArn) .destination(Paths.get("."))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket(mrapArn) .sourceKey("sourceKey") .destinationBucket("bucket") .destinationKey("destKey"))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket("bucket") .sourceKey("sourceKey") .destinationBucket(mrapArn) .destinationKey("destKey"))) .completionFuture().join()) .hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class); } @Test void uploadDirectory_throwException_shouldCompleteFutureExceptionally() { RuntimeException exception = new RuntimeException("test"); when(uploadDirectoryHelper.uploadDirectory(any(UploadDirectoryRequest.class))).thenThrow(exception); assertThatThrownBy(() -> tm.uploadDirectory(u -> u.source(Paths.get("/")) .bucket("bucketName")).completionFuture().join()) .hasCause(exception); } @Test void downloadDirectory_throwException_shouldCompleteFutureExceptionally() { RuntimeException exception = new RuntimeException("test"); when(downloadDirectoryHelper.downloadDirectory(any(DownloadDirectoryRequest.class))).thenThrow(exception); assertThatThrownBy(() -> tm.downloadDirectory(u -> u.destination(Paths.get("/")) .bucket("bucketName")).completionFuture().join()) .hasCause(exception); } @Test void close_shouldCloseUnderlyingResources() { S3TransferManager transferManager = new GenericS3TransferManager(mockS3Crt, uploadDirectoryHelper, configuration, downloadDirectoryHelper); transferManager.close(); verify(mockS3Crt, times(0)).close(); verify(configuration).close(); } @Test void close_shouldNotCloseCloseS3AsyncClientPassedInBuilder_when_transferManagerClosed() { S3TransferManager transferManager = S3TransferManager.builder().s3Client(mockS3Crt).build(); transferManager.close(); verify(mockS3Crt, times(0)).close(); } @Test void uploadDirectory_requestNull_shouldThrowException() { UploadDirectoryRequest request = null; assertThatThrownBy(() -> tm.uploadDirectory(request).completionFuture().join()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test void upload_requestNull_shouldThrowException() { UploadFileRequest request = null; assertThatThrownBy(() -> tm.uploadFile(request).completionFuture().join()).isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test void download_requestNull_shouldThrowException() { DownloadFileRequest request = null; assertThatThrownBy(() -> tm.downloadFile(request).completionFuture().join()).isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test void copy_requestNull_shouldThrowException() { CopyRequest request = null; assertThatThrownBy(() -> tm.copy(request).completionFuture().join()).isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test void downloadDirectory_requestNull_shouldThrowException() { DownloadDirectoryRequest request = null; assertThatThrownBy(() -> tm.downloadDirectory(request).completionFuture().join()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } }
3,977
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/CrtFileUploadTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import com.google.common.jimfs.Jimfs; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.time.Instant; import java.util.UUID; import java.util.concurrent.CompletableFuture; import nl.jqno.equalsverifier.EqualsVerifier; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.s3.ResumeToken; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.transfer.s3.internal.model.CrtFileUpload; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.progress.TransferProgress; class CrtFileUploadTest { private static final int TOTAL_PARTS = 10; private static final int NUM_OF_PARTS_COMPLETED = 5; private static final long PART_SIZE_IN_BYTES = 8 * MB; private static final String MULTIPART_UPLOAD_ID = "someId"; private S3MetaRequest metaRequest; private static FileSystem fileSystem; private static File file; private static ResumeToken token; @BeforeAll public static void setUp() throws IOException { fileSystem = Jimfs.newFileSystem(); file = File.createTempFile("test", UUID.randomUUID().toString()); Files.write(file.toPath(), RandomStringUtils.random(2000).getBytes(StandardCharsets.UTF_8)); token = new ResumeToken(new ResumeToken.PutResumeTokenBuilder() .withNumPartsCompleted(NUM_OF_PARTS_COMPLETED) .withTotalNumParts(TOTAL_PARTS) .withPartSize(PART_SIZE_IN_BYTES) .withUploadId(MULTIPART_UPLOAD_ID)); } @AfterAll public static void tearDown() throws IOException { file.delete(); } @BeforeEach void setUpBeforeEachTest() { metaRequest = Mockito.mock(S3MetaRequest.class); } @Test void equals_hashcode() { EqualsVerifier.forClass(CrtFileUpload.class) .withNonnullFields("completionFuture", "progress", "request", "observable", "resumableFileUpload") .withPrefabValues(S3MetaRequestPauseObservable.class, new S3MetaRequestPauseObservable(), new S3MetaRequestPauseObservable()) .verify(); } @Test void pause_futureCompleted_shouldReturnNormally() { PutObjectResponse putObjectResponse = PutObjectResponse.builder() .build(); CompletableFuture<CompletedFileUpload> future = CompletableFuture.completedFuture(CompletedFileUpload.builder() .response(putObjectResponse) .build()); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .sdkResponse(putObjectResponse) .transferredBytes(0L) .build()); S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable(); UploadFileRequest request = uploadFileRequest(); CrtFileUpload fileUpload = new CrtFileUpload(future, transferProgress, observable, request); observable.subscribe(metaRequest); ResumableFileUpload resumableFileUpload = fileUpload.pause(); Mockito.verify(metaRequest, Mockito.never()).pause(); assertThat(resumableFileUpload.totalParts()).isEmpty(); assertThat(resumableFileUpload.partSizeInBytes()).isEmpty(); assertThat(resumableFileUpload.multipartUploadId()).isEmpty(); assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length()); assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request); assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified())); } @Test void pauseTwice_shouldReturnTheSame() { CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(1000L) .build()); UploadFileRequest request = uploadFileRequest(); S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable(); when(metaRequest.pause()).thenReturn(token); observable.subscribe(metaRequest); CrtFileUpload fileUpload = new CrtFileUpload(future, transferProgress, observable, request); ResumableFileUpload resumableFileUpload = fileUpload.pause(); ResumableFileUpload resumableFileUpload2 = fileUpload.pause(); assertThat(resumableFileUpload).isEqualTo(resumableFileUpload2); } @Test void pause_crtThrowException_shouldPropogate() { CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(1000L) .build()); UploadFileRequest request = uploadFileRequest(); S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable(); CrtRuntimeException exception = new CrtRuntimeException("exception"); when(metaRequest.pause()).thenThrow(exception); observable.subscribe(metaRequest); CrtFileUpload fileUpload = new CrtFileUpload(future, transferProgress, observable, request); assertThatThrownBy(() -> fileUpload.pause()).isSameAs(exception); } @Test void pause_futureNotComplete_shouldPause() { CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()); S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable(); when(metaRequest.pause()).thenReturn(token); UploadFileRequest request = uploadFileRequest(); CrtFileUpload fileUpload = new CrtFileUpload(future, transferProgress, observable, request); observable.subscribe(metaRequest); ResumableFileUpload resumableFileUpload = fileUpload.pause(); Mockito.verify(metaRequest).pause(); assertThat(resumableFileUpload.totalParts()).hasValue(TOTAL_PARTS); assertThat(resumableFileUpload.partSizeInBytes()).hasValue(PART_SIZE_IN_BYTES); assertThat(resumableFileUpload.multipartUploadId()).hasValue(MULTIPART_UPLOAD_ID); assertThat(resumableFileUpload.transferredParts()).hasValue(NUM_OF_PARTS_COMPLETED); assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length()); assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request); assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified())); } @Test void pause_singlePart_shouldPause() { PutObjectResponse putObjectResponse = PutObjectResponse.builder() .build(); CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>(); TransferProgress transferProgress = Mockito.mock(TransferProgress.class); when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder() .sdkResponse(putObjectResponse) .transferredBytes(0L) .build()); S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable(); when(metaRequest.pause()).thenThrow(new CrtRuntimeException(6)); UploadFileRequest request = uploadFileRequest(); CrtFileUpload fileUpload = new CrtFileUpload(future, transferProgress, observable, request); observable.subscribe(metaRequest); ResumableFileUpload resumableFileUpload = fileUpload.pause(); Mockito.verify(metaRequest).pause(); assertThat(resumableFileUpload.totalParts()).isEmpty(); assertThat(resumableFileUpload.partSizeInBytes()).isEmpty(); assertThat(resumableFileUpload.multipartUploadId()).isEmpty(); assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length()); assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request); assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified())); } private UploadFileRequest uploadFileRequest() { return UploadFileRequest.builder() .source(file) .putObjectRequest(p -> p.key("test").bucket("bucket")) .build(); } }
3,978
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/ListObjectsHelperTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.services.s3.model.CommonPrefix; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.S3Object; class ListObjectsHelperTest { private Function<ListObjectsV2Request, CompletableFuture<ListObjectsV2Response>> listObjectsFunction; private ListObjectsHelper listObjectsHelper; @BeforeEach public void setup() { listObjectsFunction = Mockito.mock(Function.class); listObjectsHelper = new ListObjectsHelper(listObjectsFunction); } @Test void listS3Objects_noNextPageOrCommonPrefixes_shouldNotFetchAgain() { ListObjectsV2Response response = listObjectsV2Response("key1", "key2"); CompletableFuture<ListObjectsV2Response> future = CompletableFuture.completedFuture(response); when(listObjectsFunction.apply(any(ListObjectsV2Request.class))) .thenReturn(future); List<S3Object> actualObjects = new ArrayList<>(); listObjectsHelper.listS3ObjectsRecursively(ListObjectsV2Request.builder() .bucket("bucket") .build()) .subscribe(actualObjects::add).join(); future.complete(response); assertThat(actualObjects).hasSameElementsAs(response.contents()); verify(listObjectsFunction, times(1)).apply(any(ListObjectsV2Request.class)); } /** * source * / / | | \ \ * 1 2 3 4 jan feb * / / | \ / \ * 1 2 3 4 1 2 * The order of S3Objects should be "1, 2, 3, 4, jan/1, jan/2, jan/3, jan/4, feb/1, feb/2" */ @Test void listS3Objects_hasNextPageAndCommonPrefixes_shouldReturnAll() { List<CommonPrefix> commonPrefixes = Arrays.asList(CommonPrefix.builder().prefix("jan/").build(), CommonPrefix.builder().prefix("feb/").build()); ListObjectsV2Response responsePage1 = listObjectsV2Response("nextPage", commonPrefixes, "1", "2"); ListObjectsV2Response responsePage2 = listObjectsV2Response(null, Collections.emptyList(), "3", "4"); ListObjectsV2Response responsePage3 = listObjectsV2Response("nextPage", Collections.emptyList(), "jan/1", "jan/2"); ListObjectsV2Response responsePage4 = listObjectsV2Response(null, Collections.emptyList(), "jan/3", "jan/4"); ListObjectsV2Response responsePage5 = listObjectsV2Response(null, Collections.emptyList(), "feb/1", "feb/2"); CompletableFuture<ListObjectsV2Response> futurePage1 = CompletableFuture.completedFuture(responsePage1); CompletableFuture<ListObjectsV2Response> futurePage2 = CompletableFuture.completedFuture(responsePage2); CompletableFuture<ListObjectsV2Response> futurePage3 = CompletableFuture.completedFuture(responsePage3); CompletableFuture<ListObjectsV2Response> futurePage4 = CompletableFuture.completedFuture(responsePage4); CompletableFuture<ListObjectsV2Response> futurePage5 = CompletableFuture.completedFuture(responsePage5); when(listObjectsFunction.apply(any(ListObjectsV2Request.class))).thenReturn(futurePage1) .thenReturn(futurePage2) .thenReturn(futurePage3) .thenReturn(futurePage4) .thenReturn(futurePage5); List<S3Object> actualObjects = new ArrayList<>(); ListObjectsV2Request firstRequest = ListObjectsV2Request.builder() .bucket("bucket") .build(); listObjectsHelper.listS3ObjectsRecursively(firstRequest) .subscribe(actualObjects::add).join(); futurePage1.complete(responsePage1); ArgumentCaptor<ListObjectsV2Request> argumentCaptor = ArgumentCaptor.forClass(ListObjectsV2Request.class); verify(listObjectsFunction, times(5)).apply(argumentCaptor.capture()); List<ListObjectsV2Request> actualListObjectsV2Request = argumentCaptor.getAllValues(); assertThat(actualListObjectsV2Request).hasSize(5) .satisfies(list -> { assertThat(list.get(0)).isEqualTo(firstRequest); assertThat(list.get(1)).isEqualTo(firstRequest.toBuilder().continuationToken( "nextPage").build()); assertThat(list.get(2)).isEqualTo(firstRequest.toBuilder().prefix("jan/").build()); assertThat(list.get(3)).isEqualTo(firstRequest.toBuilder().prefix("jan/") .continuationToken("nextPage").build()); assertThat(list.get(4)).isEqualTo(firstRequest.toBuilder().prefix("feb/").build()); }); assertThat(actualObjects).hasSize(10); } private ListObjectsV2Response listObjectsV2Response(String... keys) { return listObjectsV2Response(null, null, keys); } private ListObjectsV2Response listObjectsV2Response(String continuationToken, List<CommonPrefix> commonPrefixes, String... keys) { List<S3Object> s3Objects = Arrays.stream(keys).map(k -> S3Object.builder().key(k).build()).collect(Collectors.toList()); return ListObjectsV2Response.builder() .nextContinuationToken(continuationToken) .commonPrefixes(commonPrefixes) .contents(s3Objects) .build(); } }
3,979
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/UploadDirectoryHelperTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.testutils.FileUtils; import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration; import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileUpload; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgress; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.DirectoryUpload; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; import software.amazon.awssdk.transfer.s3.progress.TransferListener; public class UploadDirectoryHelperTest { private FileSystem jimfs; private Path directory; /** * Local directory is needed to test symlinks because jimfs doesn't work well with symlinks */ private static Path localDirectory; private Function<UploadFileRequest, FileUpload> singleUploadFunction; private UploadDirectoryHelper uploadDirectoryHelper; public static Collection<FileSystem> fileSystems() { return Arrays.asList(Jimfs.newFileSystem(Configuration.unix()), Jimfs.newFileSystem(Configuration.osX()), Jimfs.newFileSystem(Configuration.windows())); } @BeforeAll public static void setUp() throws IOException { localDirectory = createLocalTestDirectory(); } @AfterAll public static void tearDown() throws IOException { FileUtils.cleanUpTestDirectory(localDirectory); } @BeforeEach public void methodSetup() throws IOException { jimfs = Jimfs.newFileSystem(); directory = jimfs.getPath("test"); Files.createDirectory(directory); Files.createFile(jimfs.getPath("test/1")); Files.createFile(jimfs.getPath("test/2")); singleUploadFunction = mock(Function.class); uploadDirectoryHelper = new UploadDirectoryHelper(TransferManagerConfiguration.builder().build(), singleUploadFunction); } @AfterEach public void methodCleanup() throws IOException { jimfs.close(); } @Test void uploadDirectory_cancel_shouldCancelAllFutures() { CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>(); FileUpload fileUpload = newUpload(future); CompletableFuture<CompletedFileUpload> future2 = new CompletableFuture<>(); FileUpload fileUpload2 = newUpload(future2); when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .build()); uploadDirectory.completionFuture().cancel(true); assertThatThrownBy(() -> future.get(1, TimeUnit.SECONDS)) .isInstanceOf(CancellationException.class); assertThatThrownBy(() -> future2.get(1, TimeUnit.SECONDS)) .isInstanceOf(CancellationException.class); } @Test void uploadDirectory_allUploadsSucceed_failedUploadsShouldBeEmpty() throws Exception { PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build(); CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build(); CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>(); FileUpload fileUpload = newUpload(successfulFuture); successfulFuture.complete(completedFileUpload); PutObjectResponse putObjectResponse2 = PutObjectResponse.builder().eTag("5678").build(); CompletedFileUpload completedFileUpload2 = CompletedFileUpload.builder().response(putObjectResponse2).build(); CompletableFuture<CompletedFileUpload> successfulFuture2 = new CompletableFuture<>(); FileUpload fileUpload2 = newUpload(successfulFuture2); successfulFuture2.complete(completedFileUpload2); when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .build()); CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().get(5, TimeUnit.SECONDS); assertThat(completedDirectoryUpload.failedTransfers()).isEmpty(); } @Test void uploadDirectory_partialSuccess_shouldProvideFailedUploads() throws Exception { PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build(); CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build(); CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>(); FileUpload fileUpload = newUpload(successfulFuture); successfulFuture.complete(completedFileUpload); SdkClientException exception = SdkClientException.create("failed"); CompletableFuture<CompletedFileUpload> failedFuture = new CompletableFuture<>(); FileUpload fileUpload2 = newUpload(failedFuture); failedFuture.completeExceptionally(exception); when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .build()); CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().get(5, TimeUnit.SECONDS); assertThat(completedDirectoryUpload.failedTransfers()).hasSize(1); assertThat(completedDirectoryUpload.failedTransfers().iterator().next().exception()).isEqualTo(exception); assertThat(completedDirectoryUpload.failedTransfers().iterator().next().request().source().toString()) .isEqualTo("test" + directory.getFileSystem().getSeparator() + "2"); } @Test void uploadDirectory_withRequestTransformer_usesRequestTransformer() throws Exception { PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build(); CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build(); CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>(); FileUpload upload = newUpload(successfulFuture); successfulFuture.complete(completedFileUpload); PutObjectResponse putObjectResponse2 = PutObjectResponse.builder().eTag("5678").build(); CompletedFileUpload completedFileUpload2 = CompletedFileUpload.builder().response(putObjectResponse2).build(); CompletableFuture<CompletedFileUpload> successfulFuture2 = new CompletableFuture<>(); FileUpload upload2 = newUpload(successfulFuture2); successfulFuture2.complete(completedFileUpload2); ArgumentCaptor<UploadFileRequest> uploadRequestCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(uploadRequestCaptor.capture())).thenReturn(upload, upload2); Path newSource = Paths.get("/new/path"); PutObjectRequest newPutObjectRequest = PutObjectRequest.builder().build(); TransferRequestOverrideConfiguration newOverrideConfig = TransferRequestOverrideConfiguration.builder() .build(); List<TransferListener> listeners = Arrays.asList(LoggingTransferListener.create()); Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer = r -> r.source(newSource) .putObjectRequest(newPutObjectRequest) .transferListeners(listeners); uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .uploadFileRequestTransformer(uploadFileRequestTransformer) .build()) .completionFuture() .get(5, TimeUnit.SECONDS); List<UploadFileRequest> uploadRequests = uploadRequestCaptor.getAllValues(); assertThat(uploadRequests).hasSize(2); assertThat(uploadRequests).element(0).satisfies(r -> { assertThat(r.source()).isEqualTo(newSource); assertThat(r.putObjectRequest()).isEqualTo(newPutObjectRequest); assertThat(r.transferListeners()).isEqualTo(listeners); }); assertThat(uploadRequests).element(1).satisfies(r -> { assertThat(r.source()).isEqualTo(newSource); assertThat(r.putObjectRequest()).isEqualTo(newPutObjectRequest); assertThat(r.transferListeners()).isEqualTo(listeners); }); } @ParameterizedTest @MethodSource("fileSystems") void uploadDirectory_defaultSetting_shouldRecursivelyUpload(FileSystem fileSystem) { directory = createJimFsTestDirectory(fileSystem); ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())) .thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .followSymbolicLinks(false) .build()); uploadDirectory.completionFuture().join(); List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket")); assertThat(actualRequests.size()).isEqualTo(3); List<String> keys = actualRequests.stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys).containsOnly("bar.txt", "foo/1.txt", "foo/2.txt"); } @Test void uploadDirectory_depth1FollowSymlinkTrue_shouldOnlyUploadTopLevel() { ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(localDirectory) .bucket("bucket") .maxDepth(1) .followSymbolicLinks(true) .build()); uploadDirectory.completionFuture().join(); List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); List<String> keys = actualRequests.stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys.size()).isEqualTo(2); assertThat(keys).containsOnly("bar.txt", "symlink2"); } @Test void uploadDirectory_FollowSymlinkTrue_shouldIncludeLinkedFiles() { ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(localDirectory) .bucket("bucket") .followSymbolicLinks(true) .build()); uploadDirectory.completionFuture().join(); List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket")); List<String> keys = actualRequests.stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys.size()).isEqualTo(5); assertThat(keys).containsOnly("bar.txt", "foo/1.txt", "foo/2.txt", "symlink/2.txt", "symlink2"); } @ParameterizedTest @MethodSource("fileSystems") void uploadDirectory_withPrefix_keysShouldHavePrefix(FileSystem fileSystem) { directory = createJimFsTestDirectory(fileSystem); ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .s3Prefix("yolo") .build()); uploadDirectory.completionFuture().join(); List<String> keys = requestArgumentCaptor.getAllValues().stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys.size()).isEqualTo(3); keys.forEach(r -> assertThat(r).startsWith("yolo/")); } @ParameterizedTest @MethodSource("fileSystems") void uploadDirectory_withDelimiter_shouldHonor(FileSystem fileSystem) { directory = createJimFsTestDirectory(fileSystem); ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .s3Delimiter(",") .s3Prefix("yolo") .build()); uploadDirectory.completionFuture().join(); List<String> keys = requestArgumentCaptor.getAllValues().stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys.size()).isEqualTo(3); assertThat(keys).containsOnly("yolo,foo,2.txt", "yolo,foo,1.txt", "yolo,bar.txt"); } @ParameterizedTest @MethodSource("fileSystems") void uploadDirectory_maxLengthOne_shouldOnlyUploadTopLevel(FileSystem fileSystem) { directory = createJimFsTestDirectory(fileSystem); ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())) .thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(directory) .bucket("bucket") .maxDepth(1) .build()); uploadDirectory.completionFuture().join(); List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket")); assertThat(actualRequests.size()).isEqualTo(1); List<String> keys = actualRequests.stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys).containsOnly("bar.txt"); } @ParameterizedTest @MethodSource("fileSystems") void uploadDirectory_directoryNotExist_shouldCompleteFutureExceptionally(FileSystem fileSystem) { directory = createJimFsTestDirectory(fileSystem); assertThatThrownBy(() -> uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder().source(Paths.get( "randomstringneverexistas234ersaf1231")) .bucket("bucketName").build()).completionFuture().join()) .hasMessageContaining("does not exist").hasCauseInstanceOf(IllegalArgumentException.class); } @Test void uploadDirectory_notDirectory_shouldCompleteFutureExceptionally() { assertThatThrownBy(() -> uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .source(Paths.get(localDirectory.toString(), "symlink")) .bucket("bucketName").build()).completionFuture().join()) .hasMessageContaining("is not a directory").hasCauseInstanceOf(IllegalArgumentException.class); } @Test void uploadDirectory_notDirectoryFollowSymlinkTrue_shouldCompleteSuccessfully() { ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class); when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload()); DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder() .followSymbolicLinks(true) .source(Paths.get(localDirectory.toString(), "symlink")) .bucket("bucket").build()); uploadDirectory.completionFuture().join(); List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket")); assertThat(actualRequests.size()).isEqualTo(1); List<String> keys = actualRequests.stream().map(u -> u.putObjectRequest().key()) .collect(Collectors.toList()); assertThat(keys).containsOnly("2.txt"); } private DefaultFileUpload completedUpload() { return new DefaultFileUpload(CompletableFuture.completedFuture(CompletedFileUpload.builder() .response(PutObjectResponse.builder().build()) .build()), new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()), UploadFileRequest.builder() .source(Paths.get(".")).putObjectRequest(b -> b.bucket("bucket").key("key")) .build()); } private FileUpload newUpload(CompletableFuture<CompletedFileUpload> future) { return new DefaultFileUpload(future, new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()), UploadFileRequest.builder() .putObjectRequest(p -> p.key("key").bucket("bucket")).source(Paths.get( "test.txt")) .build()); } private Path createJimFsTestDirectory(FileSystem fileSystem) { try { return createJmfsTestDirectory(fileSystem); } catch (IOException exception) { throw new UncheckedIOException(exception); } } private static Path createLocalTestDirectory() { try { return createLocalTestDirectoryWithSymLink(); } catch (IOException exception) { throw new UncheckedIOException(exception); } } /** * Create a test directory with the following structure - test1 - foo - 1.txt - 2.txt - bar.txt - symlink -> test2 - symlink2 * -> test3/4.txt - test2 - 2.txt - test3 - 4.txt */ private static Path createLocalTestDirectoryWithSymLink() throws IOException { Path directory = Files.createTempDirectory("test1"); Path anotherDirectory = Files.createTempDirectory("test2"); Path thirdDirectory = Files.createTempDirectory("test3"); String directoryName = directory.toString(); String anotherDirectoryName = anotherDirectory.toString(); Files.createDirectory(Paths.get(directory + "/foo")); Files.write(Paths.get(directoryName, "bar.txt"), "bar".getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(directoryName, "foo/1.txt"), "1".getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(directoryName, "foo/2.txt"), "2".getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(anotherDirectoryName, "2.txt"), "2".getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(thirdDirectory.toString(), "3.txt"), "3".getBytes(StandardCharsets.UTF_8)); Files.createSymbolicLink(Paths.get(directoryName, "symlink"), anotherDirectory); Files.createSymbolicLink(Paths.get(directoryName, "symlink2"), Paths.get(thirdDirectory.toString(), "3.txt")); return directory; } /** * Create a test directory with the following structure - test1 - foo - 1.txt - 2.txt - bar.txt */ private Path createJmfsTestDirectory(FileSystem jimfs) throws IOException { String directoryName = "test"; Path directory = jimfs.getPath(directoryName); Files.createDirectory(directory); Files.createDirectory(jimfs.getPath(directoryName + "/foo")); Files.write(jimfs.getPath(directoryName, "bar.txt"), "bar".getBytes(StandardCharsets.UTF_8)); Files.write(jimfs.getPath(directoryName, "foo", "1.txt"), "1".getBytes(StandardCharsets.UTF_8)); Files.write(jimfs.getPath(directoryName, "foo", "2.txt"), "2".getBytes(StandardCharsets.UTF_8)); return directory; } }
3,980
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDirectoryUploadTest.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.transfer.s3.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryUpload; class DefaultDirectoryUploadTest { @Test void equals_hashcode() { EqualsVerifier.forClass(DefaultDirectoryUpload.class) .withNonnullFields("completionFuture") .verify(); } }
3,981
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultCopyTest.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.transfer.s3.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.model.DefaultCopy; class DefaultCopyTest { @Test void equals_hashcode() { EqualsVerifier.forClass(DefaultCopy.class) .withNonnullFields("completionFuture", "progress") .verify(); } }
3,982
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerUploadPauseAndResumeTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SDK_HTTP_EXECUTION_ATTRIBUTES; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.CRT_PAUSE_RESUME_TOKEN; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpExecutionAttributes; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; class S3TransferManagerUploadPauseAndResumeTest { private S3CrtAsyncClient mockS3Crt; private S3TransferManager tm; private UploadDirectoryHelper uploadDirectoryHelper; private DownloadDirectoryHelper downloadDirectoryHelper; private TransferManagerConfiguration configuration; private File file; @BeforeEach public void methodSetup() throws IOException { file = RandomTempFile.createTempFile("test", UUID.randomUUID().toString()); Files.write(file.toPath(), RandomStringUtils.randomAlphanumeric(1000).getBytes(StandardCharsets.UTF_8)); mockS3Crt = mock(S3CrtAsyncClient.class); uploadDirectoryHelper = mock(UploadDirectoryHelper.class); configuration = mock(TransferManagerConfiguration.class); downloadDirectoryHelper = mock(DownloadDirectoryHelper.class); tm = new CrtS3TransferManager(configuration, mockS3Crt, false); } @AfterEach public void methodTeardown() { file.delete(); tm.close(); } @Test void resumeUploadFile_noResumeToken_shouldUploadFromBeginning() { PutObjectRequest putObjectRequest = putObjectRequest(); PutObjectResponse response = PutObjectResponse.builder().build(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); long fileLength = file.length(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(putObjectRequest) .source(file) .build(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class))) .thenReturn(CompletableFuture.completedFuture(response)); CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength) .uploadFileRequest(uploadFileRequest) .fileLastModified(fileLastModified)) .completionFuture() .join(); assertThat(completedFileUpload.response()).isEqualTo(response); verifyActualPutObjectRequestNotResumed(); } @Test void resumeUploadFile_fileModified_shouldAbortExistingAndUploadFromBeginning() { PutObjectRequest putObjectRequest = putObjectRequest(); PutObjectResponse response = PutObjectResponse.builder().build(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); long fileLength = file.length(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(putObjectRequest) .source(file) .build(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class))) .thenReturn(CompletableFuture.completedFuture(response)); when(mockS3Crt.abortMultipartUpload(any(AbortMultipartUploadRequest.class))) .thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build())); String multipartId = "someId"; CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength + 10L) .partSizeInBytes(8 * MB) .totalParts(10L) .multipartUploadId(multipartId) .uploadFileRequest(uploadFileRequest) .fileLastModified(fileLastModified)) .completionFuture() .join(); assertThat(completedFileUpload.response()).isEqualTo(response); verifyActualPutObjectRequestNotResumed(); ArgumentCaptor<AbortMultipartUploadRequest> abortMultipartUploadRequestArgumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class); verify(mockS3Crt).abortMultipartUpload(abortMultipartUploadRequestArgumentCaptor.capture()); AbortMultipartUploadRequest actualRequest = abortMultipartUploadRequestArgumentCaptor.getValue(); assertThat(actualRequest.uploadId()).isEqualTo(multipartId); } @Test void resumeUploadFile_hasValidResumeToken_shouldResumeUpload() { PutObjectRequest putObjectRequest = putObjectRequest(); PutObjectResponse response = PutObjectResponse.builder().build(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); long fileLength = file.length(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(putObjectRequest) .source(file) .build(); when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class))) .thenReturn(CompletableFuture.completedFuture(response)); String multipartId = "someId"; long totalParts = 10L; long partSizeInBytes = 8 * MB; CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength) .partSizeInBytes(partSizeInBytes) .totalParts(totalParts) .multipartUploadId(multipartId) .uploadFileRequest(uploadFileRequest) .fileLastModified(fileLastModified)) .completionFuture() .join(); assertThat(completedFileUpload.response()).isEqualTo(response); ArgumentCaptor<PutObjectRequest> putObjectRequestArgumentCaptor = ArgumentCaptor.forClass(PutObjectRequest.class); verify(mockS3Crt).putObject(putObjectRequestArgumentCaptor.capture(), any(Path.class)); PutObjectRequest actualRequest = putObjectRequestArgumentCaptor.getValue(); AwsRequestOverrideConfiguration awsRequestOverrideConfiguration = actualRequest.overrideConfiguration().get(); SdkHttpExecutionAttributes attribute = awsRequestOverrideConfiguration.executionAttributes().getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES); assertThat(attribute.getAttribute(CRT_PAUSE_RESUME_TOKEN)).satisfies(token -> { assertThat(token.getUploadId()).isEqualTo(multipartId); assertThat(token.getPartSize()).isEqualTo(partSizeInBytes); assertThat(token.getTotalNumParts()).isEqualTo(totalParts); }); } private void verifyActualPutObjectRequestNotResumed() { ArgumentCaptor<PutObjectRequest> putObjectRequestArgumentCaptor = ArgumentCaptor.forClass(PutObjectRequest.class); verify(mockS3Crt).putObject(putObjectRequestArgumentCaptor.capture(), any(Path.class)); PutObjectRequest actualRequest = putObjectRequestArgumentCaptor.getValue(); AwsRequestOverrideConfiguration awsRequestOverrideConfiguration = actualRequest.overrideConfiguration().get(); SdkHttpExecutionAttributes attribute = awsRequestOverrideConfiguration.executionAttributes().getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES); assertThat(attribute.getAttribute(CRT_PAUSE_RESUME_TOKEN)).isNull(); } private static PutObjectRequest putObjectRequest() { return PutObjectRequest.builder() .key("key") .bucket("bucket") .build(); } }
3,983
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultUploadTest.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.transfer.s3.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.model.DefaultUpload; public class DefaultUploadTest { @Test public void equals_hashcode() { EqualsVerifier.forClass(DefaultUpload.class) .withNonnullFields("completionFuture", "progress") .verify(); } }
3,984
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferManagerConfigurationTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.EXECUTOR; import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS; import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_MAX_DEPTH; import java.nio.file.Paths; import java.util.concurrent.ExecutorService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest; public class TransferManagerConfigurationTest { private TransferManagerConfiguration transferManagerConfiguration; @Test public void resolveMaxDepth_requestOverride_requestOverrideShouldTakePrecedence() { transferManagerConfiguration = TransferManagerConfiguration.builder() .uploadDirectoryMaxDepth(1) .build(); UploadDirectoryRequest uploadDirectoryRequest = UploadDirectoryRequest.builder() .bucket("bucket") .source(Paths.get(".")) .maxDepth(2) .build(); assertThat(transferManagerConfiguration.resolveUploadDirectoryMaxDepth(uploadDirectoryRequest)).isEqualTo(2); } @Test public void resolveFollowSymlinks_requestOverride_requestOverrideShouldTakePrecedence() { transferManagerConfiguration = TransferManagerConfiguration.builder() .uploadDirectoryFollowSymbolicLinks(false) .build(); UploadDirectoryRequest uploadDirectoryRequest = UploadDirectoryRequest.builder() .bucket("bucket") .source(Paths.get(".")) .followSymbolicLinks(true) .build(); assertThat(transferManagerConfiguration.resolveUploadDirectoryFollowSymbolicLinks(uploadDirectoryRequest)).isTrue(); } @Test public void noOverride_shouldUseDefaults() { transferManagerConfiguration = TransferManagerConfiguration.builder().build(); assertThat(transferManagerConfiguration.option(UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS)).isFalse(); assertThat(transferManagerConfiguration.option(UPLOAD_DIRECTORY_MAX_DEPTH)).isEqualTo(Integer.MAX_VALUE); assertThat(transferManagerConfiguration.option(EXECUTOR)).isNotNull(); } @Test public void close_noCustomExecutor_shouldCloseDefaultOne() { transferManagerConfiguration = TransferManagerConfiguration.builder().build(); transferManagerConfiguration.close(); ExecutorService executor = (ExecutorService) transferManagerConfiguration.option(EXECUTOR); assertThat(executor.isShutdown()).isTrue(); } @Test public void close_customExecutor_shouldNotCloseCustomExecutor() { ExecutorService executorService = Mockito.mock(ExecutorService.class); transferManagerConfiguration = TransferManagerConfiguration.builder().executor(executorService).build(); transferManagerConfiguration.close(); verify(executorService, never()).shutdown(); } }
3,985
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDirectoryDownloadTest.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.transfer.s3.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryDownload; class DefaultDirectoryDownloadTest { @Test void equals_hashcode() { EqualsVerifier.forClass(DefaultDirectoryDownload.class) .withNonnullFields("completionFuture") .verify(); } }
3,986
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultTransferProgressSnapshotTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot; public class DefaultTransferProgressSnapshotTest { @Test public void bytesTransferred_greaterThan_transferSize_shouldThrow() { DefaultTransferProgressSnapshot.Builder builder = DefaultTransferProgressSnapshot.builder() .transferredBytes(2L) .totalBytes(1L); assertThatThrownBy(builder::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("transferredBytes (2) must not be greater than totalBytes (1)"); } @Test public void ratioTransferred_withoutTransferSize_isEmpty() { TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(1L) .build(); assertThat(snapshot.ratioTransferred()).isNotPresent(); } @Test public void ratioTransferred_withTransferSize_isCorrect() { TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(1L) .totalBytes(2L) .build(); assertThat(snapshot.ratioTransferred()).hasValue(0.5); } @Test public void bytesRemainingTransferred_withoutTransferSize_isEmpty() { TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(1L) .build(); assertThat(snapshot.remainingBytes()).isNotPresent(); } @Test public void bytesRemainingTransferred_withTransferSize_isCorrect() { TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder() .transferredBytes(1L) .totalBytes(3L) .build(); assertThat(snapshot.remainingBytes()).hasValue(2L); } }
3,987
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerListenerTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.DrainingSubscriber; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.Download; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.DownloadRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.Upload; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.model.UploadRequest; import software.amazon.awssdk.transfer.s3.progress.TransferListener; public class S3TransferManagerListenerTest { private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); private S3CrtAsyncClient s3Crt; private S3TransferManager tm; private long contentLength; @BeforeEach public void methodSetup() { s3Crt = mock(S3CrtAsyncClient.class); tm = new GenericS3TransferManager(s3Crt, mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class), mock(DownloadDirectoryHelper.class)); contentLength = 1024L; when(s3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenAnswer(drainPutRequestBody()); when(s3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))) .thenAnswer(randomGetResponseBody(contentLength)); } @AfterEach public void methodTeardown() { tm.close(); } @Test public void uploadFile_success_shouldInvokeListener() throws Exception { TransferListener listener = mock(TransferListener.class); Path path = newTempFile(); Files.write(path, randomBytes(contentLength)); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(r -> r.bucket("bucket") .key("key")) .source(path) .addTransferListener(listener) .build(); FileUpload fileUpload = tm.uploadFile(uploadFileRequest); ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 = ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class); verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture()); TransferListener.Context.TransferInitiated ctx1 = captor1.getValue(); assertThat(ctx1.request()).isSameAs(uploadFileRequest); assertThat(ctx1.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx1.progressSnapshot().transferredBytes()).isZero(); ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 = ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class); verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture()); TransferListener.Context.BytesTransferred ctx2 = captor2.getValue(); assertThat(ctx2.request()).isSameAs(uploadFileRequest); assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive(); ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 = ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class); verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture()); TransferListener.Context.TransferComplete ctx3 = captor3.getValue(); assertThat(ctx3.request()).isSameAs(uploadFileRequest); assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength); assertThat(ctx3.completedTransfer()).isSameAs(fileUpload.completionFuture().get()); fileUpload.completionFuture().join(); verifyNoMoreInteractions(listener); } @Test public void upload_success_shouldInvokeListener() throws Exception { TransferListener listener = mock(TransferListener.class); UploadRequest uploadRequest = UploadRequest.builder() .putObjectRequest(r -> r.bucket("bucket") .key("key")) .requestBody(AsyncRequestBody.fromString("foo")) .addTransferListener(listener) .build(); Upload upload = tm.upload(uploadRequest); ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 = ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class); verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture()); TransferListener.Context.TransferInitiated ctx1 = captor1.getValue(); assertThat(ctx1.request()).isSameAs(uploadRequest); assertThat(ctx1.progressSnapshot().totalBytes()).hasValue(3L); assertThat(ctx1.progressSnapshot().transferredBytes()).isZero(); ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 = ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class); verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture()); TransferListener.Context.BytesTransferred ctx2 = captor2.getValue(); assertThat(ctx2.request()).isSameAs(uploadRequest); assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(3L); assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive(); ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 = ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class); verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture()); TransferListener.Context.TransferComplete ctx3 = captor3.getValue(); assertThat(ctx3.request()).isSameAs(uploadRequest); assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(3L); assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(3L); assertThat(ctx3.completedTransfer()).isSameAs(upload.completionFuture().get()); upload.completionFuture().join(); verifyNoMoreInteractions(listener); } @Test public void downloadFile_success_shouldInvokeListener() throws Exception { TransferListener listener = mock(TransferListener.class); DownloadFileRequest downloadRequest = DownloadFileRequest.builder() .getObjectRequest(r -> r.bucket("bucket") .key("key")) .destination(newTempFile()) .addTransferListener(listener) .build(); FileDownload download = tm.downloadFile(downloadRequest); ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 = ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class); verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture()); TransferListener.Context.TransferInitiated ctx1 = captor1.getValue(); assertThat(ctx1.request()).isSameAs(downloadRequest); // transferSize is not known until we receive GetObjectResponse header assertThat(ctx1.progressSnapshot().totalBytes()).isNotPresent(); assertThat(ctx1.progressSnapshot().transferredBytes()).isZero(); ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 = ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class); verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture()); TransferListener.Context.BytesTransferred ctx2 = captor2.getValue(); assertThat(ctx2.request()).isSameAs(downloadRequest); // transferSize should now be known assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive(); ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 = ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class); verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture()); TransferListener.Context.TransferComplete ctx3 = captor3.getValue(); assertThat(ctx3.request()).isSameAs(downloadRequest); assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength); assertThat(ctx3.completedTransfer()).isSameAs(download.completionFuture().get()); download.completionFuture().join(); verifyNoMoreInteractions(listener); } @Test public void download_success_shouldInvokeListener() throws Exception { TransferListener listener = mock(TransferListener.class); DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest = DownloadRequest.builder() .getObjectRequest(r -> r.bucket( "bucket") .key("key")) .responseTransformer(AsyncResponseTransformer.toBytes()) .addTransferListener(listener) .build(); Download<ResponseBytes<GetObjectResponse>> download = tm.download(downloadRequest); ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 = ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class); verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture()); TransferListener.Context.TransferInitiated ctx1 = captor1.getValue(); assertThat(ctx1.request()).isSameAs(downloadRequest); // transferSize is not known until we receive GetObjectResponse header assertThat(ctx1.progressSnapshot().totalBytes()).isNotPresent(); assertThat(ctx1.progressSnapshot().transferredBytes()).isZero(); ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 = ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class); verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture()); TransferListener.Context.BytesTransferred ctx2 = captor2.getValue(); assertThat(ctx2.request()).isSameAs(downloadRequest); // transferSize should now be known assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive(); ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 = ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class); verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture()); TransferListener.Context.TransferComplete ctx3 = captor3.getValue(); assertThat(ctx3.request()).isSameAs(downloadRequest); assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength); assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength); assertThat(ctx3.completedTransfer()).isSameAs(download.completionFuture().get()); download.completionFuture().join(); verifyNoMoreInteractions(listener); } @Test public void uploadFile_failure_shouldInvokeListener() throws Exception { TransferListener listener = mock(TransferListener.class); Path path = newTempFile(); Files.write(path, randomBytes(contentLength)); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(r -> r.bucket("bucket") .key("key")) .source(path) .addTransferListener(listener) .build(); SdkClientException sdkClientException = SdkClientException.create(""); when(s3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class))) .thenThrow(sdkClientException); FileUpload fileUpload = tm.uploadFile(uploadFileRequest); CompletableFuture<CompletedFileUpload> future = fileUpload.completionFuture(); assertThatThrownBy(future::join) .isInstanceOf(CompletionException.class) .hasCause(sdkClientException); ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 = ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class); verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture()); TransferListener.Context.TransferInitiated ctx1 = captor1.getValue(); assertThat(ctx1.request()).isSameAs(uploadFileRequest); assertThat(ctx1.progressSnapshot().transferredBytes()).isZero(); ArgumentCaptor<TransferListener.Context.TransferFailed> captor2 = ArgumentCaptor.forClass(TransferListener.Context.TransferFailed.class); verify(listener, timeout(1000).times(1)).transferFailed(captor2.capture()); TransferListener.Context.TransferFailed ctx2 = captor2.getValue(); assertThat(ctx2.request()).isSameAs(uploadFileRequest); assertThat(ctx2.progressSnapshot().transferredBytes()).isZero(); assertThat(ctx2.exception()).isEqualTo(sdkClientException); verifyNoMoreInteractions(listener); } @Test public void listener_exception_shouldBeSuppressed() throws Exception { TransferListener listener = throwingListener(); Path path = newTempFile(); Files.write(path, randomBytes(contentLength)); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(r -> r.bucket("bucket") .key("key")) .source(path) .addTransferListener(listener) .build(); FileUpload fileUpload = tm.uploadFile(uploadFileRequest); verify(listener, timeout(1000).times(1)).transferInitiated(any()); verify(listener, timeout(1000).times(1)).bytesTransferred(any()); verify(listener, timeout(1000).times(1)).transferComplete(any()); fileUpload.completionFuture().join(); verifyNoMoreInteractions(listener); } private static TransferListener throwingListener() { TransferListener listener = mock(TransferListener.class); RuntimeException e = new RuntimeException("Intentional exception for testing purposes"); doThrow(e).when(listener).transferInitiated(any()); doThrow(e).when(listener).bytesTransferred(any()); doThrow(e).when(listener).transferComplete(any()); doThrow(e).when(listener).transferFailed(any()); return listener; } private static Answer<CompletableFuture<PutObjectResponse>> drainPutRequestBody() { return invocationOnMock -> { AsyncRequestBody requestBody = invocationOnMock.getArgument(1, AsyncRequestBody.class); CompletableFuture<PutObjectResponse> cf = new CompletableFuture<>(); requestBody.subscribe(new DrainingSubscriber<ByteBuffer>() { @Override public void onError(Throwable t) { cf.completeExceptionally(t); } @Override public void onComplete() { cf.complete(PutObjectResponse.builder().build()); } }); return cf; }; } private static Answer<CompletableFuture<GetObjectResponse>> randomGetResponseBody(long contentLength) { return invocationOnMock -> { AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> responseTransformer = invocationOnMock.getArgument(1, AsyncResponseTransformer.class); CompletableFuture<GetObjectResponse> cf = responseTransformer.prepare(); responseTransformer.onResponse(GetObjectResponse.builder() .contentLength(contentLength) .build()); responseTransformer.onStream(AsyncRequestBody.fromBytes(randomBytes(contentLength))); return cf; }; } private Path newTempFile() { return fs.getPath("/", UUID.randomUUID().toString()); } private static byte[] randomBytes(long size) { byte[] bytes = new byte[Math.toIntExact(size)]; ThreadLocalRandom.current().nextBytes(bytes); return bytes; } }
3,988
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/CrtTransferManagerPauseAndResumeTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.time.Instant; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload; import software.amazon.awssdk.utils.CompletableFutureUtils; class CrtTransferManagerPauseAndResumeTest { private S3CrtAsyncClient mockS3Crt; private S3TransferManager tm; private UploadDirectoryHelper uploadDirectoryHelper; private DownloadDirectoryHelper downloadDirectoryHelper; private TransferManagerConfiguration configuration; private File file; @BeforeEach public void methodSetup() throws IOException { file = RandomTempFile.createTempFile("test", UUID.randomUUID().toString()); Files.write(file.toPath(), RandomStringUtils.randomAlphanumeric(1000).getBytes(StandardCharsets.UTF_8)); mockS3Crt = mock(S3CrtAsyncClient.class); uploadDirectoryHelper = mock(UploadDirectoryHelper.class); configuration = mock(TransferManagerConfiguration.class); downloadDirectoryHelper = mock(DownloadDirectoryHelper.class); tm = new CrtS3TransferManager(configuration, mockS3Crt, false); } @AfterEach public void methodTeardown() { file.delete(); tm.close(); } @Test void resumeDownloadFile_shouldSetRangeAccordingly() { GetObjectRequest getObjectRequest = getObjectRequest(); GetObjectResponse response = GetObjectResponse.builder().build(); Instant s3ObjectLastModified = Instant.now(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); HeadObjectResponse headObjectResponse = headObjectResponse(s3ObjectLastModified); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))) .thenReturn(CompletableFuture.completedFuture(response)); when(mockS3Crt.headObject(any(Consumer.class))) .thenReturn(CompletableFuture.completedFuture(headObjectResponse)); CompletedFileDownload completedFileDownload = tm.resumeDownloadFile(r -> r.bytesTransferred(file.length()) .downloadFileRequest(downloadFileRequest) .fileLastModified(fileLastModified) .s3ObjectLastModified(s3ObjectLastModified)) .completionFuture() .join(); assertThat(completedFileDownload.response()).isEqualTo(response); verifyActualGetObjectRequest(getObjectRequest, "bytes=1000-2000"); } @Test void resumeDownloadFile_headObjectFailed_shouldFail() { GetObjectRequest getObjectRequest = getObjectRequest(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); SdkClientException sdkClientException = SdkClientException.create("failed"); when(mockS3Crt.headObject(any(Consumer.class))) .thenReturn(CompletableFutureUtils.failedFuture(sdkClientException)); assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l) .downloadFileRequest(downloadFileRequest) .fileLastModified(fileLastModified) .s3ObjectLastModified(Instant.now())) .completionFuture() .join()).hasRootCause(sdkClientException); } @Test void resumeDownloadFile_errorShouldNotBeWrapped() { GetObjectRequest getObjectRequest = getObjectRequest(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); Error error = new OutOfMemoryError(); when(mockS3Crt.headObject(any(Consumer.class))) .thenReturn(CompletableFutureUtils.failedFuture(error)); assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l) .downloadFileRequest(downloadFileRequest) .fileLastModified(fileLastModified) .s3ObjectLastModified(Instant.now())) .completionFuture() .join()).hasCauseInstanceOf(Error.class); } @Test void resumeDownloadFile_SdkExceptionShouldNotBeWrapped() { GetObjectRequest getObjectRequest = getObjectRequest(); Instant fileLastModified = Instant.ofEpochMilli(file.lastModified()); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest) .destination(file) .build(); SdkException sdkException = SdkException.create("Failed to resume the request", new Throwable()); when(mockS3Crt.headObject(any(Consumer.class))) .thenReturn(CompletableFutureUtils.failedFuture(sdkException)); assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l) .downloadFileRequest(downloadFileRequest) .fileLastModified(fileLastModified) .s3ObjectLastModified(Instant.now())) .completionFuture() .join()).hasCause(sdkException); } @Test public void pauseAfterResumeBeforeHeadSucceeds() throws InterruptedException { DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest()) .destination(file) .build(); CompletableFuture<?> headFuture = new CompletableFuture<>(); when(mockS3Crt.headObject(any(Consumer.class))).thenReturn(headFuture); ResumableFileDownload originalResumable = ResumableFileDownload.builder() .bytesTransferred(file.length()) .downloadFileRequest(downloadFileRequest) .fileLastModified(Instant.ofEpochMilli(file.lastModified())) .s3ObjectLastModified(Instant.now()) .totalSizeInBytes(2000L) .build(); FileDownload fileDownload = tm.resumeDownloadFile(originalResumable); ResumableFileDownload newResumable = fileDownload.pause(); assertThat(newResumable).isEqualTo(originalResumable); assertThat(fileDownload.completionFuture()).isCancelled(); assertThat(headFuture).isCancelled(); } @Test public void pauseAfterResumeAfterHeadBeforeGetSucceeds() throws InterruptedException { DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(getObjectRequest()) .destination(file) .build(); CompletableFuture<?> getFuture = new CompletableFuture<>(); when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))).thenReturn(getFuture); Instant s3LastModified = Instant.now(); when(mockS3Crt.headObject(any(Consumer.class))) .thenReturn(CompletableFuture.completedFuture(headObjectResponse(s3LastModified))); ResumableFileDownload originalResumable = ResumableFileDownload.builder() .bytesTransferred(file.length()) .downloadFileRequest(downloadFileRequest) .fileLastModified(Instant.ofEpochMilli(file.lastModified())) .s3ObjectLastModified(s3LastModified) .totalSizeInBytes(2000L) .build(); FileDownload fileDownload = tm.resumeDownloadFile(originalResumable); ResumableFileDownload newResumable = fileDownload.pause(); assertThat(newResumable.s3ObjectLastModified()).isEqualTo(originalResumable.s3ObjectLastModified()); assertThat(newResumable.bytesTransferred()).isEqualTo(originalResumable.bytesTransferred()); assertThat(newResumable.totalSizeInBytes()).isEqualTo(originalResumable.totalSizeInBytes()); assertThat(newResumable.fileLastModified()).isEqualTo(originalResumable.fileLastModified()); // Download will be modified now that we finished the head request assertThat(newResumable.downloadFileRequest()).isNotEqualTo(originalResumable.downloadFileRequest()); assertThat(fileDownload.completionFuture()).isCancelled(); assertThat(getFuture).isCancelled(); } private void verifyActualGetObjectRequest(GetObjectRequest getObjectRequest, String range) { ArgumentCaptor<GetObjectRequest> getObjectRequestArgumentCaptor = ArgumentCaptor.forClass(GetObjectRequest.class); verify(mockS3Crt).getObject(getObjectRequestArgumentCaptor.capture(), any(AsyncResponseTransformer.class)); GetObjectRequest actualRequest = getObjectRequestArgumentCaptor.getValue(); assertThat(actualRequest.bucket()).isEqualTo(getObjectRequest.bucket()); assertThat(actualRequest.key()).isEqualTo(getObjectRequest.key()); assertThat(actualRequest.range()).isEqualTo(range); } private static GetObjectRequest getObjectRequest() { return GetObjectRequest.builder() .key("key") .bucket("bucket") .build(); } private static HeadObjectResponse headObjectResponse(Instant s3ObjectLastModified) { return HeadObjectResponse .builder() .contentLength(2000L) .lastModified(s3ObjectLastModified) .build(); } }
3,989
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/AsyncBufferingSubscriberTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Subscription; class AsyncBufferingSubscriberTest { private static final int MAX_CONCURRENT_EXECUTIONS = 5; private AsyncBufferingSubscriber<String> subscriber; private Function<String, CompletableFuture<?>> consumer; private CompletableFuture<Void> returnFuture; private final List<CompletableFuture<Void>> futures = new ArrayList<>(); private static ScheduledExecutorService scheduledExecutorService; @BeforeAll public static void setUp() { scheduledExecutorService = Executors.newScheduledThreadPool(5); } @BeforeEach public void setUpPerTest() { returnFuture = new CompletableFuture<>(); for (int i = 0; i < 101; i++) { futures.add(new CompletableFuture<>()); } Iterator<CompletableFuture<Void>> iterator = futures.iterator(); consumer = s -> { CompletableFuture<Void> future = iterator.next(); scheduledExecutorService.schedule(() -> { future.complete(null); }, 200, TimeUnit.MILLISECONDS); return future; }; subscriber = new AsyncBufferingSubscriber<>(consumer, returnFuture, MAX_CONCURRENT_EXECUTIONS); } @AfterAll public static void cleanUp() { scheduledExecutorService.shutdown(); } @ParameterizedTest @ValueSource(ints = {1, 4, 11, 20, 100}) void differentNumberOfStrings_shouldCompleteSuccessfully(int numberOfStrings) throws Exception { Flowable.fromArray(IntStream.range(0, numberOfStrings).mapToObj(String::valueOf).toArray(String[]::new)).subscribe(subscriber); List<Integer> numRequestsInFlightSampling = new ArrayList<>(); Disposable disposable = Observable.interval(100, TimeUnit.MILLISECONDS, Schedulers.newThread()) .map(time -> subscriber.numRequestsInFlight()) .subscribe(numRequestsInFlightSampling::add, t -> {}); returnFuture.get(1000, TimeUnit.SECONDS); assertThat(returnFuture).isCompleted().isNotCompletedExceptionally(); if (numberOfStrings >= MAX_CONCURRENT_EXECUTIONS) { assertThat(numRequestsInFlightSampling).contains(MAX_CONCURRENT_EXECUTIONS); } disposable.dispose(); } @Test void onErrorInvoked_shouldCompleteFutureExceptionally() { subscriber.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { } }); RuntimeException exception = new RuntimeException("test"); subscriber.onError(exception); assertThat(returnFuture).isCompletedExceptionally(); } }
3,990
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DownloadDirectoryHelperTest.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.transfer.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.transfer.s3.util.S3ApiCallMockUtils.stubSuccessfulListObjects; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import org.assertj.core.util.Sets; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.EncodingType; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileDownload; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgress; import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.DirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; import software.amazon.awssdk.transfer.s3.progress.TransferListener; public class DownloadDirectoryHelperTest { private static final String DIRECTORY_NAME = "test"; private FileSystem fs; private Path directory; private Function<DownloadFileRequest, FileDownload> singleDownloadFunction; private DownloadDirectoryHelper downloadDirectoryHelper; private ListObjectsHelper listObjectsHelper; @BeforeEach public void methodSetup() { fs = Jimfs.newFileSystem(); directory = fs.getPath("test"); listObjectsHelper = mock(ListObjectsHelper.class); singleDownloadFunction = mock(Function.class); downloadDirectoryHelper = new DownloadDirectoryHelper(TransferManagerConfiguration.builder().build(), listObjectsHelper, singleDownloadFunction); } @AfterEach public void methodCleanup() throws IOException { fs.close(); } public static Collection<FileSystem> fileSystems() { return Sets.newHashSet(Arrays.asList(Jimfs.newFileSystem(Configuration.unix()), Jimfs.newFileSystem(Configuration.osX()), Jimfs.newFileSystem(Configuration.windows()))); } @Test void downloadDirectory_allDownloadsSucceed_failedDownloadsShouldBeEmpty() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); FileDownload fileDownload = newSuccessfulDownload(); FileDownload fileDownload2 = newSuccessfulDownload(); when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS); ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); verify(singleDownloadFunction, times(2)).apply(argumentCaptor.capture()); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); assertThat(argumentCaptor.getAllValues()).element(0).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo( "key1")); assertThat(argumentCaptor.getAllValues()).element(1).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo( "key2")); } @ParameterizedTest @ValueSource(strings = {"/blah", "../blah/object.dat", "blah/../../object.dat", "blah/../object/../../blah/another/object.dat", "../{directory-name}-2/object.dat"}) void invalidKey_shouldThrowException(String testingString) throws Exception { assertExceptionThrownForInvalidKeys(testingString); } private void assertExceptionThrownForInvalidKeys(String key) throws IOException { Path destinationDirectory = Files.createTempDirectory("test"); String lastElement = destinationDirectory.getName(destinationDirectory.getNameCount() - 1).toString(); key = key.replace("{directory-name}", lastElement); stubSuccessfulListObjects(listObjectsHelper, key); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(destinationDirectory) .bucket("bucket") .build()); assertThatThrownBy(() -> downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(SdkClientException.class).getRootCause().hasMessageContaining("Cannot download key"); } @Test void downloadDirectory_cancel_shouldCancelAllFutures() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); CompletableFuture<CompletedFileDownload> future = new CompletableFuture<>(); FileDownload fileDownload = newDownload(future); CompletableFuture<CompletedFileDownload> future2 = new CompletableFuture<>(); FileDownload fileDownload2 = newDownload(future2); when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .build()); downloadDirectory.completionFuture().cancel(true); assertThatThrownBy(() -> future.get(1, TimeUnit.SECONDS)) .isInstanceOf(CancellationException.class); assertThatThrownBy(() -> future2.get(1, TimeUnit.SECONDS)) .isInstanceOf(CancellationException.class); } @Test void downloadDirectory_partialSuccess_shouldProvideFailedDownload() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); FileDownload fileDownload = newSuccessfulDownload(); SdkClientException exception = SdkClientException.create("failed"); FileDownload fileDownload2 = newFailedDownload(exception); when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS); assertThat(completedDirectoryDownload.failedTransfers()).hasSize(1) .element(0).satisfies(failedFileDownload -> assertThat(failedFileDownload.exception()).isEqualTo(exception)); } @Test void downloadDirectory_withFilter_shouldHonorFilter() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); FileDownload fileDownload = newSuccessfulDownload(); FileDownload fileDownload2 = newSuccessfulDownload(); when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .filter(s3Object -> "key2".equals(s3Object.key())) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS); ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); verify(singleDownloadFunction, times(1)).apply(argumentCaptor.capture()); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); assertThat(argumentCaptor.getAllValues()).element(0).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo( "key2")); } @Test void downloadDirectory_withDownloadRequestTransformer_shouldTransform() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); FileDownload fileDownload = newSuccessfulDownload(); FileDownload fileDownload2 = newSuccessfulDownload(); when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); Path newDestination = Paths.get("/new/path"); GetObjectRequest newGetObjectRequest = GetObjectRequest.builder().build(); List<TransferListener> newTransferListener = Arrays.asList(LoggingTransferListener.create()); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .downloadFileRequestTransformer(d -> d.destination(newDestination) .getObjectRequest(newGetObjectRequest) .transferListeners(newTransferListener)) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS); ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); verify(singleDownloadFunction, times(2)).apply(argumentCaptor.capture()); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); assertThat(argumentCaptor.getAllValues()).allSatisfy(d -> { assertThat(d.getObjectRequest()).isEqualTo(newGetObjectRequest); assertThat(d.transferListeners()).isEqualTo(newTransferListener); assertThat(d.destination()).isEqualTo(newDestination); }); } @Test void downloadDirectory_withListObjectsRequestTransformer_shouldTransform() throws Exception { stubSuccessfulListObjects(listObjectsHelper, "key1", "key2"); FileDownload fileDownload = newSuccessfulDownload(); FileDownload fileDownload2 = newSuccessfulDownload(); EncodingType newEncodingType = EncodingType.URL; int newMaxKeys = 10; when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .listObjectsV2RequestTransformer(l -> l.encodingType(newEncodingType) .maxKeys(newMaxKeys)) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS); ArgumentCaptor<ListObjectsV2Request> argumentCaptor = ArgumentCaptor.forClass(ListObjectsV2Request.class); verify(listObjectsHelper, times(1)).listS3ObjectsRecursively(argumentCaptor.capture()); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); assertThat(argumentCaptor.getValue()).satisfies(l -> { assertThat(l.encodingType()).isEqualTo(newEncodingType); assertThat(l.maxKeys()).isEqualTo(newMaxKeys); }); } @ParameterizedTest @MethodSource("fileSystems") void downloadDirectory_shouldRecursivelyDownload(FileSystem jimfs) { directory = jimfs.getPath("test"); String[] keys = {"1.png", "2020/1.png", "2021/1.png", "2022/1.png", "2023/1/1.png"}; stubSuccessfulListObjects(listObjectsHelper, keys); ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); when(singleDownloadFunction.apply(requestArgumentCaptor.capture())) .thenReturn(completedDownload()); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join(); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.getObjectRequest().bucket()).isEqualTo("bucket")); assertThat(actualRequests.size()).isEqualTo(keys.length); verifyDestinationPathForSingleDownload(jimfs, "/", keys, actualRequests); } /** * The S3 bucket has the following keys: * abc/def/image.jpg * abc/def/title.jpg * abc/def/ghi/xyz.txt * * if the prefix is "abc/def/", the structure should like this: * image.jpg * title.jpg * ghi * - xyz.txt */ @ParameterizedTest @MethodSource("fileSystems") void downloadDirectory_withPrefix_shouldStripPrefixInDestinationPath(FileSystem jimfs) { directory = jimfs.getPath("test"); String[] keys = {"abc/def/image.jpg", "abc/def/title.jpg", "abc/def/ghi/xyz.txt"}; stubSuccessfulListObjects(listObjectsHelper, keys); ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); when(singleDownloadFunction.apply(requestArgumentCaptor.capture())) .thenReturn(completedDownload()); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .listObjectsV2RequestTransformer(l -> l.prefix( "abc/def/")) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join(); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); assertThat(actualRequests.size()).isEqualTo(keys.length); List<String> destinations = actualRequests.stream().map(u -> u.destination().toString()) .collect(Collectors.toList()); String jimfsSeparator = jimfs.getSeparator(); List<String> expectedPaths = Arrays.asList("image.jpg", "title.jpg", "ghi/xyz.txt").stream() .map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace("/",jimfsSeparator)).collect(Collectors.toList()); assertThat(destinations).isEqualTo(expectedPaths); } @ParameterizedTest @MethodSource("fileSystems") void downloadDirectory_containsObjectWithPrefixInIt_shouldInclude(FileSystem jimfs) { String prefix = "abc"; directory = jimfs.getPath("test"); String[] keys = {"abc/def/image.jpg", "abc/def/title.jpg", "abcd"}; stubSuccessfulListObjects(listObjectsHelper, keys); ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); when(singleDownloadFunction.apply(requestArgumentCaptor.capture())) .thenReturn(completedDownload()); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .listObjectsV2RequestTransformer(l -> l.prefix(prefix)) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join(); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); assertThat(actualRequests.size()).isEqualTo(keys.length); List<String> destinations = actualRequests.stream().map(u -> u.destination().toString()) .collect(Collectors.toList()); String jimfsSeparator = jimfs.getSeparator(); List<String> expectedPaths = Arrays.asList("def/image.jpg", "def/title.jpg", "abcd").stream() .map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace("/",jimfsSeparator)).collect(Collectors.toList()); assertThat(destinations).isEqualTo(expectedPaths); } @ParameterizedTest @MethodSource("fileSystems") void downloadDirectory_withDelimiter_shouldHonor(FileSystem jimfs) { directory = jimfs.getPath("test"); String delimiter = "|"; String[] keys = {"1.png", "2020|1.png", "2021|1.png", "2022|1.png", "2023|1|1.png"}; stubSuccessfulListObjects(listObjectsHelper, keys); ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class); when(singleDownloadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedDownload()); DirectoryDownload downloadDirectory = downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder() .destination(directory) .bucket("bucket") .listObjectsV2RequestTransformer(r -> r.delimiter(delimiter)) .build()); CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join(); assertThat(completedDirectoryDownload.failedTransfers()).isEmpty(); List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues(); actualRequests.forEach(r -> assertThat(r.getObjectRequest().bucket()).isEqualTo("bucket")); assertThat(actualRequests.size()).isEqualTo(keys.length); verifyDestinationPathForSingleDownload(jimfs, delimiter, keys, actualRequests); } @ParameterizedTest @MethodSource("fileSystems") void downloadDirectory_notDirectory_shouldCompleteFutureExceptionally(FileSystem jimfs) throws IOException { directory = jimfs.getPath("test"); Path file = jimfs.getPath("afile" + UUID.randomUUID()); Files.write(file, "hellowrold".getBytes(StandardCharsets.UTF_8)); assertThatThrownBy(() -> downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder().destination(file) .bucket("bucketName").build()).completionFuture().join()) .hasMessageContaining("is not a directory").hasCauseInstanceOf(IllegalArgumentException.class); } private static DefaultFileDownload completedDownload() { return new DefaultFileDownload(CompletableFuture.completedFuture(CompletedFileDownload.builder() .response(GetObjectResponse.builder().build()) .build()), new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()), () -> DownloadFileRequest.builder().getObjectRequest(GetObjectRequest.builder().build()) .destination(Paths.get(".")) .build(), null); } private static void verifyDestinationPathForSingleDownload(FileSystem jimfs, String delimiter, String[] keys, List<DownloadFileRequest> actualRequests) { String jimfsSeparator = jimfs.getSeparator(); List<String> destinations = actualRequests.stream().map(u -> u.destination().toString()) .collect(Collectors.toList()); List<String> expectedPaths = Arrays.stream(keys).map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace(delimiter, jimfsSeparator)).collect(Collectors.toList()); assertThat(destinations).isEqualTo(expectedPaths); } private FileDownload newSuccessfulDownload() { GetObjectResponse getObjectResponse = GetObjectResponse.builder().eTag(UUID.randomUUID().toString()).build(); CompletedFileDownload completedFileDownload = CompletedFileDownload.builder().response(getObjectResponse).build(); CompletableFuture<CompletedFileDownload> successfulFuture = new CompletableFuture<>(); FileDownload fileDownload = newDownload(successfulFuture); successfulFuture.complete(completedFileDownload); return fileDownload; } private FileDownload newFailedDownload(SdkClientException exception) { CompletableFuture<CompletedFileDownload> failedFuture = new CompletableFuture<>(); FileDownload fileDownload2 = newDownload(failedFuture); failedFuture.completeExceptionally(exception); return fileDownload2; } private FileDownload newDownload(CompletableFuture<CompletedFileDownload> future) { return new DefaultFileDownload(future, new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder() .transferredBytes(0L) .build()), () -> DownloadFileRequest.builder().destination(Paths.get( ".")).getObjectRequest(GetObjectRequest.builder().build()).build(), null); } }
3,991
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileDownloadSerializerTest.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.transfer.s3.internal.serialization; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.services.s3.model.ChecksumMode; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.RequestPayer; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; class ResumableFileDownloadSerializerTest { private static final Path PATH = RandomTempFile.randomUncreatedFile().toPath(); private static final Instant DATE1 = parseIso8601Date("2022-05-13T21:55:52.529Z"); private static final Instant DATE2 = parseIso8601Date("2022-05-15T21:50:11.308Z"); private static final Map<String, GetObjectRequest> GET_OBJECT_REQUESTS; static { Map<String, GetObjectRequest> requests = new HashMap<>(); requests.put("EMPTY", GetObjectRequest.builder().build()); requests.put("STANDARD", GetObjectRequest.builder().bucket("BUCKET").key("KEY").build()); requests.put("ALL_TYPES", GetObjectRequest.builder() .bucket("BUCKET") .key("KEY") .partNumber(1) .ifModifiedSince(parseIso8601Date("2020-01-01T12:10:30Z")) .checksumMode(ChecksumMode.ENABLED) .requestPayer(RequestPayer.REQUESTER) .build()); GET_OBJECT_REQUESTS = Collections.unmodifiableMap(requests); } @ParameterizedTest @MethodSource("downloadObjects") void serializeDeserialize_ShouldWorkForAllDownloads(ResumableFileDownload download) { byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download); ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload); assertThat(deserializedDownload).isEqualTo(download); } @Test void serializeDeserialize_fromStoredString_ShouldWork() { ResumableFileDownload download = ResumableFileDownload.builder() .downloadFileRequest(d -> d.destination(Paths.get("test/request")) .getObjectRequest(GET_OBJECT_REQUESTS.get("ALL_TYPES"))) .bytesTransferred(1000L) .fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z")) .totalSizeInBytes(5000L) .s3ObjectLastModified(parseIso8601Date("2022-03-10T08:21:00Z")) .build(); byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download); assertThat(new String(serializedDownload, StandardCharsets.UTF_8)).isEqualTo(SERIALIZED_DOWNLOAD_OBJECT); ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(SERIALIZED_DOWNLOAD_OBJECT.getBytes(StandardCharsets.UTF_8)); assertThat(deserializedDownload).isEqualTo(download); } @Test void serializeDeserialize_DoesNotPersistConfiguration() { ResumableFileDownload download = ResumableFileDownload.builder() .downloadFileRequest(d -> d.destination(PATH) .getObjectRequest(GET_OBJECT_REQUESTS.get("STANDARD")) .addTransferListener(LoggingTransferListener.create())) .bytesTransferred(1000L) .build(); byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download); ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload); DownloadFileRequest fileRequestWithoutConfig = download.downloadFileRequest().copy(r -> r.transferListeners((List) null)); assertThat(deserializedDownload).isEqualTo(download.copy(d -> d.downloadFileRequest(fileRequestWithoutConfig))); } @Test void serializeDeserialize_DoesNotPersistRequestOverrideConfiguration() { GetObjectRequest requestWithOverride = GetObjectRequest.builder() .bucket("BUCKET") .key("KEY") .overrideConfiguration(c -> c.apiCallAttemptTimeout(Duration.ofMillis(20)).build()) .build(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .destination(PATH) .getObjectRequest(requestWithOverride) .build(); ResumableFileDownload download = ResumableFileDownload.builder() .downloadFileRequest(downloadFileRequest) .build(); byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download); ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload); GetObjectRequest requestWithoutOverride = requestWithOverride.copy(r -> r.overrideConfiguration((AwsRequestOverrideConfiguration) null)); DownloadFileRequest fileRequestCopy = downloadFileRequest.copy(r -> r.getObjectRequest(requestWithoutOverride)); assertThat(deserializedDownload).isEqualTo(download.copy(d -> d.downloadFileRequest(fileRequestCopy))); } public static Collection<ResumableFileDownload> downloadObjects() { return Stream.of(differentDownloadSettings(), differentGetObjects()) .flatMap(Collection::stream).collect(Collectors.toList()); } private static List<ResumableFileDownload> differentGetObjects() { return GET_OBJECT_REQUESTS.values() .stream() .map(request -> resumableFileDownload(1000L, null, DATE1, null, downloadRequest(PATH, request))) .collect(Collectors.toList()); } private static List<ResumableFileDownload> differentDownloadSettings() { DownloadFileRequest request = downloadRequest(PATH, GET_OBJECT_REQUESTS.get("STANDARD")); return Arrays.asList( resumableFileDownload(null, null, null, null, request), resumableFileDownload(1000L, null, null, null, request), resumableFileDownload(1000L, null, DATE1, null, request), resumableFileDownload(1000L, 2000L, DATE1, DATE2, request), resumableFileDownload(Long.MAX_VALUE, Long.MAX_VALUE, DATE1, DATE2, request) ); } private static ResumableFileDownload resumableFileDownload(Long bytesTransferred, Long totalSizeInBytes, Instant fileLastModified, Instant s3ObjectLastModified, DownloadFileRequest request) { ResumableFileDownload.Builder builder = ResumableFileDownload.builder() .downloadFileRequest(request) .bytesTransferred(bytesTransferred); if (totalSizeInBytes != null) { builder.totalSizeInBytes(totalSizeInBytes); } if (fileLastModified != null) { builder.fileLastModified(fileLastModified); } if (s3ObjectLastModified != null) { builder.s3ObjectLastModified(s3ObjectLastModified); } return builder.build(); } private static DownloadFileRequest downloadRequest(Path path, GetObjectRequest request) { return DownloadFileRequest.builder() .getObjectRequest(request) .destination(path) .build(); } private static final String SERIALIZED_DOWNLOAD_OBJECT = "{\"bytesTransferred\":1000,\"fileLastModified\":1646734530.000," + "\"totalSizeInBytes\":5000,\"s3ObjectLastModified\":1646900460" + ".000,\"downloadFileRequest\":{\"destination\":\"test/request\"," + "\"getObjectRequest\":{\"Bucket\":\"BUCKET\"," + "\"If-Modified-Since\":1577880630.000,\"Key\":\"KEY\"," + "\"x-amz-request-payer\":\"requester\",\"partNumber\":1," + "\"x-amz-checksum-mode\":\"ENABLED\"}}}"; }
3,992
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerMarshallerUtilsTest.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.transfer.s3.internal.serialization; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.protocol.MarshallingType; class TransferManagerMarshallerUtilsTest { @ParameterizedTest @MethodSource("marshallingValues") void getMarshallerByType(Object o, MarshallingType<Object> type, TransferManagerJsonMarshaller<?> expectedMarshaller) { TransferManagerJsonMarshaller<Object> marshaller = TransferManagerMarshallingUtils.getMarshaller(type, o); assertThat(marshaller).isNotNull() .isEqualTo(expectedMarshaller); } @ParameterizedTest @MethodSource("marshallingValues") void findMarshallerByValue(Object o, MarshallingType<Object> type, TransferManagerJsonMarshaller<?> expectedMarshaller) { TransferManagerJsonMarshaller<Object> marshaller = TransferManagerMarshallingUtils.getMarshaller(o); assertThat(marshaller).isEqualTo(expectedMarshaller); } @ParameterizedTest @MethodSource("unmarshallingValues") void getUnmarshaller(MarshallingType<Object> type, TransferManagerJsonUnmarshaller<?> expectedUnmarshaller) { TransferManagerJsonUnmarshaller<Object> marshaller = (TransferManagerJsonUnmarshaller<Object>) TransferManagerMarshallingUtils.getUnmarshaller(type); assertThat(marshaller).isEqualTo(expectedUnmarshaller); } @Test void whenNoMarshaller_shouldThrowException() { assertThatThrownBy(() -> TransferManagerMarshallingUtils.getMarshaller(MarshallingType.DOCUMENT, Document.fromNull())) .isInstanceOf(IllegalStateException.class).hasMessageContaining("Cannot find a marshaller"); } @Test void whenNoUnmarshaller_shouldThrowException() { assertThatThrownBy(() -> TransferManagerMarshallingUtils.getUnmarshaller(MarshallingType.DOCUMENT)) .isInstanceOf(IllegalStateException.class).hasMessageContaining("Cannot find an unmarshaller"); } private static Stream<Arguments> marshallingValues() { return Stream.of(Arguments.of("String", MarshallingType.STRING, TransferManagerJsonMarshaller.STRING), Arguments.of((short) 10, MarshallingType.SHORT, TransferManagerJsonMarshaller.SHORT), Arguments.of(100, MarshallingType.INTEGER, TransferManagerJsonMarshaller.INTEGER), Arguments.of(100L, MarshallingType.LONG, TransferManagerJsonMarshaller.LONG), Arguments.of(Instant.now(), MarshallingType.INSTANT, TransferManagerJsonMarshaller.INSTANT), Arguments.of(null, MarshallingType.NULL, TransferManagerJsonMarshaller.NULL), Arguments.of(12.34f, MarshallingType.FLOAT, TransferManagerJsonMarshaller.FLOAT), Arguments.of(12.34d, MarshallingType.DOUBLE, TransferManagerJsonMarshaller.DOUBLE), Arguments.of(new BigDecimal(34), MarshallingType.BIG_DECIMAL, TransferManagerJsonMarshaller.BIG_DECIMAL), Arguments.of(true, MarshallingType.BOOLEAN, TransferManagerJsonMarshaller.BOOLEAN), Arguments.of(SdkBytes.fromString("String", StandardCharsets.UTF_8), MarshallingType.SDK_BYTES, TransferManagerJsonMarshaller.SDK_BYTES), Arguments.of(Arrays.asList(100, 45), MarshallingType.LIST, TransferManagerJsonMarshaller.LIST), Arguments.of(Collections.singletonMap("key", "value"), MarshallingType.MAP, TransferManagerJsonMarshaller.MAP) ); } private static Stream<Arguments> unmarshallingValues() { return Stream.of(Arguments.of(MarshallingType.STRING, TransferManagerJsonUnmarshaller.STRING), Arguments.of(MarshallingType.SHORT, TransferManagerJsonUnmarshaller.SHORT), Arguments.of(MarshallingType.INTEGER, TransferManagerJsonUnmarshaller.INTEGER), Arguments.of(MarshallingType.LONG, TransferManagerJsonUnmarshaller.LONG), Arguments.of(MarshallingType.INSTANT, TransferManagerJsonUnmarshaller.INSTANT), Arguments.of(MarshallingType.NULL, TransferManagerJsonUnmarshaller.NULL), Arguments.of(MarshallingType.FLOAT, TransferManagerJsonUnmarshaller.FLOAT), Arguments.of(MarshallingType.DOUBLE, TransferManagerJsonUnmarshaller.DOUBLE), Arguments.of(MarshallingType.BIG_DECIMAL, TransferManagerJsonUnmarshaller.BIG_DECIMAL), Arguments.of(MarshallingType.BOOLEAN, TransferManagerJsonUnmarshaller.BOOLEAN), Arguments.of(MarshallingType.SDK_BYTES, TransferManagerJsonUnmarshaller.SDK_BYTES) ); } }
3,993
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileUploadSerializerTest.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.transfer.s3.internal.serialization; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.ObjectCannedACL; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.RequestPayer; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; class ResumableFileUploadSerializerTest { private static final Instant DATE = parseIso8601Date("2022-05-15T21:50:11.308Z"); private static final Path PATH = RandomTempFile.randomUncreatedFile().toPath(); private static final Map<String, PutObjectRequest> PUT_OBJECT_REQUESTS; static { Map<String, PutObjectRequest> requests = new HashMap<>(); requests.put("EMPTY", PutObjectRequest.builder().build()); requests.put("STANDARD", PutObjectRequest.builder().bucket("BUCKET").key("KEY").build()); Map<String, String> metadata = new HashMap<>(); metadata.put("foo", "bar"); requests.put("ALL_TYPES", PutObjectRequest.builder() .bucket("BUCKET") .key("KEY") .acl(ObjectCannedACL.PRIVATE) .checksumAlgorithm(ChecksumAlgorithm.CRC32) .requestPayer(RequestPayer.REQUESTER) .metadata(metadata) .build()); PUT_OBJECT_REQUESTS = Collections.unmodifiableMap(requests); } @ParameterizedTest @MethodSource("uploadObjects") void serializeDeserialize_ShouldWorkForAllUploads(ResumableFileUpload upload) { byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload); ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload); assertThat(deserializedUpload).isEqualTo(upload); } @Test void serializeDeserialize_fromStoredString_ShouldWork() { ResumableFileUpload upload = ResumableFileUpload.builder() .uploadFileRequest(d -> d.source(Paths.get("test/request")) .putObjectRequest(PUT_OBJECT_REQUESTS.get("ALL_TYPES"))) .fileLength(5000L) .fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z")) .multipartUploadId("id") .totalParts(40L) .partSizeInBytes(1024L) .build(); byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload); assertThat(new String(serializedUpload, StandardCharsets.UTF_8)).isEqualTo(SERIALIZED_UPLOAD_OBJECT); ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(SERIALIZED_UPLOAD_OBJECT.getBytes(StandardCharsets.UTF_8)); assertThat(deserializedUpload).isEqualTo(upload); } @Test void serializeDeserialize_DoesNotPersistConfiguration() { ResumableFileUpload upload = ResumableFileUpload.builder() .uploadFileRequest(d -> d.source(PATH) .putObjectRequest(PUT_OBJECT_REQUESTS.get("STANDARD")) .addTransferListener(LoggingTransferListener.create())) .fileLength(5000L) .fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z")) .build(); byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload); ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload); UploadFileRequest fileRequestWithoutConfig = upload.uploadFileRequest().copy(r -> r.transferListeners((List) null)); assertThat(deserializedUpload).isEqualTo(upload.copy(d -> d.uploadFileRequest(fileRequestWithoutConfig))); } @Test void serializeDeserialize_DoesNotPersistRequestOverrideConfiguration() { PutObjectRequest requestWithOverride = PutObjectRequest.builder() .bucket("BUCKET") .key("KEY") .overrideConfiguration(c -> c.apiCallAttemptTimeout(Duration.ofMillis(20)).build()) .build(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .source(PATH) .putObjectRequest(requestWithOverride) .build(); ResumableFileUpload upload = ResumableFileUpload.builder() .uploadFileRequest(uploadFileRequest) .fileLastModified(DATE) .fileLength(1000L) .build(); byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload); ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload); PutObjectRequest requestWithoutOverride = requestWithOverride.copy(r -> r.overrideConfiguration((AwsRequestOverrideConfiguration) null)); UploadFileRequest fileRequestCopy = uploadFileRequest.copy(r -> r.putObjectRequest(requestWithoutOverride)); assertThat(deserializedUpload).isEqualTo(upload.copy(d -> d.uploadFileRequest(fileRequestCopy))); } public static Collection<ResumableFileUpload> uploadObjects() { return Stream.of(differentUploadSettings(), differentPutObjects()) .flatMap(Collection::stream).collect(Collectors.toList()); } private static List<ResumableFileUpload> differentPutObjects() { return PUT_OBJECT_REQUESTS.values() .stream() .map(request -> resumableFileUpload(1000L, null, null, null)) .collect(Collectors.toList()); } private static List<ResumableFileUpload> differentUploadSettings() { return Arrays.asList( resumableFileUpload(null, null, null, null), resumableFileUpload(1000L, null, null, null), resumableFileUpload(1000L, 5L, 1L, null), resumableFileUpload(1000L, 5L, 2L, "1234") ); } private static ResumableFileUpload resumableFileUpload(Long partSizeInBytes, Long totalNumberOfParts, Long transferredParts, String multipartUploadId) { UploadFileRequest request = downloadRequest(PATH, PUT_OBJECT_REQUESTS.get("STANDARD")); return ResumableFileUpload.builder() .uploadFileRequest(request) .fileLength(1000L) .multipartUploadId(multipartUploadId) .fileLastModified(DATE) .partSizeInBytes(partSizeInBytes) .totalParts(totalNumberOfParts) .transferredParts(transferredParts) .build(); } private static UploadFileRequest downloadRequest(Path path, PutObjectRequest request) { return UploadFileRequest.builder() .putObjectRequest(request) .source(path) .build(); } private static final String SERIALIZED_UPLOAD_OBJECT = "{\"fileLength\":5000,\"fileLastModified\":1646734530.000," + "\"multipartUploadId\":\"id\",\"partSizeInBytes\":1024," + "\"totalParts\":40,\"uploadFileRequest\":{\"source\":\"test" + "/request\",\"putObjectRequest\":{\"x-amz-acl\":\"private\"," + "\"Bucket\":\"BUCKET\",\"x-amz-sdk-checksum-algorithm\":\"CRC32\"," + "\"Key\":\"KEY\",\"x-amz-meta-\":{\"foo\":\"bar\"}," + "\"x-amz-request-payer\":\"requester\"}}}"; }
3,994
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonUnmarshallerTest.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.transfer.s3.internal.serialization; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.DateUtils; class TransferManagerJsonUnmarshallerTest { @ParameterizedTest @MethodSource("unmarshallingValues") void deserialize_ShouldWorkForAllSupportedTypes(JsonNode node, Object o, TransferManagerJsonUnmarshaller<?> unmarshaller) { Object param = unmarshaller.unmarshall(node); assertThat(param).isEqualTo(o); } private static Stream<Arguments> unmarshallingValues() { return Stream.of(Arguments.of(new StringJsonNode("String"), "String", TransferManagerJsonUnmarshaller.STRING), Arguments.of(new NumberJsonNode("100"), (short) 100, TransferManagerJsonUnmarshaller.SHORT), Arguments.of(new NumberJsonNode("100"), 100, TransferManagerJsonUnmarshaller.INTEGER), Arguments.of(new NumberJsonNode("100"), 100L, TransferManagerJsonUnmarshaller.LONG), Arguments.of(new NumberJsonNode("12.34"), 12.34f, TransferManagerJsonUnmarshaller.FLOAT), Arguments.of(new NumberJsonNode("12.34"), 12.34d, TransferManagerJsonUnmarshaller.DOUBLE), Arguments.of(new NumberJsonNode("2.3"), new BigDecimal("2.3"), TransferManagerJsonUnmarshaller.BIG_DECIMAL), Arguments.of(new NumberJsonNode("1646734530.000"), DateUtils.parseIso8601Date("2022-03-08T10:15:30Z"), TransferManagerJsonUnmarshaller.INSTANT), Arguments.of(NullJsonNode.instance(), null, TransferManagerJsonUnmarshaller.NULL), Arguments.of(new StringJsonNode(BinaryUtils.toBase64(SdkBytes.fromString("100", StandardCharsets.UTF_8) .asByteArray())), SdkBytes.fromString("100", StandardCharsets.UTF_8), TransferManagerJsonUnmarshaller.SDK_BYTES) ); } }
3,995
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonMarshallerTest.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.transfer.s3.internal.serialization; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.protocols.jsoncore.JsonWriter; import software.amazon.awssdk.utils.DateUtils; class TransferManagerJsonMarshallerTest { @ParameterizedTest @MethodSource("marshallingValues") void serialize_ShouldWorkForAllSupportedTypes(Object o, TransferManagerJsonMarshaller<Object> marshaller, String expected) { JsonWriter writer = JsonWriter.create(); writer.writeStartObject(); marshaller.marshall(o, writer, "param"); writer.writeEndObject(); String serializedResult = new String(writer.getBytes(), StandardCharsets.UTF_8); assertThat(serializedResult).contains(expected); } private static Stream<Arguments> marshallingValues() { return Stream.of(Arguments.of("String", TransferManagerJsonMarshaller.STRING, "String"), Arguments.of((short) 10, TransferManagerJsonMarshaller.SHORT, Short.toString((short) 10)), Arguments.of(100, TransferManagerJsonMarshaller.INTEGER, Integer.toString(100)), Arguments.of(100L, TransferManagerJsonMarshaller.LONG, Long.toString(100L)), Arguments.of(DateUtils.parseIso8601Date("2022-03-08T10:15:30Z"), TransferManagerJsonMarshaller.INSTANT, "1646734530.000"), Arguments.of(null, TransferManagerJsonMarshaller.NULL, "{}"), Arguments.of(12.34f, TransferManagerJsonMarshaller.FLOAT, Float.toString(12.34f)), Arguments.of(12.34d, TransferManagerJsonMarshaller.DOUBLE, Double.toString(12.34d)), Arguments.of(new BigDecimal(34), TransferManagerJsonMarshaller.BIG_DECIMAL, (new BigDecimal(34)).toString()), Arguments.of(true, TransferManagerJsonMarshaller.BOOLEAN, "true"), Arguments.of(SdkBytes.fromString("String", StandardCharsets.UTF_8), TransferManagerJsonMarshaller.SDK_BYTES, "U3RyaW5n"), Arguments.of(Arrays.asList(100, 45), TransferManagerJsonMarshaller.LIST, "[100,45]"), Arguments.of(Arrays.asList("100", "45"), TransferManagerJsonMarshaller.LIST, "[\"100\",\"45\"]"), Arguments.of(Collections.singletonMap("key", "value"), TransferManagerJsonMarshaller.MAP, "{\"key\":\"value\"}"), Arguments.of(new HashMap<String, Long>() {{ put("key1", 100L); put("key2", 200L); }}, TransferManagerJsonMarshaller.MAP, "{\"key1\":100,\"key2\":200}") ); } private static String serializedValue(String paramValue) { return String.format("{\"param\":%s}", paramValue); } }
3,996
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/samples/S3TransferManagerSamples.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.transfer.s3.samples; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.nio.file.Path; import java.nio.file.Paths; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedCopy; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload; import software.amazon.awssdk.transfer.s3.model.Copy; import software.amazon.awssdk.transfer.s3.model.CopyRequest; import software.amazon.awssdk.transfer.s3.model.DirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DirectoryUpload; import software.amazon.awssdk.transfer.s3.model.Download; import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.DownloadRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload; import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload; import software.amazon.awssdk.transfer.s3.model.Upload; import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest; import software.amazon.awssdk.transfer.s3.model.UploadRequest; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; /** * Contains code snippets that will be used in the Javadocs of {@link S3TransferManager} */ public class S3TransferManagerSamples { public void defaultClient() { // @start region=defaultTM S3TransferManager transferManager = S3TransferManager.create(); // @end region=defaultTM } public void customClient() { // @start region=customTM S3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_WEST_2) .targetThroughputInGbps(20.0) .minimumPartSizeInBytes(8 * MB) .build(); S3TransferManager transferManager = S3TransferManager.builder() .s3Client(s3AsyncClient) .build(); // @end region=customTM } public void downloadFile() { // @start region=downloadFile S3TransferManager transferManager = S3TransferManager.create(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(req -> req.bucket("bucket").key("key")) .destination(Paths.get("myFile.txt")) .addTransferListener(LoggingTransferListener.create()) .build(); FileDownload download = transferManager.downloadFile(downloadFileRequest); // Wait for the transfer to complete download.completionFuture().join(); // @end region=downloadFile } public void download() { // @start region=download S3TransferManager transferManager = S3TransferManager.create(); DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest = DownloadRequest.builder() .getObjectRequest(req -> req.bucket("bucket").key("key")) .responseTransformer(AsyncResponseTransformer.toBytes()) .build(); // Initiate the transfer Download<ResponseBytes<GetObjectResponse>> download = transferManager.download(downloadRequest); // Wait for the transfer to complete download.completionFuture().join(); // @end region=download } public void resumeDownloadFile() { // @start region=resumeDownloadFile S3TransferManager transferManager = S3TransferManager.create(); DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(req -> req.bucket("bucket").key("key")) .destination(Paths.get("myFile.txt")) .build(); // Initiate the transfer FileDownload download = transferManager.downloadFile(downloadFileRequest); // Pause the download ResumableFileDownload resumableFileDownload = download.pause(); // @link substring="pause" target="software.amazon.awssdk.transfer.s3.model.FileDownload#pause()" // Optionally, persist the download object Path path = Paths.get("resumableFileDownload.json"); resumableFileDownload.serializeToFile(path); // Retrieve the resumableFileDownload from the file resumableFileDownload = ResumableFileDownload.fromFile(path); // Resume the download FileDownload resumedDownload = transferManager.resumeDownloadFile(resumableFileDownload); // Wait for the transfer to complete resumedDownload.completionFuture().join(); // @end region=resumeDownloadFile } public void resumeUploadFile() { // @start region=resumeUploadFile S3TransferManager transferManager = S3TransferManager.create(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(req -> req.bucket("bucket").key("key")) .source(Paths.get("myFile.txt")) .build(); // Initiate the transfer FileUpload upload = transferManager.uploadFile(uploadFileRequest); // Pause the upload ResumableFileUpload resumableFileUpload = upload.pause(); // Optionally, persist the resumableFileUpload Path path = Paths.get("resumableFileUpload.json"); resumableFileUpload.serializeToFile(path); // Retrieve the resumableFileUpload from the file ResumableFileUpload persistedResumableFileUpload = ResumableFileUpload.fromFile(path); // Resume the upload FileUpload resumedUpload = transferManager.resumeUploadFile(persistedResumableFileUpload); // Wait for the transfer to complete resumedUpload.completionFuture().join(); // @end region=resumeUploadFile } public void uploadFile() { // @start region=uploadFile S3TransferManager transferManager = S3TransferManager.create(); UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(req -> req.bucket("bucket").key("key")) .addTransferListener(LoggingTransferListener.create()) .source(Paths.get("myFile.txt")) .build(); FileUpload upload = transferManager.uploadFile(uploadFileRequest); upload.completionFuture().join(); // @end region=uploadFile } public void upload() { // @start region=upload S3TransferManager transferManager = S3TransferManager.create(); UploadRequest uploadRequest = UploadRequest.builder() .requestBody(AsyncRequestBody.fromString("Hello world")) .putObjectRequest(req -> req.bucket("bucket").key("key")) .build(); Upload upload = transferManager.upload(uploadRequest); // Wait for the transfer to complete upload.completionFuture().join(); // @end region=upload } public void uploadDirectory() { // @start region=uploadDirectory S3TransferManager transferManager = S3TransferManager.create(); DirectoryUpload directoryUpload = transferManager.uploadDirectory(UploadDirectoryRequest.builder() .source(Paths.get("source/directory")) .bucket("bucket") .s3Prefix("prefix") .build()); // Wait for the transfer to complete CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join(); // Print out the failed uploads completedDirectoryUpload.failedTransfers().forEach(System.out::println); // @end region=uploadDirectory } public void downloadDirectory() { // @start region=downloadDirectory S3TransferManager transferManager = S3TransferManager.create(); DirectoryDownload directoryDownload = transferManager.downloadDirectory(DownloadDirectoryRequest.builder() .destination(Paths.get("destination/directory")) .bucket("bucket") .listObjectsV2RequestTransformer(l -> l.prefix("prefix")) .build()); // Wait for the transfer to complete CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join(); // Print out the failed downloads completedDirectoryDownload.failedTransfers().forEach(System.out::println); // @end region=downloadDirectory } public void copy() { // @start region=copy S3TransferManager transferManager = S3TransferManager.create(); CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder() .sourceBucket("source_bucket") .sourceKey("source_key") .destinationBucket("dest_bucket") .destinationKey("dest_key") .build(); CopyRequest copyRequest = CopyRequest.builder() .copyObjectRequest(copyObjectRequest) .build(); Copy copy = transferManager.copy(copyRequest); // Wait for the transfer to complete CompletedCopy completedCopy = copy.completionFuture().join(); // @end region=copy } }
3,997
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedFileDownloadTest.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.transfer.s3.model; import static org.assertj.core.api.Assertions.assertThatThrownBy; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; public class CompletedFileDownloadTest { @Test public void responseNull_shouldThrowException() { assertThatThrownBy(() -> CompletedFileDownload.builder().build()).isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test public void equalsHashcode() { EqualsVerifier.forClass(CompletedFileDownload.class) .withNonnullFields("response") .verify(); } }
3,998
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedFileUploadTest.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.transfer.s3.model; import static org.assertj.core.api.Assertions.assertThatThrownBy; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; public class CompletedFileUploadTest { @Test public void responseNull_shouldThrowException() { assertThatThrownBy(() -> CompletedFileUpload.builder().build()).isInstanceOf(NullPointerException.class) .hasMessageContaining("must not be null"); } @Test public void equalsHashcode() { EqualsVerifier.forClass(CompletedFileUpload.class) .withNonnullFields("response") .verify(); } }
3,999