index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/IndexExpression.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.jmespath.component; import java.util.Optional; import software.amazon.awssdk.utils.Validate; /** * An index expression is used to access elements in a list. Indexing is 0 based, the index of 0 refers to the first element * of the list. A negative number is a valid index. A negative number indicates that indexing is relative to the end of the * list. * * https://jmespath.org/specification.html#index-expressions */ public class IndexExpression { private final Expression expression; private final BracketSpecifier bracketSpecifier; private IndexExpression(Expression expression, BracketSpecifier bracketSpecifier) { this.expression = expression; this.bracketSpecifier = bracketSpecifier; } public static IndexExpression indexExpression(Expression expression, BracketSpecifier bracketSpecifier) { Validate.notNull(bracketSpecifier, "bracketSpecifier"); return new IndexExpression(expression, bracketSpecifier); } public Optional<Expression> expression() { return Optional.ofNullable(expression); } public BracketSpecifier bracketSpecifier() { return bracketSpecifier; } }
3,600
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/Literal.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.jmespath.component; import com.fasterxml.jackson.jr.stree.JrsValue; /** * A literal JSON value embedded in a JMESPath expression. * * https://jmespath.org/specification.html#literal-expressions */ public class Literal { private final JrsValue jsonValue; public Literal(JrsValue jsonValue) { this.jsonValue = jsonValue; } public JrsValue jsonValue() { return jsonValue; } }
3,601
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/FunctionArg.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.jmespath.component; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathVisitor; import software.amazon.awssdk.utils.Validate; /** * An argument to a {@link FunctionExpression}. Either a {@link Expression} that is evaluated and passed to the function or a * {@link ExpressionType} that is passed to the function as-is and is evaluated by the function. */ public class FunctionArg { private Expression expression; private ExpressionType expressionType; private FunctionArg() { } public static FunctionArg expression(Expression expression) { Validate.notNull(expression, "expression"); FunctionArg result = new FunctionArg(); result.expression = expression; return result; } public static FunctionArg expressionType(ExpressionType expressionType) { Validate.notNull(expressionType, "expressionType"); FunctionArg result = new FunctionArg(); result.expressionType = expressionType; return result; } public boolean isExpression() { return expression != null; } public boolean isExpressionType() { return expressionType != null; } public Expression asExpression() { Validate.validState(isExpression(), "Not a Expression"); return expression; } public ExpressionType asExpressionType() { Validate.validState(isExpressionType(), "Not a ExpressionType"); return expressionType; } public void visit(JmesPathVisitor visitor) { if (isExpression()) { visitor.visitExpression(asExpression()); } else if (isExpressionType()) { visitor.visitExpressionType(asExpressionType()); } else { throw new IllegalStateException(); } } }
3,602
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/AndExpression.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.jmespath.component; /** * An and expression will evaluate to either the left expression or the right expression. If the expression on the left hand side * is a truth-like value, then the value on the right hand side is returned. Otherwise the result of the expression on the left * hand side is returned. * * Examples: * <ul> * <li>True && False</li> * <li>Number && EmptyList</li> * <li>a == `1` && b == `2`</li> * </ul> * * https://jmespath.org/specification.html#and-expressions */ public class AndExpression { private final Expression leftExpression; private final Expression rightExpression; public AndExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; this.rightExpression = rightExpression; } public Expression leftExpression() { return leftExpression; } public Expression rightExpression() { return rightExpression; } }
3,603
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/SubExpressionRight.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.jmespath.component; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathVisitor; import software.amazon.awssdk.utils.Validate; /** * The right side of a {@link SubExpression}. */ public class SubExpressionRight { private String identifier; private MultiSelectList multiSelectList; private MultiSelectHash multiSelectHash; private FunctionExpression functionExpression; private WildcardExpression wildcardExpression; public static SubExpressionRight identifier(String identifier) { Validate.notNull(identifier, "identifier"); SubExpressionRight result = new SubExpressionRight(); result.identifier = identifier; return result; } public static SubExpressionRight multiSelectList(MultiSelectList multiSelectList) { Validate.notNull(multiSelectList, "multiSelectList"); SubExpressionRight result = new SubExpressionRight(); result.multiSelectList = multiSelectList; return result; } public static SubExpressionRight multiSelectHash(MultiSelectHash multiSelectHash) { Validate.notNull(multiSelectHash, "multiSelectHash"); SubExpressionRight result = new SubExpressionRight(); result.multiSelectHash = multiSelectHash; return result; } public static SubExpressionRight functionExpression(FunctionExpression functionExpression) { Validate.notNull(functionExpression, "functionExpression"); SubExpressionRight result = new SubExpressionRight(); result.functionExpression = functionExpression; return result; } public static SubExpressionRight wildcardExpression(WildcardExpression wildcardExpression) { Validate.notNull(wildcardExpression, "wildcardExpression"); SubExpressionRight result = new SubExpressionRight(); result.wildcardExpression = wildcardExpression; return result; } public boolean isIdentifier() { return identifier != null; } public boolean isMultiSelectList() { return multiSelectList != null; } public boolean isMultiSelectHash() { return multiSelectHash != null; } public boolean isFunctionExpression() { return functionExpression != null; } public boolean isWildcardExpression() { return wildcardExpression != null; } public String asIdentifier() { Validate.validState(isIdentifier(), "Not an Identifier"); return identifier; } public MultiSelectList asMultiSelectList() { Validate.validState(isMultiSelectList(), "Not a MultiSelectList"); return multiSelectList; } public MultiSelectHash asMultiSelectHash() { Validate.validState(isMultiSelectHash(), "Not a MultiSelectHash"); return multiSelectHash; } public FunctionExpression asFunctionExpression() { Validate.validState(isFunctionExpression(), "Not a FunctionExpression"); return functionExpression; } public WildcardExpression asWildcardExpression() { Validate.validState(isWildcardExpression(), "Not a WildcardExpression"); return wildcardExpression; } public void visit(JmesPathVisitor visitor) { if (isIdentifier()) { visitor.visitIdentifier(asIdentifier()); } else if (isMultiSelectList()) { visitor.visitMultiSelectList(asMultiSelectList()); } else if (isMultiSelectHash()) { visitor.visitMultiSelectHash(asMultiSelectHash()); } else if (isFunctionExpression()) { visitor.visitFunctionExpression(asFunctionExpression()); } else if (isWildcardExpression()) { visitor.visitWildcardExpression(asWildcardExpression()); } else { throw new IllegalStateException(); } } }
3,604
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/BracketSpecifierWithContents.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.jmespath.component; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathVisitor; import software.amazon.awssdk.utils.Validate; /** * A {@link BracketSpecifier} with some kind of content. Either: * <ul> * <li>A number, as in [1]</li> * <li>A star expression, as in [*]</li> * <li>A slice expression, as in [1:2:3]</li> * </ul> */ public class BracketSpecifierWithContents { private Integer number; private WildcardExpression wildcardExpression; private SliceExpression sliceExpression; private BracketSpecifierWithContents() { } public static BracketSpecifierWithContents number(Integer number) { Validate.notNull(number, "number"); BracketSpecifierWithContents result = new BracketSpecifierWithContents(); result.number = number; return result; } public static BracketSpecifierWithContents wildcardExpression(WildcardExpression wildcardExpression) { Validate.notNull(wildcardExpression, "wildcardExpression"); BracketSpecifierWithContents result = new BracketSpecifierWithContents(); result.wildcardExpression = wildcardExpression; return result; } public static BracketSpecifierWithContents sliceExpression(SliceExpression sliceExpression) { Validate.notNull(sliceExpression, "sliceExpression"); BracketSpecifierWithContents result = new BracketSpecifierWithContents(); result.sliceExpression = sliceExpression; return result; } public boolean isNumber() { return number != null; } public boolean isWildcardExpression() { return wildcardExpression != null; } public boolean isSliceExpression() { return sliceExpression != null; } public int asNumber() { Validate.validState(isNumber(), "Not a Number"); return number; } public WildcardExpression asWildcardExpression() { Validate.validState(isWildcardExpression(), "Not a WildcardExpression"); return wildcardExpression; } public SliceExpression asSliceExpression() { Validate.validState(isSliceExpression(), "Not a SliceExpression"); return sliceExpression; } public void visit(JmesPathVisitor visitor) { if (isNumber()) { visitor.visitNumber(asNumber()); } else if (isWildcardExpression()) { visitor.visitWildcardExpression(asWildcardExpression()); } else if (isSliceExpression()) { visitor.visitSliceExpression(asSliceExpression()); } else { throw new IllegalStateException(); } } }
3,605
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/PipeExpression.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.jmespath.component; /** * A pipe expression combines two expressions, separated by the | character. It is similar to a sub-expression with two * important distinctions: * * <ol> * <li>Any expression can be used on the right hand side. A sub-expression restricts the type of expression that can be used * on the right hand side.</li> * <li>A pipe-expression stops projections on the left hand side from propagating to the right hand side. If the left * expression creates a projection, it does not apply to the right hand side.</li> * </ol> * * https://jmespath.org/specification.html#pipe-expressions */ public class PipeExpression { private final Expression leftExpression; private final Expression rightExpression; public PipeExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; this.rightExpression = rightExpression; } public Expression leftExpression() { return leftExpression; } public Expression rightExpression() { return rightExpression; } }
3,606
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/Comparator.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.jmespath.component; /** * A comparator within a {@link ComparatorExpression}. */ public enum Comparator { LESS_THAN_OR_EQUAL("<="), EQUAL("=="), GREATER_THAN_OR_EQUAL(">="), NOT_EQUAL("!="), LESS_THAN("<"), GREATER_THAN(">"); private final String tokenSymbol; Comparator(String tokenSymbol) { this.tokenSymbol = tokenSymbol; } public String tokenSymbol() { return tokenSymbol; } }
3,607
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/SliceExpression.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.jmespath.component; import java.util.OptionalInt; /** * A slice expression allows you to select a contiguous subset of an array. A slice has a start, stop, and step value. The * general form of a slice is [start:stop:step], but each component is optional and can be omitted. * * https://jmespath.org/specification.html#slices */ public class SliceExpression { private final Integer start; private final Integer stop; private final Integer step; public SliceExpression(Integer start, Integer stop, Integer step) { this.start = start; this.stop = stop; this.step = step; } public OptionalInt start() { return toOptional(start); } public OptionalInt stop() { return toOptional(stop); } public OptionalInt step() { return toOptional(step); } private OptionalInt toOptional(Integer n) { return n == null ? OptionalInt.empty() : OptionalInt.of(n); } }
3,608
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/component/ExpressionType.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.jmespath.component; /** * An expression type is an expression prefixed by "&". These are used within {@link FunctionExpression}s as a lambda to be * invoked by the JMESPath function where they are needed. * * For an example in practice, see the sort_by function: https://jmespath.org/specification.html#func-sort-by */ public class ExpressionType { private final Expression expression; public ExpressionType(Expression expression) { this.expression = expression; } public Expression expression() { return expression; } }
3,609
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser/Parser.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.jmespath.parser; /** * A JMESPath parser, for generating a {@link ParseResult} from a string between two provided bounds. */ @FunctionalInterface public interface Parser<T> { /** * Parse a JMESPath string between the start position (inclusive) and end position (exclusive). */ ParseResult<T> parse(int startPosition, int endPosition); }
3,610
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser/JmesPathParser.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.jmespath.parser; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.function.BiFunction; import software.amazon.awssdk.codegen.internal.Jackson; import software.amazon.awssdk.codegen.jmespath.component.AndExpression; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifier; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithQuestionMark; import software.amazon.awssdk.codegen.jmespath.component.Comparator; import software.amazon.awssdk.codegen.jmespath.component.ComparatorExpression; import software.amazon.awssdk.codegen.jmespath.component.CurrentNode; import software.amazon.awssdk.codegen.jmespath.component.Expression; import software.amazon.awssdk.codegen.jmespath.component.ExpressionType; import software.amazon.awssdk.codegen.jmespath.component.FunctionArg; import software.amazon.awssdk.codegen.jmespath.component.FunctionExpression; import software.amazon.awssdk.codegen.jmespath.component.IndexExpression; import software.amazon.awssdk.codegen.jmespath.component.KeyValueExpression; import software.amazon.awssdk.codegen.jmespath.component.Literal; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectHash; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectList; import software.amazon.awssdk.codegen.jmespath.component.NotExpression; import software.amazon.awssdk.codegen.jmespath.component.OrExpression; import software.amazon.awssdk.codegen.jmespath.component.ParenExpression; import software.amazon.awssdk.codegen.jmespath.component.PipeExpression; import software.amazon.awssdk.codegen.jmespath.component.SliceExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpressionRight; import software.amazon.awssdk.codegen.jmespath.component.WildcardExpression; import software.amazon.awssdk.codegen.jmespath.parser.util.CompositeParser; import software.amazon.awssdk.utils.Logger; /** * Parses a JMESPath expression string into an {@link Expression}. * * This implements the grammar described here: https://jmespath.org/specification.html#grammar */ public class JmesPathParser { private static final Logger log = Logger.loggerFor(JmesPathParser.class); private final String input; private JmesPathParser(String input) { this.input = input; } /** * Parses a JMESPath expression string into a {@link Expression}. */ public static Expression parse(String jmesPathString) { return new JmesPathParser(jmesPathString).parse(); } private Expression parse() { ParseResult<Expression> expression = parseExpression(0, input.length()); if (!expression.hasResult()) { throw new IllegalArgumentException("Failed to parse expression."); } return expression.result(); } /** * expression = sub-expression / index-expression / comparator-expression * expression =/ or-expression / identifier * expression =/ and-expression / not-expression / paren-expression * expression =/ "*" / multi-select-list / multi-select-hash / literal * expression =/ function-expression / pipe-expression / raw-string * expression =/ current-node */ private ParseResult<Expression> parseExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (startPosition < 0 || endPosition > input.length() + 1) { return ParseResult.error(); } return CompositeParser.firstTry(this::parseSubExpression, Expression::subExpression) .thenTry(this::parseIndexExpression, Expression::indexExpression) .thenTry(this::parseNotExpression, Expression::notExpression) .thenTry(this::parseAndExpression, Expression::andExpression) .thenTry(this::parseOrExpression, Expression::orExpression) .thenTry(this::parseComparatorExpression, Expression::comparatorExpression) .thenTry(this::parsePipeExpression, Expression::pipeExpression) .thenTry(this::parseIdentifier, Expression::identifier) .thenTry(this::parseParenExpression, Expression::parenExpression) .thenTry(this::parseWildcardExpression, Expression::wildcardExpression) .thenTry(this::parseMultiSelectList, Expression::multiSelectList) .thenTry(this::parseMultiSelectHash, Expression::multiSelectHash) .thenTry(this::parseLiteral, Expression::literal) .thenTry(this::parseFunctionExpression, Expression::functionExpression) .thenTry(this::parseRawString, Expression::rawString) .thenTry(this::parseCurrentNode, Expression::currentNode) .parse(startPosition, endPosition); } /** * sub-expression = expression "." ( identifier / * multi-select-list / * multi-select-hash / * function-expression / * "*" ) */ private ParseResult<SubExpression> parseSubExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); List<Integer> dotPositions = findCharacters(startPosition + 1, endPosition - 1, "."); for (Integer dotPosition : dotPositions) { ParseResult<Expression> leftSide = parseExpression(startPosition, dotPosition); if (!leftSide.hasResult()) { continue; } ParseResult<SubExpressionRight> rightSide = CompositeParser.firstTry(this::parseIdentifier, SubExpressionRight::identifier) .thenTry(this::parseMultiSelectList, SubExpressionRight::multiSelectList) .thenTry(this::parseMultiSelectHash, SubExpressionRight::multiSelectHash) .thenTry(this::parseFunctionExpression, SubExpressionRight::functionExpression) .thenTry(this::parseWildcardExpression, SubExpressionRight::wildcardExpression) .parse(dotPosition + 1, endPosition); if (!rightSide.hasResult()) { continue; } return ParseResult.success(new SubExpression(leftSide.result(), rightSide.result())); } logError("sub-expression", "Invalid sub-expression", startPosition); return ParseResult.error(); } /** * pipe-expression = expression "|" expression */ private ParseResult<PipeExpression> parsePipeExpression(int startPosition, int endPosition) { return parseBinaryExpression(startPosition, endPosition, "|", PipeExpression::new); } /** * or-expression = expression "||" expression */ private ParseResult<OrExpression> parseOrExpression(int startPosition, int endPosition) { return parseBinaryExpression(startPosition, endPosition, "||", OrExpression::new); } /** * and-expression = expression "&&" expression */ private ParseResult<AndExpression> parseAndExpression(int startPosition, int endPosition) { return parseBinaryExpression(startPosition, endPosition, "&&", AndExpression::new); } private <T> ParseResult<T> parseBinaryExpression(int startPosition, int endPosition, String delimiter, BiFunction<Expression, Expression, T> constructor) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); List<Integer> delimiterPositions = findCharacters(startPosition + 1, endPosition - 1, delimiter); for (Integer delimiterPosition : delimiterPositions) { ParseResult<Expression> leftSide = parseExpression(startPosition, delimiterPosition); if (!leftSide.hasResult()) { continue; } ParseResult<Expression> rightSide = parseExpression(delimiterPosition + delimiter.length(), endPosition); if (!rightSide.hasResult()) { continue; } return ParseResult.success(constructor.apply(leftSide.result(), rightSide.result())); } logError("binary-expression", "Invalid binary-expression", startPosition); return ParseResult.error(); } /** * not-expression = "!" expression */ private ParseResult<NotExpression> parseNotExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsWith(startPosition, '!')) { logError("not-expression", "Expected '!'", startPosition); return ParseResult.error(); } return parseExpression(startPosition + 1, endPosition).mapResult(NotExpression::new); } /** * paren-expression = "(" expression ")" */ private ParseResult<ParenExpression> parseParenExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsAndEndsWith(startPosition, endPosition, '(', ')')) { logError("paren-expression", "Expected '(' and ')'", startPosition); return ParseResult.error(); } return parseExpression(startPosition + 1, endPosition - 1).mapResult(ParenExpression::new); } /** * index-expression = expression bracket-specifier / bracket-specifier */ private ParseResult<IndexExpression> parseIndexExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); return CompositeParser.firstTry(this::parseIndexExpressionWithLhsExpression) .thenTry(this::parseBracketSpecifier, b -> IndexExpression.indexExpression(null, b)) .parse(startPosition, endPosition); } /** * expression bracket-specifier */ private ParseResult<IndexExpression> parseIndexExpressionWithLhsExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); List<Integer> bracketPositions = findCharacters(startPosition + 1, endPosition - 1, "["); for (Integer bracketPosition : bracketPositions) { ParseResult<Expression> leftSide = parseExpression(startPosition, bracketPosition); if (!leftSide.hasResult()) { continue; } ParseResult<BracketSpecifier> rightSide = parseBracketSpecifier(bracketPosition, endPosition); if (!rightSide.hasResult()) { continue; } return ParseResult.success(IndexExpression.indexExpression(leftSide.result(), rightSide.result())); } logError("index-expression with lhs-expression", "Invalid index-expression with lhs-expression", startPosition); return ParseResult.error(); } /** * multi-select-list = "[" ( expression *( "," expression ) ) "]" */ private ParseResult<MultiSelectList> parseMultiSelectList(int startPosition, int endPosition) { return parseMultiSelect(startPosition, endPosition, '[', ']', this::parseExpression) .mapResult(MultiSelectList::new); } /** * multi-select-hash = "{" ( keyval-expr *( "," keyval-expr ) ) "}" */ private ParseResult<MultiSelectHash> parseMultiSelectHash(int startPosition, int endPosition) { return parseMultiSelect(startPosition, endPosition, '{', '}', this::parseKeyValueExpression) .mapResult(MultiSelectHash::new); } /** * Parses "startDelimiter" ( entryParserType *( "," entryParserType ) ) "endDelimiter" * <p> * Used by {@link #parseMultiSelectHash}, {@link #parseMultiSelectList}. */ private <T> ParseResult<List<T>> parseMultiSelect(int startPosition, int endPosition, char startDelimiter, char endDelimiter, Parser<T> entryParser) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsAndEndsWith(startPosition, endPosition, startDelimiter, endDelimiter)) { logError("multi-select", "Expected '" + startDelimiter + "' and '" + endDelimiter + "'", startPosition); return ParseResult.error(); } List<Integer> commaPositions = findCharacters(startPosition + 1, endPosition - 1, ","); if (commaPositions.isEmpty()) { return entryParser.parse(startPosition + 1, endPosition - 1).mapResult(Collections::singletonList); } List<T> results = new ArrayList<>(); // Find first valid entries before a comma int startOfSecondEntry = -1; for (Integer comma : commaPositions) { ParseResult<T> result = entryParser.parse(startPosition + 1, comma); if (!result.hasResult()) { continue; } results.add(result.result()); startOfSecondEntry = comma + 1; } if (results.size() == 0) { logError("multi-select", "Invalid value", startPosition + 1); return ParseResult.error(); } if (results.size() > 1) { logError("multi-select", "Ambiguous separation", startPosition); return ParseResult.error(); } // Find any subsequent entries int startPositionAfterComma = startOfSecondEntry; for (Integer commaPosition : commaPositions) { if (startPositionAfterComma > commaPosition) { continue; } ParseResult<T> entry = entryParser.parse(startPositionAfterComma, commaPosition); if (!entry.hasResult()) { continue; } results.add(entry.result()); startPositionAfterComma = commaPosition + 1; } ParseResult<T> entry = entryParser.parse(startPositionAfterComma, endPosition - 1); if (!entry.hasResult()) { logError("multi-select", "Ambiguous separation", startPosition); return ParseResult.error(); } results.add(entry.result()); return ParseResult.success(results); } /** * keyval-expr = identifier ":" expression */ private ParseResult<KeyValueExpression> parseKeyValueExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); List<Integer> delimiterPositions = findCharacters(startPosition + 1, endPosition - 1, ":"); for (Integer delimiterPosition : delimiterPositions) { ParseResult<String> identifier = parseIdentifier(startPosition, delimiterPosition); if (!identifier.hasResult()) { continue; } ParseResult<Expression> expression = parseExpression(delimiterPosition + 1, endPosition); if (!expression.hasResult()) { continue; } return ParseResult.success(new KeyValueExpression(identifier.result(), expression.result())); } logError("keyval-expr", "Invalid keyval-expr", startPosition); return ParseResult.error(); } /** * bracket-specifier = "[" (number / "*" / slice-expression) "]" / "[]" * bracket-specifier =/ "[?" expression "]" */ private ParseResult<BracketSpecifier> parseBracketSpecifier(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsAndEndsWith(startPosition, endPosition, '[', ']')) { logError("bracket-specifier", "Expecting '[' and ']'", startPosition); return ParseResult.error(); } // "[]" if (charsInRange(startPosition, endPosition) == 2) { return ParseResult.success(BracketSpecifier.withoutContents()); } // "[?" expression "]" if (input.charAt(startPosition + 1) == '?') { return parseExpression(startPosition + 2, endPosition - 1) .mapResult(e -> BracketSpecifier.withQuestionMark(new BracketSpecifierWithQuestionMark(e))); } // "[" (number / "*" / slice-expression) "]" return CompositeParser.firstTry(this::parseNumber, BracketSpecifier::withNumberContents) .thenTry(this::parseWildcardExpression, BracketSpecifier::withWildcardExpressionContents) .thenTry(this::parseSliceExpression, BracketSpecifier::withSliceExpressionContents) .parse(startPosition + 1, endPosition - 1); } /** * comparator-expression = expression comparator expression */ private ParseResult<ComparatorExpression> parseComparatorExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); for (Comparator comparator : Comparator.values()) { List<Integer> comparatorPositions = findCharacters(startPosition, endPosition, comparator.tokenSymbol()); for (Integer comparatorPosition : comparatorPositions) { ParseResult<Expression> lhsExpression = parseExpression(startPosition, comparatorPosition); if (!lhsExpression.hasResult()) { continue; } ParseResult<Expression> rhsExpression = parseExpression(comparatorPosition + comparator.tokenSymbol().length(), endPosition); if (!rhsExpression.hasResult()) { continue; } return ParseResult.success(new ComparatorExpression(lhsExpression.result(), comparator, rhsExpression.result())); } } logError("comparator-expression", "Invalid comparator expression", startPosition); return ParseResult.error(); } /** * slice-expression = [number] ":" [number] [ ":" [number] ] */ private ParseResult<SliceExpression> parseSliceExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); // Find the first colon int firstColonIndex = input.indexOf(':', startPosition); if (firstColonIndex < 0 || firstColonIndex >= endPosition) { logError("slice-expression", "Expected slice expression", startPosition); return ParseResult.error(); } // Find the second colon (if it exists) int maybeSecondColonIndex = input.indexOf(':', firstColonIndex + 1); OptionalInt secondColonIndex = maybeSecondColonIndex < 0 || maybeSecondColonIndex >= endPosition ? OptionalInt.empty() : OptionalInt.of(maybeSecondColonIndex); // Find the first number bounds (if it exists) int firstNumberStart = startPosition; int firstNumberEnd = firstColonIndex; // Find the second number bounds (if it exists) int secondNumberStart = firstColonIndex + 1; int secondNumberEnd = secondColonIndex.orElse(endPosition); // Find the third number bounds (if it exists) int thirdNumberStart = secondColonIndex.orElse(endPosition) + 1; int thirdNumberEnd = endPosition; // Parse the first number (if it exists) Optional<Integer> firstNumber = Optional.empty(); if (firstNumberStart < firstNumberEnd) { ParseResult<Integer> firstNumberParse = parseNumber(firstNumberStart, firstNumberEnd); if (!firstNumberParse.hasResult()) { return ParseResult.error(); } firstNumber = Optional.of(firstNumberParse.result()); } // Parse the second number (if it exists) Optional<Integer> secondNumber = Optional.empty(); if (secondNumberStart < secondNumberEnd) { ParseResult<Integer> secondNumberParse = parseNumber(secondNumberStart, secondNumberEnd); if (!secondNumberParse.hasResult()) { return ParseResult.error(); } secondNumber = Optional.of(secondNumberParse.result()); } // Parse the third number (if it exists) Optional<Integer> thirdNumber = Optional.empty(); if (thirdNumberStart < thirdNumberEnd) { ParseResult<Integer> thirdNumberParse = parseNumber(thirdNumberStart, thirdNumberEnd); if (!thirdNumberParse.hasResult()) { return ParseResult.error(); } thirdNumber = Optional.of(thirdNumberParse.result()); } return ParseResult.success(new SliceExpression(firstNumber.orElse(null), secondNumber.orElse(null), thirdNumber.orElse(null))); } /** * function-expression = unquoted-string ( no-args / one-or-more-args ) */ private ParseResult<FunctionExpression> parseFunctionExpression(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); int paramIndex = input.indexOf('(', startPosition); if (paramIndex <= 0) { logError("function-expression", "Expected function", startPosition); return ParseResult.error(); } ParseResult<String> functionNameParse = parseUnquotedString(startPosition, paramIndex); if (!functionNameParse.hasResult()) { logError("function-expression", "Expected valid function name", startPosition); return ParseResult.error(); } return CompositeParser.firstTry(this::parseNoArgs) .thenTry(this::parseOneOrMoreArgs) .parse(paramIndex, endPosition) .mapResult(args -> new FunctionExpression(functionNameParse.result(), args)); } /** * no-args = "(" ")" */ private ParseResult<List<FunctionArg>> parseNoArgs(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsWith(startPosition, '(')) { logError("no-args", "Expected '('", startPosition); return ParseResult.error(); } int closePosition = trimLeftWhitespace(startPosition + 1, endPosition); if (input.charAt(closePosition) != ')') { logError("no-args", "Expected ')'", closePosition); return ParseResult.error(); } if (closePosition + 1 != endPosition) { logError("no-args", "Unexpected character", closePosition + 1); return ParseResult.error(); } return ParseResult.success(Collections.emptyList()); } /** * one-or-more-args = "(" ( function-arg *( "," function-arg ) ) ")" */ private ParseResult<List<FunctionArg>> parseOneOrMoreArgs(int startPosition, int endPosition) { return parseMultiSelect(startPosition, endPosition, '(', ')', this::parseFunctionArg); } /** * function-arg = expression / expression-type */ private ParseResult<FunctionArg> parseFunctionArg(int startPosition, int endPosition) { return CompositeParser.firstTry(this::parseExpression, FunctionArg::expression) .thenTry(this::parseExpressionType, FunctionArg::expressionType) .parse(startPosition, endPosition); } /** * current-node = "@" */ private ParseResult<CurrentNode> parseCurrentNode(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); return parseExpectedToken("current-node", startPosition, endPosition, '@').mapResult(x -> new CurrentNode()); } /** * expression-type = "&" expression */ private ParseResult<ExpressionType> parseExpressionType(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsWith(startPosition, '&')) { logError("expression-type", "Expected '&'", startPosition); return ParseResult.error(); } return parseExpression(startPosition + 1, endPosition).mapResult(ExpressionType::new); } /** * raw-string = "'" *raw-string-char "'" */ private ParseResult<String> parseRawString(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (charsInRange(startPosition, endPosition) < 2) { logError("raw-string", "Invalid length", startPosition); return ParseResult.error(); } if (!startsAndEndsWith(startPosition, endPosition, '\'', '\'')) { logError("raw-string", "Expected opening and closing \"'\"", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) == 2) { return ParseResult.success(""); } return parseRawStringChars(startPosition + 1, endPosition - 1); } /** * raw-string-char = (%x20-26 / %x28-5B / %x5D-10FFFF) / preserved-escape / raw-string-escape */ private ParseResult<String> parseRawStringChars(int startPosition, int endPosition) { StringBuilder result = new StringBuilder(); for (int i = startPosition; i < endPosition; i++) { ParseResult<String> rawStringChar = parseLegalRawStringChar(i, i + 1); if (rawStringChar.hasResult()) { result.append(rawStringChar.result()); continue; } ParseResult<String> preservedEscape = parsePreservedEscape(i, i + 2); if (preservedEscape.hasResult()) { result.append(preservedEscape.result()); ++i; continue; } ParseResult<String> rawStringEscape = parseRawStringEscape(i, i + 2); if (rawStringEscape.hasResult()) { result.append(rawStringEscape.result()); ++i; continue; } logError("raw-string", "Unexpected character", i); return ParseResult.error(); } return ParseResult.success(result.toString()); } /** * %x20-26 / %x28-5B / %x5D-10FFFF */ private ParseResult<String> parseLegalRawStringChar(int startPosition, int endPosition) { if (charsInRange(startPosition, endPosition) != 1) { logError("raw-string-chars", "Invalid bounds", startPosition); return ParseResult.error(); } if (!isLegalRawStringChar(input.charAt(startPosition))) { logError("raw-string-chars", "Invalid character in sequence", startPosition); return ParseResult.error(); } return ParseResult.success(input.substring(startPosition, endPosition)); } private boolean isLegalRawStringChar(char c) { return (c >= 0x20 && c <= 0x26) || (c >= 0x28 && c <= 0x5B) || (c >= 0x5D); } /** * preserved-escape = escape (%x20-26 / %28-5B / %x5D-10FFFF) */ private ParseResult<String> parsePreservedEscape(int startPosition, int endPosition) { if (endPosition > input.length()) { logError("preserved-escape", "Invalid end position", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) != 2) { logError("preserved-escape", "Invalid length", startPosition); return ParseResult.error(); } if (!startsWith(startPosition, '\\')) { logError("preserved-escape", "Expected \\", startPosition); return ParseResult.error(); } return parseLegalRawStringChar(startPosition + 1, endPosition).mapResult(v -> "\\" + v); } /** * raw-string-escape = escape ("'" / escape) */ private ParseResult<String> parseRawStringEscape(int startPosition, int endPosition) { if (endPosition > input.length()) { logError("preserved-escape", "Invalid end position", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) != 2) { logError("raw-string-escape", "Invalid length", startPosition); return ParseResult.error(); } if (!startsWith(startPosition, '\\')) { logError("raw-string-escape", "Expected '\\'", startPosition); return ParseResult.error(); } if (input.charAt(startPosition + 1) != '\'' && input.charAt(startPosition + 1) != '\\') { logError("raw-string-escape", "Expected \"'\" or \"\\\"", startPosition); return ParseResult.error(); } return ParseResult.success(input.substring(startPosition, endPosition)); } /** * literal = "`" json-value "`" */ private ParseResult<Literal> parseLiteral(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (charsInRange(startPosition, endPosition) < 2) { logError("literal", "Invalid bounds", startPosition); return ParseResult.error(); } if (!startsAndEndsWith(startPosition, endPosition, '`', '`')) { logError("literal", "Expected opening and closing '`'", startPosition); return ParseResult.error(); } StringBuilder jsonString = new StringBuilder(); for (int i = startPosition + 1; i < endPosition - 1; i++) { char character = input.charAt(i); if (character == '`') { int lastChar = i - 1; if (lastChar <= 0) { logError("literal", "Unexpected '`'", startPosition); return ParseResult.error(); } int escapeCount = 0; for (int j = i - 1; j >= startPosition; j--) { if (input.charAt(j) == '\\') { ++escapeCount; } else { break; } } if (escapeCount % 2 == 0) { logError("literal", "Unescaped '`'", startPosition); return ParseResult.error(); } jsonString.setLength(jsonString.length() - 1); // Remove escape. jsonString.append('`'); } else { jsonString.append(character); } } try { return ParseResult.success(new Literal(Jackson.readJrsValue(jsonString.toString()))); } catch (IOException e) { logError("literal", "Invalid JSON: " + e.getMessage(), startPosition); return ParseResult.error(); } } /** * number = ["-"]1*digit * digit = %x30-39 */ private ParseResult<Integer> parseNumber(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (startsWith(startPosition, '-')) { return parseNonNegativeNumber(startPosition + 1, endPosition).mapResult(i -> -i); } return parseNonNegativeNumber(startPosition, endPosition); } private ParseResult<Integer> parseNonNegativeNumber(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (charsInRange(startPosition, endPosition) < 1) { logError("number", "Expected number", startPosition); return ParseResult.error(); } try { return ParseResult.success(Integer.parseInt(input.substring(startPosition, endPosition))); } catch (NumberFormatException e) { logError("number", "Expected number", startPosition); return ParseResult.error(); } } /** * identifier = unquoted-string / quoted-string */ private ParseResult<String> parseIdentifier(int startPosition, int endPosition) { return CompositeParser.firstTry(this::parseUnquotedString) .thenTry(this::parseQuotedString) .parse(startPosition, endPosition); } /** * unquoted-string = (%x41-5A / %x61-7A / %x5F) *( ; A-Za-z_ * %x30-39 / ; 0-9 * %x41-5A / ; A-Z * %x5F / ; _ * %x61-7A) ; a-z */ private ParseResult<String> parseUnquotedString(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (charsInRange(startPosition, endPosition) < 1) { logError("unquoted-string", "Invalid unquoted-string", startPosition); return ParseResult.error(); } char firstToken = input.charAt(startPosition); if (!Character.isLetter(firstToken) && firstToken != '_') { logError("unquoted-string", "Unescaped strings must start with [A-Za-z_]", startPosition); return ParseResult.error(); } for (int i = startPosition; i < endPosition; i++) { char c = input.charAt(i); if (!Character.isLetterOrDigit(c) && c != '_') { logError("unquoted-string", "Invalid character in unescaped-string", i); return ParseResult.error(); } } return ParseResult.success(input.substring(startPosition, endPosition)); } /** * quoted-string = quote 1*(unescaped-char / escaped-char) quote * quote = '"' */ private ParseResult<String> parseQuotedString(int startPosition, int endPosition) { startPosition = trimLeftWhitespace(startPosition, endPosition); endPosition = trimRightWhitespace(startPosition, endPosition); if (!startsAndEndsWith(startPosition, endPosition, '"', '"')) { logError("quoted-string", "Expected opening and closing '\"'", startPosition); return ParseResult.error(); } int stringStart = startPosition + 1; int stringEnd = endPosition - 1; int stringTokenCount = charsInRange(stringStart, stringEnd); if (stringTokenCount < 1) { logError("quoted-string", "Invalid quoted-string", startPosition); return ParseResult.error(); } StringBuilder result = new StringBuilder(); for (int i = stringStart; i < stringEnd; i++) { ParseResult<String> unescapedChar = parseUnescapedChar(i, i + 1); if (unescapedChar.hasResult()) { result.append(unescapedChar.result()); continue; } ParseResult<String> escapedChar = parseEscapedChar(i, i + 2); if (escapedChar.hasResult()) { result.append(escapedChar.result()); ++i; continue; } ParseResult<String> escapedUnicodeSequence = parseEscapedUnicodeSequence(i, i + 6); if (escapedUnicodeSequence.hasResult()) { result.append(escapedUnicodeSequence.result()); i += 5; continue; } if (input.charAt(i) == '\\') { logError("quoted-string", "Unsupported escape sequence", i); } else { logError("quoted-string", "Unexpected character", i); } return ParseResult.error(); } return ParseResult.success(result.toString()); } /** * unescaped-char = %x20-21 / %x23-5B / %x5D-10FFFF */ private ParseResult<String> parseUnescapedChar(int startPosition, int endPosition) { for (int i = startPosition; i < endPosition; i++) { if (!isLegalUnescapedChar(input.charAt(i))) { logError("unescaped-char", "Invalid character in sequence", startPosition); return ParseResult.error(); } } return ParseResult.success(input.substring(startPosition, endPosition)); } private boolean isLegalUnescapedChar(char c) { return (c >= 0x20 && c <= 0x21) || (c >= 0x23 && c <= 0x5B) || (c >= 0x5D); } /** * escaped-char = escape ( * %x22 / ; " quotation mark U+0022 * %x5C / ; \ reverse solidus U+005C * %x2F / ; / solidus U+002F * %x62 / ; b backspace U+0008 * %x66 / ; f form feed U+000C * %x6E / ; n line feed U+000A * %x72 / ; r carriage return U+000D * %x74 / ; t tab U+0009 * %x75 4HEXDIG ) ; uXXXX U+XXXX (this is handled as part of parseEscapedUnicodeSequence) */ private ParseResult<String> parseEscapedChar(int startPosition, int endPosition) { if (endPosition > input.length()) { logError("escaped-char", "Invalid end position", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) != 2) { logError("escaped-char", "Invalid length", startPosition); return ParseResult.error(); } if (!startsWith(startPosition, '\\')) { logError("escaped-char", "Expected '\\'", startPosition); return ParseResult.error(); } char escapedChar = input.charAt(startPosition + 1); switch (escapedChar) { case '"': return ParseResult.success("\""); case '\\': return ParseResult.success("\\"); case '/': return ParseResult.success("/"); case 'b': return ParseResult.success("\b"); case 'f': return ParseResult.success("\f"); case 'n': return ParseResult.success("\n"); case 'r': return ParseResult.success("\r"); case 't': return ParseResult.success("\t"); default: logError("escaped-char", "Invalid escape sequence", startPosition); return ParseResult.error(); } } private ParseResult<String> parseEscapedUnicodeSequence(int startPosition, int endPosition) { if (endPosition > input.length()) { logError("escaped-unicode-sequence", "Invalid end position", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) != 6) { logError("escaped-unicode-sequence", "Invalid length", startPosition); return ParseResult.error(); } if (input.charAt(startPosition) != '\\') { logError("escaped-unicode-sequence", "Expected '\\'", startPosition); return ParseResult.error(); } char escapedChar = input.charAt(startPosition + 1); if (escapedChar != 'u') { logError("escaped-unicode-sequence", "Invalid escape sequence", startPosition); return ParseResult.error(); } String unicodePattern = input.substring(startPosition + 2, startPosition + 2 + 4); char unicodeChar; try { unicodeChar = (char) Integer.parseInt(unicodePattern, 16); } catch (NumberFormatException e) { logError("escaped-unicode-sequence", "Invalid unicode hex sequence", startPosition); return ParseResult.error(); } return ParseResult.success(String.valueOf(unicodeChar)); } /** * "*" */ private ParseResult<WildcardExpression> parseWildcardExpression(int startPosition, int endPosition) { return parseExpectedToken("star-expression", startPosition, endPosition, '*').mapResult(v -> new WildcardExpression()); } private int charsInRange(int startPosition, int endPosition) { return endPosition - startPosition; } private List<Integer> findCharacters(int startPosition, int endPosition, String symbol) { List<Integer> results = new ArrayList<>(); int start = startPosition; while (true) { int match = input.indexOf(symbol, start); if (match < 0 || match >= endPosition) { break; } results.add(match); start = match + 1; } return results; } private ParseResult<Character> parseExpectedToken(String parser, int startPosition, int endPosition, char expectedToken) { if (input.charAt(startPosition) != expectedToken) { logError(parser, "Expected '" + expectedToken + "'", startPosition); return ParseResult.error(); } if (charsInRange(startPosition, endPosition) != 1) { logError(parser, "Unexpected character", startPosition + 1); return ParseResult.error(); } return ParseResult.success(expectedToken); } private int trimLeftWhitespace(int startPosition, int endPosition) { while (input.charAt(startPosition) == ' ' && startPosition < endPosition - 1) { ++startPosition; } return startPosition; } private int trimRightWhitespace(int startPosition, int endPosition) { while (input.charAt(endPosition - 1) == ' ' && startPosition < endPosition - 1) { --endPosition; } return endPosition; } private boolean startsWith(int startPosition, char character) { return input.charAt(startPosition) == character; } private boolean endsWith(int endPosition, char character) { return input.charAt(endPosition - 1) == character; } private boolean startsAndEndsWith(int startPosition, int endPosition, char startChar, char endChar) { return startsWith(startPosition, startChar) && endsWith(endPosition, endChar); } private void logError(String parser, String message, int position) { log.debug(() -> parser + " at " + position + ": " + message); } }
3,611
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser/JmesPathVisitor.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.jmespath.parser; import software.amazon.awssdk.codegen.jmespath.component.AndExpression; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifier; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithContents; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithQuestionMark; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithoutContents; import software.amazon.awssdk.codegen.jmespath.component.ComparatorExpression; import software.amazon.awssdk.codegen.jmespath.component.CurrentNode; import software.amazon.awssdk.codegen.jmespath.component.Expression; import software.amazon.awssdk.codegen.jmespath.component.ExpressionType; import software.amazon.awssdk.codegen.jmespath.component.FunctionExpression; import software.amazon.awssdk.codegen.jmespath.component.IndexExpression; import software.amazon.awssdk.codegen.jmespath.component.Literal; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectHash; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectList; import software.amazon.awssdk.codegen.jmespath.component.NotExpression; import software.amazon.awssdk.codegen.jmespath.component.OrExpression; import software.amazon.awssdk.codegen.jmespath.component.ParenExpression; import software.amazon.awssdk.codegen.jmespath.component.PipeExpression; import software.amazon.awssdk.codegen.jmespath.component.SliceExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpressionRight; import software.amazon.awssdk.codegen.jmespath.component.WildcardExpression; /** * A visitor across all of the JMESPath expression types. This can be passed to any 'union' type visitors, like * {@link Expression#visit(JmesPathVisitor)}. */ public interface JmesPathVisitor { void visitExpression(Expression input); void visitSubExpression(SubExpression input); void visitSubExpressionRight(SubExpressionRight input); void visitIndexExpression(IndexExpression input); void visitBracketSpecifier(BracketSpecifier input); void visitBracketSpecifierWithContents(BracketSpecifierWithContents input); void visitSliceExpression(SliceExpression input); void visitBracketSpecifierWithoutContents(BracketSpecifierWithoutContents input); void visitBracketSpecifierWithQuestionMark(BracketSpecifierWithQuestionMark input); void visitComparatorExpression(ComparatorExpression input); void visitOrExpression(OrExpression input); void visitIdentifier(String input); void visitAndExpression(AndExpression input); void visitNotExpression(NotExpression input); void visitParenExpression(ParenExpression input); void visitWildcardExpression(WildcardExpression input); void visitMultiSelectList(MultiSelectList input); void visitMultiSelectHash(MultiSelectHash input); void visitExpressionType(ExpressionType asExpressionType); void visitLiteral(Literal input); void visitFunctionExpression(FunctionExpression input); void visitPipeExpression(PipeExpression input); void visitRawString(String input); void visitCurrentNode(CurrentNode input); void visitNumber(int input); }
3,612
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser/ParseResult.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.jmespath.parser; import java.util.function.Function; import software.amazon.awssdk.utils.Validate; /** * The result of a {@link Parser#parse(int, int)} call. This is either successful ({@link #success}) or an error * ({@link #error()}). */ public final class ParseResult<T> { private final T result; private ParseResult(T result) { this.result = result; } /** * Create a successful result with the provided value. */ public static <T> ParseResult<T> success(T result) { Validate.notNull(result, "result"); return new ParseResult<>(result); } /** * Create an error result. */ public static <T> ParseResult<T> error() { return new ParseResult<>(null); } /** * Convert the value in this parse result (if successful) using the provided function. */ public <U> ParseResult<U> mapResult(Function<T, U> mapper) { if (hasResult()) { return ParseResult.success(mapper.apply(result)); } else { return ParseResult.error(); } } /** * Returns true if the parse result was successful. */ public boolean hasResult() { return result != null; } /** * Returns the result of parsing. */ public T result() { Validate.validState(hasResult(), "Result not available"); return result; } }
3,613
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/jmespath/parser/util/CompositeParser.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.jmespath.parser.util; import java.util.function.Function; import software.amazon.awssdk.codegen.jmespath.parser.ParseResult; import software.amazon.awssdk.codegen.jmespath.parser.Parser; /** * A {@link Parser} that invokes a list of converters, returning the first converter that was successful. This is created * using {@link #firstTry(Parser)} and new converters are added via {@link #thenTry(Parser)}. */ public final class CompositeParser<T> implements Parser<T> { private final Parser<T> parser; private CompositeParser(Parser<T> parser) { this.parser = parser; } /** * Create a {@link CompositeParser} that tries the provided parser first. */ public static <T> CompositeParser<T> firstTry(Parser<T> parser) { return new CompositeParser<>(parser); } /** * Create a {@link CompositeParser} that tries the provided parser first, converting the result of that parser using the * provided function. */ public static <T, U> CompositeParser<U> firstTry(Parser<T> parser, Function<T, U> resultConverter) { return firstTry((start, end) -> parser.parse(start, end).mapResult(resultConverter)); } /** * Create a new {@link CompositeParser} that tries the provided parser after all previous parsers. */ public CompositeParser<T> thenTry(Parser<T> nextParser) { return new CompositeParser<>((start, end) -> { ParseResult<T> parse = parser.parse(start, end); if (!parse.hasResult()) { return nextParser.parse(start, end); } return parse; }); } /** * Create a new {@link CompositeParser} that tries the provided parser after all previous parsers, converting the result of * that parser using the provided function. */ public <S> CompositeParser<T> thenTry(Parser<S> nextParser, Function<S, T> resultConverter) { return thenTry((start, end) -> nextParser.parse(start, end).mapResult(resultConverter)); } @Override public ParseResult<T> parse(int startPosition, int endPosition) { return parser.parse(startPosition, endPosition); } }
3,614
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/emitters/GeneratorTaskParams.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; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.emitters.tasks.SharedModelsTaskParamsValidator; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.PoetExtension; /** * Parameters for generator tasks. */ public class GeneratorTaskParams { private static final Consumer<GeneratorTaskParams> TASK_PARAMS_VALIDATORS = new SharedModelsTaskParamsValidator(); private final IntermediateModel model; private final GeneratorPathProvider pathProvider; private final PoetExtension poetExtensions; private final Logger log = LoggerFactory.getLogger(GeneratorTaskParams.class); private GeneratorTaskParams(IntermediateModel model, GeneratorPathProvider pathProvider) { this.model = model; this.pathProvider = pathProvider; this.poetExtensions = new PoetExtension(model); } public static GeneratorTaskParams create(IntermediateModel model, String sourceDirectory, String testDirectory, String resourcesDirectory) { GeneratorPathProvider pathProvider = new GeneratorPathProvider(model, sourceDirectory, testDirectory, resourcesDirectory); GeneratorTaskParams params = new GeneratorTaskParams(model, pathProvider); TASK_PARAMS_VALIDATORS.accept(params); return params; } /** * @return Built intermediate model */ public IntermediateModel getModel() { return model; } /** * @return Provider for common paths. */ public GeneratorPathProvider getPathProvider() { return pathProvider; } /** * @return Extensions and convenience methods for Java Poet. */ public PoetExtension getPoetExtensions() { return poetExtensions; } /** * @return Logger */ public Logger getLog() { return log; } }
3,615
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/emitters/GeneratorPathProvider.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; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; /** * Common paths used by generator tasks. */ public class GeneratorPathProvider { private final IntermediateModel model; private final String sourceDirectory; private final String resourcesDirectory; private final String testDirectory; public GeneratorPathProvider(IntermediateModel model, String sourceDirectory, String testDirectory, String resourcesDirectory) { this.model = model; this.sourceDirectory = sourceDirectory; this.resourcesDirectory = resourcesDirectory; this.testDirectory = testDirectory; } public String getSourceDirectory() { return sourceDirectory; } public String getResourcesDirectory() { return resourcesDirectory; } public String getTestDirectory() { return testDirectory; } public String getModelDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullModelPackageName()); } public String getTransformDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullTransformPackageName()); } public String getClientDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullClientPackageName()); } public String getClientInternalDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullClientInternalPackageName()); } public String getPaginatorsDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullPaginatorsPackageName()); } public String getAuthorizerDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullAuthPolicyPackageName()); } public String getWaitersDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullWaitersPackageName()); } public String getWaitersInternalDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullWaitersInternalPackageName()); } public String getEndpointRulesDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullEndpointRulesPackageName()); } public String getEndpointRulesInternalDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullInternalEndpointRulesPackageName()); } public String getEndpointRulesInternalResourcesDirectory() { return resourcesDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullInternalEndpointRulesPackageName()); } public String getEndpointRulesTestDirectory() { return testDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullEndpointRulesPackageName()); } public String getAuthSchemeDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullAuthSchemePackageName()); } public String getAuthSchemeInternalDirectory() { return sourceDirectory + "/" + Utils.packageToDirectory(model.getMetadata().getFullInternalAuthSchemePackageName()); } }
3,616
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/emitters/CodeWriter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import static software.amazon.awssdk.codegen.internal.Constant.JAVA_FILE_NAME_SUFFIX; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.utils.StringUtils; /** * Formats the generated code and write it to the underlying file. The caller should call the flush * method to write the contents to the file. This class is intended to be used only by the code * generation system and is not to be used for public use. */ public class CodeWriter extends StringWriter { /** * The code transformation that should be applied before code is written. */ private final CodeTransformer codeWriteTransformer; /** * The code transformation that should be applied before source code is "compared" for equality. This is only used when * attempting to clobber a file that has already been generated. */ private final CodeTransformer codeComparisonTransformer = new LinkRemover(); private final String dir; private final String file; /** * Constructor to use for .java files. * @param dir * output directory where the file is to be created. * @param file * name of the file without .java suffix. */ public CodeWriter(String dir, String file) { this(dir, file, JAVA_FILE_NAME_SUFFIX, false); } public CodeWriter(String dir, String file, boolean disableFormatter) { this(dir, file, JAVA_FILE_NAME_SUFFIX, disableFormatter); } /** * Constructor to use for custom file suffixes. * * @param dir * output directory where the file is to be created. * @param file * name of the file excluding suffix. * @param fileNameSuffix * suffix to be appended at the end of file name. */ public CodeWriter(String dir, String file, String fileNameSuffix, boolean disableFormatter) { if (dir == null) { throw new IllegalArgumentException( "Output Directory cannot be null."); } if (file == null) { throw new IllegalArgumentException("File name cannot be null."); } if (fileNameSuffix == null) { throw new IllegalArgumentException("File name suffix cannot be null."); } if (!file.endsWith(fileNameSuffix)) { file = file + fileNameSuffix; } this.dir = dir; this.file = file; Utils.createDirectory(dir); if (disableFormatter) { codeWriteTransformer = CodeTransformer.chain(new UnusedImportRemover()); } else { codeWriteTransformer = CodeTransformer.chain(new UnusedImportRemover(), new JavaCodeFormatter()); } } /** * This method is expected to be called only once during the code generation process after the * template processing is done. */ @Override public void flush() { try { Path outputFile = Paths.get(dir, this.file); String contents = getBuffer().toString(); String formattedContents = codeWriteTransformer.apply(contents); if (fileSize(outputFile) == 0) { try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { writer.write(formattedContents); } } else { validateFileContentMatches(outputFile, formattedContents); } } catch (IOException e) { throw new IllegalStateException(e); } } private long fileSize(Path outputFile) throws IOException { try { return Files.size(outputFile); } catch (NoSuchFileException e) { return 0; } } private void validateFileContentMatches(Path outputFile, String newFileContents) throws IOException { byte[] currentFileBytes = Files.readAllBytes(outputFile); String currentFileContents = new String(currentFileBytes, StandardCharsets.UTF_8); String currentContentForComparison = codeComparisonTransformer.apply(currentFileContents); String newContentForComparison = codeComparisonTransformer.apply(newFileContents); if (!StringUtils.equals(currentContentForComparison, newContentForComparison)) { throw new IllegalStateException("Attempted to clobber existing file (" + outputFile + ") with a new file that has " + "different content. This may indicate forgetting to clean up old generated files " + "before running the generator?\n" + "Existing file: \n" + currentContentForComparison + "\n\n" + "New file: \n" + newContentForComparison); } } }
3,617
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/emitters/LinkRemover.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import java.util.regex.Pattern; /** * Removes HTML "anchor" tags from a string. This is used to compare files during clobbering while ignoring their documentation * links, which will pretty much always differ. */ public class LinkRemover implements CodeTransformer { private static final Pattern LINK_PATTERN = Pattern.compile("(<a[ \n]*/>|<a[> \n].*?</a>)", Pattern.DOTALL); @Override public String apply(String input) { return LINK_PATTERN.matcher(input).replaceAll(""); } }
3,618
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/emitters/GeneratorTask.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; import java.util.concurrent.RecursiveAction; /** * Base class for tasks. */ public abstract class GeneratorTask extends RecursiveAction { }
3,619
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/emitters/PoetGeneratorTask.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; import static software.amazon.awssdk.codegen.internal.Utils.closeQuietly; import static software.amazon.awssdk.codegen.poet.PoetUtils.buildJavaFile; import java.io.IOException; import java.io.Writer; import software.amazon.awssdk.codegen.poet.ClassSpec; public final class PoetGeneratorTask extends GeneratorTask { private final Writer writer; private final ClassSpec classSpec; private final String fileHeader; public PoetGeneratorTask(String outputDirectory, String fileHeader, ClassSpec classSpec) { this (outputDirectory, fileHeader, classSpec, false); } public PoetGeneratorTask(String outputDirectory, String fileHeader, ClassSpec classSpec, boolean disableFormatting) { this.fileHeader = fileHeader; this.writer = new CodeWriter(outputDirectory, classSpec.className().simpleName(), disableFormatting); this.classSpec = classSpec; } @Override public void compute() { try { writer.write(fileHeader); writer.write("\n"); buildJavaFile(classSpec).writeTo(writer); writer.flush(); } catch (IOException e) { throw new RuntimeException(String.format("Error creating class %s", classSpec.className().simpleName()), e); } finally { closeQuietly(writer); } } }
3,620
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/emitters/JavaCodeFormatter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.TextEdit; import software.amazon.awssdk.codegen.internal.Constant; /** * Formats the generated java source code. Uses Eclipse JDT core plugin from the Eclipse SDK. */ @SuppressWarnings("unchecked") public class JavaCodeFormatter implements CodeTransformer { private static final Map<String, Object> DEFAULT_FORMATTER_OPTIONS; static { DEFAULT_FORMATTER_OPTIONS = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, DefaultCodeFormatterConstants.FALSE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_COMPACT, DefaultCodeFormatterConstants.INDENT_DEFAULT)); // Formats custom file headers if provided DEFAULT_FORMATTER_OPTIONS .put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, DefaultCodeFormatterConstants.TRUE); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "130"); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "120"); } private final CodeFormatter codeFormatter; /** * Creates a JavaCodeFormatter using the default formatter options. */ public JavaCodeFormatter() { this(new HashMap<>()); } /** * Creates a JavaCodeFormatter using the default formatter options and * optionally applying user provided options on top. * * @param overrideOptions user provided options to apply on top of defaults */ public JavaCodeFormatter(final Map<String, Object> overrideOptions) { Map formatterOptions = new HashMap<>(DEFAULT_FORMATTER_OPTIONS); if (overrideOptions != null) { formatterOptions.putAll(overrideOptions); } this.codeFormatter = ToolFactory.createCodeFormatter(formatterOptions, ToolFactory.M_FORMAT_EXISTING); } @Override public String apply(String contents) { TextEdit edit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, Constant.LF); if (edit == null) { // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost return contents; } IDocument document = new Document(contents); try { edit.apply(document); } catch (Exception e) { throw new RuntimeException( "Failed to format the generated source code.", e); } return document.get(); } }
3,621
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/emitters/CodeTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import java.util.function.Function; import java.util.stream.Stream; public interface CodeTransformer extends Function<String, String> { static CodeTransformer chain(CodeTransformer... processors) { return input -> Stream.of(processors).map(p -> (Function<String, String>) p) .reduce(Function.identity(), Function::andThen).apply(input); } @Override String apply(String input); }
3,622
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/emitters/SimpleGeneratorTask.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; import static software.amazon.awssdk.codegen.internal.Utils.closeQuietly; import java.io.IOException; import java.io.Writer; import java.util.function.Supplier; /** * Simple generator task that writes a string to a file. */ public final class SimpleGeneratorTask extends GeneratorTask { private final Writer writer; private final String fileHeader; private final String fileName; private final Supplier<String> contents; public SimpleGeneratorTask(String outputDirectory, String fileName, String fileHeader, Supplier<String> contents) { this.fileHeader = fileHeader; this.writer = new CodeWriter(outputDirectory, fileName); this.fileName = fileName; this.contents = contents; } public SimpleGeneratorTask(String outputDirectory, String fileName, String filenameSuffix, String fileHeader, Supplier<String> contents) { this.fileHeader = fileHeader; this.writer = new CodeWriter(outputDirectory, fileName, filenameSuffix, false); this.fileName = fileName; this.contents = contents; } @Override public void compute() { try { writer.write(fileHeader + "\n"); writer.write(contents.get()); writer.flush(); } catch (IOException e) { throw new RuntimeException(String.format("Error creating file %s", fileName), e); } finally { closeQuietly(writer); } } }
3,623
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/emitters/UnusedImportRemover.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import static java.util.stream.Collectors.toSet; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UnusedImportRemover implements CodeTransformer { private static Pattern IMPORT_PATTERN = Pattern.compile("import(?:\\s+)(?:static\\s+)?(.*)(?:\\s*);"); @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } private Function<String, String> removeImportFunction(String importToRemove) { return c -> c.replaceFirst(findSpecificImportRegex(importToRemove), ""); } private Set<String> findUnusedImports(String content) { return findImports(content).stream().filter(isUnused(content)).collect(toSet()); } private List<String> findImports(String content) { Matcher m = IMPORT_PATTERN.matcher(content); List<String> imports = new ArrayList<>(); while (m.find()) { imports.add(m.group(1)); } return imports; } private String removeAllImports(String content) { return content.replaceAll(IMPORT_PATTERN.pattern(), ""); } private Predicate<String> isUnused(String content) { String contentWithoutImports = removeAllImports(content); return importToCheck -> !importToCheck.contains("*") && (isNotReferenced(contentWithoutImports, importToCheck) || isDuplicate(content, importToCheck)); } private boolean isNotReferenced(String contentWithoutImports, String importToCheck) { String symbol = importToCheck.substring(importToCheck.lastIndexOf('.') + 1); return !Pattern.compile(String.format("\\b%s\\b", symbol)).matcher(contentWithoutImports).find(); } private boolean isDuplicate(String content, String importToCheck) { Matcher m = Pattern.compile(findSpecificImportRegex(importToCheck)).matcher(content); return m.find() && m.find(); } private String findSpecificImportRegex(String specificImport) { return String.format("import(?:\\s+)(?:static )?(?:%s)(?:\\s*);", specificImport); } }
3,624
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/CommonClientGeneratorTasks.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.Arrays; 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.BaseClientBuilderClass; import software.amazon.awssdk.codegen.poet.builder.BaseClientBuilderInterface; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationBuilderClass; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationClass; /** * Task for classes shared by {@link AsyncClientGeneratorTasks} and {@link SyncClientGeneratorTasks}. */ public class CommonClientGeneratorTasks extends BaseGeneratorTasks { public CommonClientGeneratorTasks(GeneratorTaskParams dependencies) { super(dependencies); } @Override protected List<GeneratorTask> createTasks() throws Exception { return Arrays.asList(createBaseBuilderTask(), createBaseBuilderInterfaceTask(), createServiceClientConfigurationTask(), createServiceClientConfigurationBuilderTask()); } private GeneratorTask createBaseBuilderTask() throws IOException { return createPoetGeneratorTask(new BaseClientBuilderClass(model)); } private GeneratorTask createBaseBuilderInterfaceTask() throws IOException { return createPoetGeneratorTask(new BaseClientBuilderInterface(model)); } private GeneratorTask createServiceClientConfigurationTask() throws IOException { return createPoetGeneratorTask(new ServiceClientConfigurationClass(model)); } private GeneratorTask createServiceClientConfigurationBuilderTask() throws IOException { return createPoetGeneratorTask(new ServiceClientConfigurationBuilderClass(model)); } }
3,625
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/SharedModelsTaskParamsValidator.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.File; import java.util.function.Consumer; import software.amazon.awssdk.codegen.emitters.CodeWriter; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.config.customization.ShareModelConfig; /** * This validates that services with the {@link CustomizationConfig#shareModelConfig} attribute specified are being generated * after the service they are attempting to share models with. This ensures that the services are kept together in the same * module and allows us to verify (in {@link CodeWriter}) that their models are compatible with each other. */ public class SharedModelsTaskParamsValidator implements Consumer<GeneratorTaskParams> { @Override public void accept(GeneratorTaskParams params) { ShareModelConfig sharedModelService = params.getModel().getCustomizationConfig().getShareModelConfig(); if (sharedModelService != null) { // Validate the service we're sharing models with has been generated already. File modelPackageDirectory = new File(params.getPathProvider().getModelDirectory()); if (!modelPackageDirectory.exists()) { String error = String.format("Unable to share models with '%s', because that service's models haven't been " + "generated yet ('%s' doesn't exist). You must generate that service before " + "generating '%s'.", sharedModelService, modelPackageDirectory, params.getModel().getMetadata().getDescriptiveServiceName()); throw new IllegalStateException(error); } } } }
3,626
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,627
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,628
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,629
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,630
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,631
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,632
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,633
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,634
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,635
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,636
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,637
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,638
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,639
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,640
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,641
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,642
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,643
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,644
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,645
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,646
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,647
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,648
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,649
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,650
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,651
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,652
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,653
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,654
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,655
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,656
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,657
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,658
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,659
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,660
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,661
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,662
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,663
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,664
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,665
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,666
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,667
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,668
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,669
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,670
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,671
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,672
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,673
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,674
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,675
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,676
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,677
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,678
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,679
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,680
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,681
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,682
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,683
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,684
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,685
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,686
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,687
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,688
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,689
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,690
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,691
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,692
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,693
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,694
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,695
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,696
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,697
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,698
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,699